You are here

function fancy_file_delete_unmanaged_update_view in Fancy File Delete 8

Same name and namespace in other branches
  1. 7 fancy_file_delete.module \fancy_file_delete_unmanaged_update_view()

Updates the view and populates the unmanaged files table.

File

./fancy_file_delete.module, line 114

Code

function fancy_file_delete_unmanaged_update_view() {

  // Get all files from default standard file dir.
  $dir = \Drupal::state()
    ->get('file_public_path') ?: 'sites/default/files';
  $files = file_scan_directory($dir, '(.*?)');

  // Go through each one and replace this with a proper uri.
  foreach ($files as $file) {
    $file_check[] = str_replace($dir . '/', 'public://', $file->uri);
  }

  // All the files in the file_managed table.
  $query = \Drupal::database()
    ->select('file_managed', 'fm')
    ->fields('fm', [
    'uri',
  ])
    ->execute();

  // Set this to a numeric keyed array so we can check this easier.
  foreach ($query
    ->fetchAll() as $result) {
    $db_check[] = $result->uri;
  }

  // Get the files not in the file_managed table.
  $results = array_diff($file_check, $db_check);

  // Go through and add this to the batch.
  if (count($results) > 0) {
    $um = \Drupal::database()
      ->select('unmanaged_files', 'um')
      ->fields('um', [
      'path',
    ])
      ->condition('path', [
      $results,
    ], 'IN')
      ->execute()
      ->fetchAll();

    // Go in and check it and set it as an array to check.
    $um_check = [];
    foreach ($um as $res) {
      $um_check[] = $res->path;
    }

    // Again check the difference, only want ones not in the table.
    $um_final = array_diff($results, $um_check);
    if (count($um_final) > 0) {
      $insert_unmanaged = \Drupal::database()
        ->insert('unmanaged_files')
        ->fields([
        'path',
      ]);
      foreach ($um_final as $key => $value) {
        $insert_unmanaged
          ->values([
          'path' => $value,
        ]);
      }
      $insert_unmanaged
        ->execute();
    }
  }
}