You are here

private function AjaxController::createFileKey in S3 File System CORS Upload 8

Create a new file key if the original one already exists.

1 call to AjaxController::createFileKey()
AjaxController::getKey in src/Controller/AjaxController.php
Return the file key (i.e. the path and name).

File

src/Controller/AjaxController.php, line 136

Class

AjaxController
Default controller for the s3fs_cors module.

Namespace

Drupal\s3fs_cors\Controller

Code

private function createFileKey($directory, $file_name) {

  // Remove the root folder from the file directory if specified.
  $root_folder = '';
  $config = $this
    ->config('s3fs.settings');
  if (!empty($config
    ->get('root_folder'))) {
    $root_folder = $config
      ->get('root_folder') . '/';
    $directory = str_replace($root_folder, '', $directory);
  }
  $separator = '/';

  // A URI or path may already have a trailing slash or look like "public://".
  if (substr($directory, -1) == '/') {
    $separator = '';
  }

  // Extract the file base name and the file extension (with leading period).
  $base_name = substr($file_name, 0, strrpos($file_name, '.'));
  $extension = substr($file_name, strrpos($file_name, '.'));
  $key_base = $root_folder . $directory . $separator . $base_name;

  // Look in the s3fs cache to find files with a key like this.
  $uri_base = 's3://' . $directory . $separator . $base_name;
  $records = $this->database
    ->select('s3fs_file', 's')
    ->fields('s', [
    'uri',
  ])
    ->condition('uri', $this->database
    ->escapeLike($uri_base) . '%', 'LIKE')
    ->execute()
    ->fetchCol();

  // Process the results array to extract the suffix values.
  $results = [];
  foreach ($records as $record) {
    $suffix = str_replace([
      $uri_base,
      $extension,
    ], '', $record);
    if ($suffix) {

      // Drop the leading underscore char.
      $suffix = (int) substr($suffix, 1);
      $results[$suffix] = $record;
    }
  }

  // Find a key suffix that can be used by looking for a gap in suffix values.
  for ($suffix = 0; $suffix < count($results); $suffix++) {
    if (!isset($results[$suffix])) {
      break;
    }
  }

  // If we drop out the bottom then suffix will be one greater then largest
  // existing value.  Create a trial key and test.
  $trial_key = $key_base . '_' . $suffix . $extension;
  if ($this
    ->s3FileExists($trial_key)) {

    // Destination file already exists, then cache is stale. Rebuild required.
    $this->logger
      ->info('S3fs cache table rebuild required (key %key missing)', [
      '%key' => $trial_key,
    ]);

    // Look for a new suffix value greater then the largest already known.
    $suffix = max(array_keys($results));
    do {
      $trial_key = $key_base . '_' . ++$suffix . $extension;
    } while ($this
      ->s3FileExists($trial_key));
  }
  return $trial_key;
}