ww_publish-8.x-1.x-dev/src/Image.php
src/Image.php
<?php
namespace Drupal\ww_publish;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Logger\RfcLogLevel;
use Drupal\media\Entity\Media;
use Drupal\media\Entity\MediaType;
class Image {
use FieldTrait;
/**
* The image content component.
*
* @var object
*/
private $imageContent;
/**
* @var \Drupal\ww_publish\Message
*/
private $message;
/**
* WoodWing Studio article ID field.
*
* @var string
*/
private $idField;
/**
* Configuration of the ww_publish module.
*
* @var \Drupal\Core\Config\Config
*/
private $config;
/**
* A logger instance.
*
* @var \Psr\Log\LoggerInterface
*/
private $logger;
/**
* The media type.
*
* @var \Drupal\media\MediaTypeInterface
*/
protected $mediaType;
/**
* Constructor.
*
* @param string $media_type
* The media type.
* @param object $image_content
* The image content component.
* @param \Drupal\ww_publish\Message $message
* Article metadata.
* @param \Drupal\Core\Config\Config $config
* Configuration of the ww_publish module.
* @param \Psr\Log\LoggerInterface $logger
* A logger instance.
*/
public function __construct(string $media_type, $image_content, Message $message, $config, $logger) {
$this->imageContent = $image_content;
$this->message = $message;
$this->mediaType = MediaType::load($media_type);
$this->idField = $this->mediaType->getThirdPartySetting('ww_publish', 'id_field');
$this->config = $config;
$this->logger = $logger;
}
/**
* Get Media entity of the image.
*
* @return \Drupal\Core\Entity\EntityInterface
* @throws \Drupal\Core\Entity\EntityStorageException
*/
public function getMediaEntity() {
if (!$this->idField) {
throw new \Exception('ID field media type third party setting not configured');
}
if (empty($this->imageContent->image->id)) {
throw new \Exception('Received invalid image content structure, must have ->image->id property');
}
// Find the media entity.
$imageIds = \Drupal::entityQuery('media')
->accessCheck(FALSE)
->condition('bundle', $this->mediaType->id())
->condition($this->idField, $this->imageContent->image->id)
->execute();
if ($this->config->get('debug_mode'))
$this->logger->debug('Media ID Field: @id_field, WW ID: @ww_id, image IDs: <pre><code>@image_ids</code></pre>', ['@id_field' => $this->idField, '@ww_id' => $this->imageContent, '@image_ids' => print_r($imageIds, TRUE)]);
if (empty($imageIds)) {
return $this->createMediaEntity();
} else {
return Media::load(reset($imageIds));
}
}
/**
* Create a new image media entity.
*
* @return \Drupal\Core\Entity\EntityInterface
* @throws \Drupal\Core\Entity\EntityStorageException
*/
private function createMediaEntity() {
$image = $this->imageContent->image;
$file_path = '';
// If there is cropper data, try to fetch the cropped image, otherwise fallback to the uncropped one.
if (isset($image->cropper) && isset($image->cropper->x, $image->cropper->y, $image->cropper->width, $image->cropper->height)) {
$file_path = $this->message->getImage("{$image->id}_cx_{$image->cropper->x}_cy_{$image->cropper->y}_cw_{$image->cropper->width}_ch_{$image->cropper->height}");
}
if (!$file_path) {
$file_path = $this->message->getImage($image->id);
}
if (!$file_path) {
return NULL;
}
$file_data = file_get_contents($file_path);
// Create the directory if it does not exist.
$directory_path = 'public://' . $this->config->get('ww_path') . '/' . date('Y-m');
$fileSystem = \Drupal::service('file_system');
$fileSystem->prepareDirectory($directory_path, FileSystemInterface::CREATE_DIRECTORY);
$destination = $directory_path . '/' . $this->message->getArticleMetadata()->getFileName($image->id, $file_path);
if ($this->config->get('debug_mode'))
$this->logger->debug('File destination: <pre><code>@destination</code></pre>', ['@destination' => print_r($destination, TRUE)]);
$file = \Drupal::service('file.repository')->writeData($file_data, $destination);
if (!empty($image->focuspoint->x) && !empty($image->focuspoint->y) && \Drupal::moduleHandler()->moduleExists('focal_point')) {
$image_file = \Drupal::service('image.factory')->get($file->getFileUri());
if ($image_file) {
$image_width = $image_file->getWidth();
$image_height = $image_file->getHeight();
if ($image_height && $image_width) {
$x = (int) ($image_width * $image->focuspoint->x);
$y = (int) ($image_height * $image->focuspoint->y);
$crop_type = \Drupal::config('focal_point.settings')->get('crop_type');
/** @var \Drupal\focal_point\FocalPointManagerInterface $focal_point_manager */
$focal_point_manager = \Drupal::service('focal_point.manager');
$crop = $focal_point_manager->getCropEntity($file, $crop_type);
$current_crop = \Drupal::service('focal_point.manager')->getCropEntity($file, $crop_type);
if ($current_crop && $current_crop->position() != ['x' => $x, 'y' => $y]) {
$crop->setPosition($x, $y);
$crop->save();
}
}
}
}
$alt = $this->imageContent->caption[0]->insert ?? '';
if (strlen($alt) > 512) {
$alt = substr($alt, 0, 512);
$this->logger->warning('The alt text of the following image has been cut as per the image settings: WW ID: @ww_id', ['@ww_id' => $image->id]);
}
$mediaData = [
'bundle' => $this->mediaType->id(),
'name' => $file->getFilename(),
'status' => 1,
'uid' => $this->message->getArticleMetadata()->getAuthor() ?: 0,
$this->mediaType->getSource()->getSourceFieldDefinition($this->mediaType)->getName() => [
'target_id' => $file->id(),
'alt' => $alt,
],
$this->idField => $image->id,
];
if ($this->config->get('debug_mode'))
$this->logger->debug('Media data: <pre><code>@media_data</code></pre>', ['@media_data' => print_r($mediaData, TRUE)]);
$media = Media::create($mediaData);
$media->save();
return $media;
}
}
