View source
<?php
namespace Drupal\image\Controller;
use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityDisplayRepositoryInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Image\ImageFactory;
use Drupal\Core\Render\Element\StatusMessages;
use Drupal\Core\Render\RendererInterface;
use Drupal\image\Plugin\Field\FieldType\ImageItem;
use Drupal\Core\TempStore\PrivateTempStoreFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class QuickEditImageController extends ControllerBase {
protected $tempStore;
protected $renderer;
protected $imageFactory;
protected $entityDisplayRepository;
protected $fileSystem;
public function __construct(RendererInterface $renderer, ImageFactory $image_factory, PrivateTempStoreFactory $temp_store_factory, EntityDisplayRepositoryInterface $entity_display_repository = NULL, FileSystemInterface $file_system = NULL) {
$this->renderer = $renderer;
$this->imageFactory = $image_factory;
$this->tempStore = $temp_store_factory
->get('quickedit');
if (!$entity_display_repository) {
@trigger_error('The entity_display.repository service must be passed to QuickEditImageController::__construct(), it is required before Drupal 9.0.0. See https://www.drupal.org/node/2549139.', E_USER_DEPRECATED);
$entity_display_repository = \Drupal::service('entity_display.repository');
}
$this->entityDisplayRepository = $entity_display_repository;
if (!$file_system) {
@trigger_error('The file_system service must be passed to QuickEditImageController::__construct(), it is required before Drupal 9.0.0. See https://www.drupal.org/node/3006851.', E_USER_DEPRECATED);
$file_system = \Drupal::service('file_system');
}
$this->fileSystem = $file_system;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('renderer'), $container
->get('image.factory'), $container
->get('tempstore.private'), $container
->get('entity_display.repository'), $container
->get('file_system'));
}
public function upload(EntityInterface $entity, $field_name, $langcode, $view_mode_id) {
$field = $this
->getField($entity, $field_name, $langcode);
$field_validators = $field
->getUploadValidators();
$field_settings = $field
->getFieldDefinition()
->getSettings();
$destination = $field
->getUploadLocation();
if ($field_settings['max_resolution'] || $field_settings['min_resolution']) {
$field_validators['file_validate_image_resolution'] = [
$field_settings['max_resolution'],
$field_settings['min_resolution'],
];
}
if (isset($destination) && !$this->fileSystem
->prepareDirectory($destination, FileSystemInterface::CREATE_DIRECTORY)) {
return new JsonResponse([
'main_error' => $this
->t('The destination directory could not be created.'),
'errors' => '',
]);
}
$result = file_save_upload('image', $field_validators, $destination);
if (is_array($result) && $result[0]) {
$file = $result[0];
$image = $this->imageFactory
->get($file
->getFileUri());
$value = $entity->{$field_name}
->getValue();
$value[0]['target_id'] = $file
->id();
$value[0]['width'] = $image
->getWidth();
$value[0]['height'] = $image
->getHeight();
$entity->{$field_name}
->setValue($value);
$entity_view_mode_ids = array_keys($this->entityDisplayRepository
->getViewModes($entity
->getEntityTypeId()));
if (in_array($view_mode_id, $entity_view_mode_ids, TRUE)) {
$output = $entity->{$field_name}
->view($view_mode_id);
}
else {
$mode_id_parts = explode('-', $view_mode_id, 2);
$module = reset($mode_id_parts);
$args = [
$entity,
$field_name,
$view_mode_id,
$langcode,
];
$output = $this
->moduleHandler()
->invoke($module, 'quickedit_render_field', $args);
}
$this->tempStore
->set($entity
->uuid(), $entity);
$data = [
'fid' => $file
->id(),
'html' => $this->renderer
->renderRoot($output),
];
return new JsonResponse($data);
}
else {
$messages = StatusMessages::renderMessages('error');
return new JsonResponse([
'errors' => $this->renderer
->render($messages),
'main_error' => $this
->t('The image failed validation.'),
]);
}
}
public function getInfo(EntityInterface $entity, $field_name, $langcode, $view_mode_id) {
$field = $this
->getField($entity, $field_name, $langcode);
$settings = $field
->getFieldDefinition()
->getSettings();
$info = [
'alt' => $field->alt,
'title' => $field->title,
'alt_field' => $settings['alt_field'],
'title_field' => $settings['title_field'],
'alt_field_required' => $settings['alt_field_required'],
'title_field_required' => $settings['title_field_required'],
];
$response = new CacheableJsonResponse($info);
$response
->addCacheableDependency($entity);
return $response;
}
protected function getField(EntityInterface $entity, $field_name, $langcode) {
if (!$entity instanceof ContentEntityInterface) {
throw new BadRequestHttpException('Requested Entity is not a Content Entity.');
}
$field_list = $entity
->getTranslation($langcode)
->get($field_name);
if (!$field_list) {
throw new BadRequestHttpException('Requested Field does not exist.');
}
if ($field_list
->isEmpty()) {
$field = $field_list
->appendItem();
}
else {
$field = $entity
->getTranslation($langcode)
->get($field_name)
->first();
}
if (!$field instanceof ImageItem) {
throw new BadRequestHttpException('Requested Field is not of type "image".');
}
return $field;
}
}