You are here

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

Same name and namespace in other branches
  1. 8.4 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|bool Returns file ID wrapped in target or false.

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 753

Class

DrupalUserProcessor
Handles processing of a user from LDAP to Drupal.

Namespace

Drupal\ldap_user\Processor

Code

private function saveUserPicture(FieldItemListInterface $field, $ldapUserPicture) {

  // Create tmp file to get image format and derive extension.
  $fileName = uniqid();
  $unmanagedFile = file_directory_temp() . '/' . $fileName;
  file_put_contents($unmanagedFile, $ldapUserPicture);
  $image_type = exif_imagetype($unmanagedFile);
  $extension = image_type_to_extension($image_type, FALSE);
  unlink($unmanagedFile);
  $fieldSettings = $field
    ->getFieldDefinition()
    ->getItemDefinition()
    ->getSettings();
  $tokenService = \Drupal::token();
  $directory = $tokenService
    ->replace($fieldSettings['file_directory']);
  $fullDirectoryPath = $fieldSettings['uri_scheme'] . '://' . $directory;
  if (!is_dir(\Drupal::service('file_system')
    ->realpath($fullDirectoryPath))) {
    \Drupal::service('file_system')
      ->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(),
    ];
  }
  else {

    // 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 FALSE;
  }
}