You are here

function ServiceAuditFilesNotInDatabase::auditfiles_not_in_database_batch_add_process_file in Audit Files 8

Adds the specified file to the database.

Parameters

string $filepathname: The full pathname to the file to add to the database.

File

src/ServiceAuditFilesNotInDatabase.php, line 340
providing the service that used in not in database functionality.

Class

ServiceAuditFilesNotInDatabase

Namespace

Drupal\auditfiles

Code

function auditfiles_not_in_database_batch_add_process_file($filepathname) {
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()
    ->id());
  $file = new \StdClass();
  $file->uid = $user
    ->get('uid')->value;
  $file->filename = trim(basename($filepathname));
  $file->uri = file_build_uri($filepathname);
  $real_filenamepath = drupal_realpath($file->uri);
  $file->filemime = \Drupal::service('file.mime_type.guesser')
    ->guess($real_filenamepath);
  $file->filesize = filesize($real_filenamepath);
  $file->status = FILE_STATUS_PERMANENT;
  $file->timestamp = REQUEST_TIME;
  $uuid_service = \Drupal::service('uuid');
  $uuid = $uuid_service
    ->generate();
  $connection = Database::getConnection();
  $query = $connection
    ->select('file_managed', 'fm');
  $query
    ->condition('fm.uri', $file->uri);
  $query
    ->fields('fm', [
    'fid',
  ]);
  $existing_file = $query
    ->execute()
    ->fetchField();
  if (empty($existing_file)) {
    $results = \Drupal::database()
      ->merge('file_managed')
      ->key([
      'fid' => NULL,
    ])
      ->fields([
      'fid' => NULL,
      'uuid' => $uuid,
      'langcode' => 'en',
      'uid' => $file->uid,
      'filename' => $file->filename,
      'uri' => $file->uri,
      'filemime' => $file->filemime,
      'filesize' => $file->filesize,
      'status' => $file->status,
      'created' => $file->timestamp,
      'changed' => $file->timestamp,
    ])
      ->execute();
    if (empty($results)) {
      drupal_set_message(t('Failed to add %file to the database.', [
        '%file' => $filepathname,
      ]));
    }
    else {
      drupal_set_message(t('Sucessfully added %file to the database.', [
        '%file' => $filepathname,
      ]));
    }
  }
  else {
    drupal_set_message(t('The file %file is already in the database.', [
      '%file' => $filepathname,
    ]), 'error');
  }
}