function tmgmt_file_tmgmt_job_delete

Implements hook_tmgmt_job_delete().

File

translators/tmgmt_file/tmgmt_file.module, line 65
Module file of the translation management test module.

Code

function tmgmt_file_tmgmt_job_delete(JobInterface $job) {

  // Ignore jobs that don't have a file translator.
  if (!$job
    ->hasTranslator() || $job
    ->getTranslator()
    ->getPluginId() != 'file') {
    return;
  }

  // Check if there are any files that need to be deleted.
  // @todo There doesn't seem to be an API function for this...
  $args = array(
    ':module' => 'tmgmt_file',
    ':type' => 'tmgmt_job',
    ':id' => $job
      ->id(),
  );
  $result = \Drupal::database()
    ->query('SELECT fid FROM {file_usage} WHERE module = :module and type = :type and id = :id', $args);
  $fids = $result
    ->fetchCol();
  if (!empty($fids)) {

    // Remove file usage record.

    /** @var \Drupal\file\FileUsage\FileUsageInterface $file_usage */
    $file_usage = \Drupal::service('file.usage');
    foreach (File::loadMultiple($fids) as $file) {
      $file_usage
        ->delete($file, 'tmgmt_file', 'tmgmt_job', $job
        ->id());

      // If this was the last usage, FileUsageBase marks the file as temporary
      // for delayed deletion. Because we know it is not needed, delete the file
      // immediately.
      $usage = $file_usage
        ->listUsage($file);
      if (empty($usage)) {
        $file
          ->delete();
      }
    }
  }
}