You are here

public function ServiceAuditFilesNotInDatabase::auditfilesNotInDatabaseBatchAddProcessFile in Audit Files 8.2

Same name and namespace in other branches
  1. 8.3 src/ServiceAuditFilesNotInDatabase.php \Drupal\auditfiles\ServiceAuditFilesNotInDatabase::auditfilesNotInDatabaseBatchAddProcessFile()
  2. 4.x src/ServiceAuditFilesNotInDatabase.php \Drupal\auditfiles\ServiceAuditFilesNotInDatabase::auditfilesNotInDatabaseBatchAddProcessFile()

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 435

Class

ServiceAuditFilesNotInDatabase
Define all methods that are used on Files not in database functionality.

Namespace

Drupal\auditfiles

Code

public function auditfilesNotInDatabaseBatchAddProcessFile($filepathname) {
  $user = $this->entityTypeManager
    ->getStorage('user')
    ->load($this->currentUser
    ->id());
  $file = new \StdClass();
  $file->uid = $user
    ->get('uid')->value;
  $file->filename = trim(basename($filepathname));
  $file->uri = $this
    ->auditfilesBuildUri($filepathname);
  $real_filenamepath = $this->fileSystem
    ->realpath($file->uri);
  $file->filemime = $this->fileMimeTypeGuesser
    ->guess($real_filenamepath);
  $file->filesize = filesize($real_filenamepath);
  $file->status = FILE_STATUS_PERMANENT;
  $file->timestamp = $this->time
    ->getCurrentTime();
  $uuid = $this->uuidService
    ->generate();
  $connection = $this->connection;
  $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 = $this->connection
      ->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)) {
      $this
        ->messenger()
        ->addStatus($this->stringTranslation
        ->translate('Failed to add %file to the database.', [
        '%file' => $filepathname,
      ]));
    }
    else {
      $this
        ->messenger()
        ->addStatus($this->stringTranslation
        ->translate('Sucessfully added %file to the database.', [
        '%file' => $filepathname,
      ]));
    }
  }
  else {
    $this
      ->messenger()
      ->addStatus($this->stringTranslation
      ->translate('The file %file is already in the database.', [
      '%file' => $filepathname,
    ]));
  }
}