You are here

public function UnmanagedFilesService::updateView in Fancy File Delete 2.0.x

Updates the view and populates the unmanaged files table.

File

src/UnmanagedFilesService.php, line 55

Class

UnmanagedFilesService
Class UnmanagedFilesService.

Namespace

Drupal\fancy_file_delete

Code

public function updateView() {

  // Get all files from default standard public & private directories.
  $directories = $this
    ->getChosenDirs();
  $files = $this
    ->getFiles($directories);

  // Remove files from the batch that are not in our latest check.
  if (count($files)) {
    $this->database
      ->delete('unmanaged_files')
      ->condition('path', $files, 'NOT IN')
      ->execute();
  }
  else {
    $this->database
      ->delete('unmanaged_files')
      ->execute();
  }

  // Go through and add this to the batch.
  if (count($files) > 0) {

    // I changed this to use array chunk & db query for performance.
    // see issue: https://www.drupal.org/node/2637028
    $files_chunk = array_chunk($files, ceil(count($files) / 4), TRUE);
    foreach ($files_chunk as $filez) {
      $result = $this->database
        ->select('unmanaged_files', 'uf')
        ->fields('uf', [
        'path',
      ])
        ->condition('path', $filez, 'NOT IN')
        ->execute()
        ->fetchAll();

      // Check if this is a first run.
      if (count($result) === 0) {
        $new = TRUE;
      }
      else {
        $umsplit[] = $result;
        $new = FALSE;
      }
    }

    // Insert if new.
    if ($new) {
      foreach ($files_chunk as $chunk) {
        foreach ($chunk as $fpath) {
          $new_files[] = $fpath;
        }
      }
      if (isset($new_files)) {

        // Insert records
        foreach ($new_files as $value) {
          $un_file = UnmanagedFiles::create([
            'path' => $value,
          ]);
          $un_file
            ->save();
        }
      }
    }
    else {
      $um = array_merge(...$umsplit);

      // 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($files, $um_check);
      if (count($um_final) > 0) {

        // Insert records
        foreach ($um_final as $value) {
          $un_file = UnmanagedFiles::create([
            'path' => $value,
          ]);
          $un_file
            ->save();
        }
      }
    }
  }
}