public function PhotosUpload::saveImage in Album Photos 6.0.x
Same name and namespace in other branches
- 8.5 src/PhotosUpload.php \Drupal\photos\PhotosUpload::saveImage()
- 8.4 src/PhotosUpload.php \Drupal\photos\PhotosUpload::saveImage()
Attach image file to PhotosImage entity.
Parameters
\Drupal\file\FileInterface $file: The file entity.
Return value
bool TRUE if image saved successfully.
Overrides PhotosUploadInterface::saveImage
1 call to PhotosUpload::saveImage()
- PhotosUpload::unzip in src/
PhotosUpload.php - Unzip archive of image files.
File
- src/
PhotosUpload.php, line 227
Class
- PhotosUpload
- Functions to help with uploading images to albums.
Namespace
Drupal\photosCode
public function saveImage(FileInterface $file) {
$config = $this->configFactory
->get('photos.settings');
// @todo maybe pass file object and array of other vars.
if ($file
->id() && isset($file->album_id)) {
$fid = $file
->id();
$albumId = $file->album_id;
$album_photo_limit = $config
->get('album_photo_limit');
$photo_count = $this->connection
->query("SELECT count FROM {photos_album} WHERE album_id = :album_id", [
':album_id' => $albumId,
])
->fetchField();
if ($album_photo_limit && $photo_count >= $album_photo_limit) {
return FALSE;
}
// Prep image title.
if (isset($file->title) && !empty($file->title)) {
$title = $file->title;
}
else {
// Cleanup filename and use as title.
$title = $this
->cleanTitle($file
->getFilename());
}
// Create photos_image entity.
/** @var \Drupal\Core\Image\Image $image */
$image = $this->imageFactory
->get($file
->getFileUri());
$defaultWeight = $this->connection
->select('photos_image_field_data', 'i')
->fields('i', [
'weight',
])
->condition('i.album_id', $albumId)
->orderBy('i.weight', 'DESC')
->execute()
->fetchField();
if ($image
->isValid()) {
$newPhotosImageEntity = [
'album_id' => $albumId,
'title' => $title,
'weight' => isset($file->weight) ? $file->weight : $defaultWeight + 1,
'description' => isset($file->des) ? $file->des : '',
];
// Check if photos_image has default field_image.
$uploadField = $config
->get('multi_upload_default_field');
$uploadFieldParts = explode(':', $uploadField);
$field = isset($uploadFieldParts[0]) ? $uploadFieldParts[0] : 'field_image';
$allBundleFields = $this->entityFieldManager
->getFieldDefinitions('photos_image', 'photos_image');
if (isset($allBundleFields[$field])) {
$fieldType = $allBundleFields[$field]
->getType();
if ($fieldType == 'image') {
$newPhotosImageEntity[$field] = [
'target_id' => $fid,
'alt' => $title,
'title' => $title,
'width' => $image
->getWidth(),
'height' => $image
->getHeight(),
];
}
else {
// Check media fields.
if ($fieldType == 'entity_reference') {
$mediaField = isset($uploadFieldParts[1]) ? $uploadFieldParts[1] : '';
$mediaBundle = isset($uploadFieldParts[2]) ? $uploadFieldParts[2] : '';
if ($mediaField && $mediaBundle) {
// Create new media entity.
$values = [
'bundle' => $mediaBundle,
'uid' => $this->currentUser
->id(),
];
$values[$mediaField] = [
'target_id' => $file
->id(),
];
$media = Media::create($values);
// @todo media name?
$media
->setName('Photo ' . $file
->id())
->setPublished()
->save();
// Set photos_image media reference field.
$newPhotosImageEntity[$field] = [
'target_id' => $media
->id(),
];
}
}
}
}
$photosImage = PhotosImage::create($newPhotosImageEntity);
try {
$photosImage
->save();
if ($photosImage && $photosImage
->id()) {
if (isset($fieldType) && $fieldType == 'image') {
// Move image to correct directory.
$fieldThirdPartySettings = $allBundleFields[$field]
->getThirdPartySettings('filefield_paths');
if (!empty($fieldThirdPartySettings) && $fieldThirdPartySettings['enabled']) {
// Get path from filefield_paths.
$tokenData = [
'file' => $file,
$photosImage
->getEntityTypeId() => $photosImage,
];
$name = $file
->getFilename();
if (!empty($fieldThirdPartySettings['file_name']['value'])) {
$name = filefield_paths_process_string($fieldThirdPartySettings['file_name']['value'], $tokenData, $fieldThirdPartySettings['file_name']['options']);
}
// Process filepath.
$path = filefield_paths_process_string($fieldThirdPartySettings['file_path']['value'], $tokenData, $fieldThirdPartySettings['file_path']['options']);
$fileUri = $this->streamWrapperManager
->normalizeUri($this->streamWrapperManager
->getScheme($file
->getFileUri()) . '://' . $path . DIRECTORY_SEPARATOR . $name);
}
else {
// Get path from field settings.
$fieldSettings = $allBundleFields[$field]
->getSettings();
$uploadLocation = $fieldSettings['file_directory'];
$uploadLocation = PlainTextOutput::renderFromHtml($this->token
->replace($uploadLocation, []));
$uploadLocation = $this->streamWrapperManager
->getScheme($file
->getFileUri()) . '://' . $uploadLocation;
$this->fileSystem
->prepareDirectory($uploadLocation, FileSystemInterface::CREATE_DIRECTORY);
$fileUri = "{$uploadLocation}/{$file->getFilename()}";
$fileUri = $this->fileSystem
->getDestinationFilename($fileUri, FileSystemInterface::EXISTS_RENAME);
// Move the file.
$this->fileSystem
->move($file
->getFileUri(), $fileUri, FileSystemInterface::EXISTS_ERROR);
}
// Set the correct URI and save the file.
$file
->setFileUri($fileUri);
$file
->save();
}
if ($config
->get('photos_user_count_cron')) {
$user = $this->currentUser;
PhotosAlbum::setCount('user_image', $photosImage
->getOwnerId() ? $photosImage
->getOwnerId() : $user
->id());
PhotosAlbum::setCount('node_album', $albumId);
}
// Save file and add file usage.
$this->fileUsage
->add($file, 'photos', 'node', $albumId);
// Check admin setting for maximum image resolution.
if ($photos_size_max = $config
->get('photos_size_max')) {
// Will scale image if needed.
file_validate_image_resolution($file, $photos_size_max);
// Get new height and width for field values.
if (isset($fieldType)) {
$image = $this->imageFactory
->get($file
->getFileUri());
if ($fieldType == 'image') {
$image_files = $photosImage
->get($field)
->getValue();
$image_files[0]['height'] = $image
->getHeight();
$image_files[0]['width'] = $image
->getWidth();
// Save new height and width.
$photosImage
->set($field, $image_files);
$photosImage
->save();
}
else {
if (isset($media) && isset($mediaField)) {
$image_files = $media
->get($mediaField)
->getValue();
$image_files[0]['height'] = $image
->getHeight();
$image_files[0]['width'] = $image
->getWidth();
// Save new height and width.
$media
->set($mediaField, $image_files);
$media
->save();
}
}
}
}
return TRUE;
}
} catch (EntityStorageException $e) {
watchdog_exception('photos', $e);
}
}
}
return FALSE;
}