You are here

public function FancyFileDeleteBatch::process in Fancy File Delete 2.0.x

Batch process function.

File

src/FancyFileDeleteBatch.php, line 121

Class

FancyFileDeleteBatch
Class FancyFileDeleteBatch.

Namespace

Drupal\fancy_file_delete

Code

public function process($fid, $force, &$context) {

  // Update our progress information.
  if (!isset($context['sandbox']['progress'])) {
    $context['sandbox']['progress'] = 0;
  }
  $context['sandbox']['progress']++;

  // Manual / Orphan Delete.
  if (is_numeric($fid)) {
    $file = File::load($fid);
    if ($file) {
      if ($force) {

        // Remove these from the DB.
        $this->database
          ->delete('file_managed')
          ->condition('fid', $fid)
          ->execute();
        $this->database
          ->delete('file_usage')
          ->condition('fid', $fid)
          ->execute();

        // Now Delete the file completely.
        // Skip file api and just delete the entity, quicker.
        $controller = $this->entityTypeManager
          ->getStorage('file');
        $entity = $controller
          ->loadMultiple([
          $fid,
        ]);
        $controller
          ->delete($entity);
      }
      else {
        $result = $file
          ->delete();
        if (is_array($result)) {

          // The file is still being referenced.
          // So it can not be forcefully deleted.
          // Notify the user instead.
          $context['results']['error'][] = array(
            'fid' => $fid,
            'message' => $this
              ->t('The file with fid#%fid cannot be delete because it
            is still referenced in the file_usage table. %file_usage', array(
              '%fid' => $fid,
              '%file_usage' => print_r($result, TRUE),
            )),
          );
        }
        else {
          $context['results'][] = $fid;
        }
      }
    }
  }
  else {

    // @todo fix this to be the new way.
    $this->database
      ->delete('unmanaged_files')
      ->condition('path', $fid)
      ->execute();
    $this->fileSystem
      ->delete($fid);
    $context['results'][] = $fid;
  }

  // Set the processing message.
  $context['message'] = $this
    ->t('Now cleansing the system of fid#%fid', [
    '%fid' => $fid,
  ]);
}