You are here

public function AvatarKitDownloadUtility::createFile in Avatar Kit 8.2

Creates a file entity from a PSR response.

Parameters

\Psr\Http\Message\ResponseInterface $response: File to download.

string $default_filename: The desirable file name. Extension may be substituted.

Return value

\Drupal\file\FileInterface|null The new file entity, or null if the file could not be downloaded.

Overrides AvatarKitDownloadUtilityInterface::createFile

File

src/AvatarKitDownloadUtility.php, line 91

Class

AvatarKitDownloadUtility
Utility for creating Drupal files from responses.

Namespace

Drupal\avatars

Code

public function createFile(ResponseInterface $response, string $default_filename) : ?FileInterface {
  $stream = $response
    ->getBody();

  // Save stream to temporary file.
  // Following block is file_unmanaged_save_data() but without the Drupal
  // message.
  $temp_filepath = $this->fileSystem
    ->tempnam('temporary://', 'temp');
  if (\file_put_contents($temp_filepath, $stream) === FALSE) {
    $this->logger
      ->notice('Unable to create temporary file: %filename.', [
      '%filename' => $temp_filepath,
    ]);
    return NULL;
  }
  [
    'dirname' => $directory,
    'filename' => $filename,
  ] = pathinfo($default_filename);
  $final_filename = $directory . DIRECTORY_SEPARATOR . $filename . '.' . $this
    ->getExtension($response);

  // Create destination directory if it doesn't exist.
  if (file_prepare_directory($directory, FILE_CREATE_DIRECTORY) !== TRUE) {
    $this->logger
      ->notice('Unable to create directory: %directory.', [
      '%directory' => $directory,
    ]);
    return NULL;
  }

  // Move the temporary file to the final destination.
  try {
    $final_filepath = $this
      ->moveFile($temp_filepath, $final_filename, FILE_EXISTS_REPLACE);
  } catch (\Exception $e) {

    // file_unmanaged_move() logs its own errors.
    return NULL;
  }

  // Create file entity.
  // file_save_data() used as inspiration.

  /** @var \Drupal\file\FileInterface $file */
  $file = $this->fileStorage
    ->create();
  $file
    ->setFileUri($final_filepath);
  $file
    ->setPermanent();

  // `$violation_count = $this->logViolations($file);`.
  // Normally you would return NULL here. But if file_entity module is
  // installed, it will cause voilations since there is no bundle set.
  try {
    $file
      ->save();
  } catch (\Exception $e) {
    $this->logger
      ->notice('Error saving file: %message.', [
      '%message' => $e
        ->getMessage(),
    ]);
  }
  return $file;
}