You are here

private function DrupalUserProcessor::saveUserPicture in Lightweight Directory Access Protocol (LDAP) 8.4

Same name and namespace in other branches
  1. 8.3 ldap_user/src/Processor/DrupalUserProcessor.php \Drupal\ldap_user\Processor\DrupalUserProcessor::saveUserPicture()

Save the user's picture.

Parameters

\Drupal\Core\Field\FieldItemListInterface $field: The field attached to the user.

string $ldapUserPicture: The picture itself.

Return value

array|null Nullable array of form ['target_id' => 123].

1 call to DrupalUserProcessor::saveUserPicture()
DrupalUserProcessor::userPictureFromLdapEntry in ldap_user/src/Processor/DrupalUserProcessor.php
Process user picture from LDAP entry.

File

ldap_user/src/Processor/DrupalUserProcessor.php, line 542

Class

DrupalUserProcessor
Handles processing of a user from LDAP to Drupal.

Namespace

Drupal\ldap_user\Processor

Code

private function saveUserPicture(FieldItemListInterface $field, string $ldapUserPicture) : ?array {

  // Create tmp file to get image format and derive extension.
  $fileName = uniqid('', FALSE);
  $unmanagedFile = $this->fileSystem
    ->getTempDirectory() . '/' . $fileName;
  file_put_contents($unmanagedFile, $ldapUserPicture);

  // @todo Declare dependency on exif or resolve it.
  $image_type = exif_imagetype($unmanagedFile);
  $extension = image_type_to_extension($image_type, FALSE);
  unlink($unmanagedFile);
  $fieldSettings = $field
    ->getFieldDefinition()
    ->getItemDefinition()
    ->getSettings();
  $directory = $this->token
    ->replace($fieldSettings['file_directory']);
  $fullDirectoryPath = $fieldSettings['uri_scheme'] . '://' . $directory;
  $realpath = $this->fileSystem
    ->realpath($fullDirectoryPath);
  if ($realpath && !is_dir((string) $realpath)) {
    $this->fileSystem
      ->mkdir($fullDirectoryPath, NULL, TRUE);
  }
  $managed_file = file_save_data($ldapUserPicture, $fullDirectoryPath . '/' . $fileName . '.' . $extension);
  $validators = [
    'file_validate_is_image' => [],
    'file_validate_image_resolution' => [
      $fieldSettings['max_resolution'],
    ],
    'file_validate_size' => [
      $fieldSettings['max_filesize'],
    ],
  ];
  $errors = file_validate($managed_file, $validators);
  if ($managed_file && empty(file_validate($managed_file, $validators))) {
    return [
      'target_id' => $managed_file
        ->id(),
    ];
  }

  // @todo Verify file garbage collection.
  foreach ($errors as $error) {
    $this->detailLog
      ->log('File upload error for user image with validation error @error', [
      '@error' => $error,
    ]);
  }
  return NULL;
}