You are here

public static function FileMimeApplyForm::process in File MIME 8

Batch process callback.

File

src/Form/FileMimeApplyForm.php, line 78

Class

FileMimeApplyForm
Implements the file MIME apply settings form.

Namespace

Drupal\filemime\Form

Code

public static function process(&$context) {
  if (!isset($context['results']['processed'])) {
    $context['results']['processed'] = 0;
    $context['results']['updated'] = 0;
    $context['sandbox']['count'] = self::count();
    $context['sandbox']['schemes'] = \Drupal::service('stream_wrapper_manager')
      ->getWrappers(StreamWrapperInterface::LOCAL);
  }
  $files = \Drupal::database()
    ->select('file_managed')
    ->fields('file_managed', [
    'fid',
    'filemime',
    'uri',
  ])
    ->range($context['results']['processed'], 1)
    ->execute();
  foreach ($files as $file) {

    // Only operate on local stream URIs, which should represent file names.
    $scheme = \Drupal::service('file_system')
      ->uriScheme($file->uri);
    if ($scheme && isset($context['sandbox']['schemes'][$scheme])) {
      $filemime = \Drupal::service('file.mime_type.guesser')
        ->guess($file->uri);
      if ($file->filemime != $filemime) {
        $variables = [
          '%old' => $file->filemime,
          '%new' => $filemime,
          '%url' => $file->uri,
        ];

        // Fully load file object.
        $file = File::load($file->fid);
        $file->filemime = $filemime;
        $file
          ->save();
        $context['results']['updated']++;
        $context['message'] = t('Updated MIME type from %old to %new for %url.', $variables);
        \Drupal::logger('filemime')
          ->notice('Updated MIME type from %old to %new for %url.', $variables);
      }
    }
    $context['results']['processed']++;
    $context['finished'] = $context['results']['processed'] / $context['sandbox']['count'];
  }
}