View source
<?php
namespace Drupal\consumer_image_styles\Normalizer;
use Drupal\consumer_image_styles\ImageStylesProviderInterface;
use Drupal\consumer_image_styles\Normalizer\Value\ImageVariantItemNormalizerValue;
use Drupal\consumer_image_styles\Normalizer\Value\ImageNormalizerValue;
use Drupal\consumers\Negotiator;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\file\Entity\File;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\jsonapi\LinkManager\LinkManager;
use Drupal\jsonapi\Normalizer\ContentEntityNormalizer;
use Drupal\jsonapi\Normalizer\Value\NullFieldNormalizerValue;
use Drupal\jsonapi\ResourceType\ResourceTypeRepositoryInterface;
class ImageEntityNormalizer extends ContentEntityNormalizer {
protected $supportedInterfaceOrClass = File::class;
protected $formats = [
'api_json',
];
protected $linkManager;
protected $resourceTypeRepository;
protected $entityTypeManager;
protected $consumerNegotiator;
protected $imageStylesProvider;
public function __construct(LinkManager $link_manager, ResourceTypeRepositoryInterface $resource_type_repository, EntityTypeManagerInterface $entity_type_manager, Negotiator $consumer_negotiator, ImageStylesProviderInterface $imageStylesProvider) {
parent::__construct($link_manager, $resource_type_repository, $entity_type_manager);
$this->consumerNegotiator = $consumer_negotiator;
$this->imageStylesProvider = $imageStylesProvider;
}
public function supportsNormalization($data, $format = NULL) {
return parent::supportsNormalization($data, $format) && strpos($data
->get('filemime')->value, 'image/') !== FALSE;
}
public function supportsDenormalization($data, $type, $format = NULL) {
return FALSE;
}
public function normalize($entity, $format = NULL, array $context = []) {
$file_entity_values = parent::normalize($entity, $format, $context);
$variants = $this
->buildVariantValues($entity, $context);
return new ImageNormalizerValue($variants, $file_entity_values);
}
public function denormalize($data, $class, $format = NULL, array $context = []) {
throw new \Exception('Unsupported denormalizer.');
}
protected function buildVariantValues(EntityInterface $entity, array $context = []) {
$request = empty($context['request']) ? NULL : $context['request'];
$consumer = $this->consumerNegotiator
->negotiateFromRequest($request);
if (!$consumer) {
$access = $entity
->access('view', $context['account'], TRUE);
return new NullFieldNormalizerValue($access, 'attributes');
}
$uri = $entity
->get('uri')->value;
$get_image_url = function ($image_style) use ($uri) {
return file_create_url($image_style
->buildUrl($uri));
};
$image_styles = $this->imageStylesProvider
->loadStyles($consumer);
$keys = array_keys($image_styles);
$values = array_map($get_image_url, array_values($image_styles));
$value = array_combine($keys, $values);
return new ImageVariantItemNormalizerValue($value, new CacheableMetadata());
}
}