You are here

class ImageEntityNormalizer in Consumer Image Styles 8.2

Same name and namespace in other branches
  1. 8 src/Normalizer/ImageEntityNormalizer.php \Drupal\consumer_image_styles\Normalizer\ImageEntityNormalizer

Hierarchy

Expanded class hierarchy of ImageEntityNormalizer

1 string reference to 'ImageEntityNormalizer'
consumer_image_styles.services.yml in ./consumer_image_styles.services.yml
consumer_image_styles.services.yml
1 service uses ImageEntityNormalizer
serializer.normalizer.image_entity.consumer_image_styles in ./consumer_image_styles.services.yml
Drupal\consumer_image_styles\Normalizer\ImageEntityNormalizer

File

src/Normalizer/ImageEntityNormalizer.php, line 18

Namespace

Drupal\consumer_image_styles\Normalizer
View source
class ImageEntityNormalizer extends ContentEntityNormalizer {

  /**
   * The interface or class that this Normalizer supports.
   *
   * @var string
   */
  protected $supportedInterfaceOrClass = File::class;

  /**
   * The formats that the Normalizer can handle.
   *
   * @var array
   */
  protected $formats = [
    'api_json',
  ];

  /**
   * The link manager.
   *
   * @var \Drupal\jsonapi\LinkManager\LinkManager
   */
  protected $linkManager;

  /**
   * The JSON API resource type repository.
   *
   * @var \Drupal\jsonapi\ResourceType\ResourceTypeRepositoryInterface
   */
  protected $resourceTypeRepository;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * @var \Drupal\consumers\Negotiator
   */
  protected $consumerNegotiator;

  /**
   * @var \Drupal\consumer_image_styles\ImageStylesProviderInterface
   */
  protected $imageStylesProvider;

  /**
   * Constructs an EntityNormalizer object.
   *
   * @param \Drupal\jsonapi\LinkManager\LinkManager $link_manager
   *   The link manager.
   * @param \Drupal\jsonapi\ResourceType\ResourceTypeRepositoryInterface $resource_type_repository
   *   The JSON API resource type repository.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\consumers\Negotiator $consumer_negotiator
   *   The consumer negotiator.
   * @param \Drupal\consumer_image_styles\ImageStylesProviderInterface
   *   Image styles utility.
   */
  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;
  }

  /**
   * {@inheritdoc}
   */
  public function supportsNormalization($data, $format = NULL) {

    // It is very tricky to detect if a file entity is an image or not. This is
    // typically done using a special field type to point to this entity.
    // However we don't have access to that in here. Besides we want this to
    // apply when requesting a listing of file entities as well, not only via
    // includes. For all this we'll do string matching against the mimetype.
    return parent::supportsNormalization($data, $format) && strpos($data
      ->get('filemime')->value, 'image/') !== FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function supportsDenormalization($data, $type, $format = NULL) {

    // We do not need to do anything special about denormalization. Passing here
    // will have the serializer use the normal content entity normalizer.
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  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);
  }

  /**
   * {@inheritdoc}
   */
  public function denormalize($data, $class, $format = NULL, array $context = []) {

    // This should never be called.
    throw new \Exception('Unsupported denormalizer.');
  }

  /**
   * @param \Drupal\Core\Entity\EntityInterface $entity
   * @param array $context
   *
   * @return \Drupal\jsonapi\Normalizer\Value\ValueExtractorInterface
   */
  protected function buildVariantValues(EntityInterface $entity, array $context = []) {
    $request = empty($context['request']) ? NULL : $context['request'];
    $consumer = $this->consumerNegotiator
      ->negotiateFromRequest($request);

    // Bail-out if no consumer is found.
    if (!$consumer) {
      $access = $entity
        ->access('view', $context['account'], TRUE);
      return new NullFieldNormalizerValue($access, 'attributes');
    }

    // Prepare some utils.
    $uri = $entity
      ->get('uri')->value;
    $get_image_url = function ($image_style) use ($uri) {
      return file_create_url($image_style
        ->buildUrl($uri));
    };

    // Generate derivatives only for the found ones.
    $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());
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CacheableNormalizerInterface::SERIALIZATION_CONTEXT_CACHEABILITY constant Name of key for bubbling cacheability metadata via serialization context.
EntityNormalizer::getFieldItemInstance protected function Gets a field item instance for use with SerializedColumnNormalizerTrait.
EntityNormalizer::getFieldNames protected function Gets the field names for the given entity.
EntityNormalizer::getFields protected function Gets the field names for the given entity. 1
EntityNormalizer::prepareInput protected function Prepares the input data to create the entity.
EntityNormalizer::serializeField protected function Serializes a given field. 1
ImageEntityNormalizer::$consumerNegotiator protected property
ImageEntityNormalizer::$entityTypeManager protected property The entity type manager. Overrides EntityNormalizer::$entityTypeManager
ImageEntityNormalizer::$formats protected property The formats that the Normalizer can handle. Overrides EntityNormalizer::$formats
ImageEntityNormalizer::$imageStylesProvider protected property
ImageEntityNormalizer::$linkManager protected property The link manager. Overrides EntityNormalizer::$linkManager
ImageEntityNormalizer::$resourceTypeRepository protected property The JSON API resource type repository. Overrides EntityNormalizer::$resourceTypeRepository
ImageEntityNormalizer::$supportedInterfaceOrClass protected property The interface or class that this Normalizer supports. Overrides EntityNormalizer::$supportedInterfaceOrClass
ImageEntityNormalizer::buildVariantValues protected function
ImageEntityNormalizer::denormalize public function Denormalizes data back into an object of the given class. Overrides EntityNormalizer::denormalize
ImageEntityNormalizer::normalize public function Normalizes an object into a set of arrays/scalars. Overrides EntityNormalizer::normalize
ImageEntityNormalizer::supportsDenormalization public function Implements \Symfony\Component\Serializer\Normalizer\DenormalizerInterface::supportsDenormalization() Overrides NormalizerBase::supportsDenormalization
ImageEntityNormalizer::supportsNormalization public function Checks whether the given class is supported for normalization by this normalizer. Overrides NormalizerBase::supportsNormalization
ImageEntityNormalizer::__construct public function Constructs an EntityNormalizer object. Overrides EntityNormalizer::__construct
NormalizerBase::$format protected property List of formats which supports (de-)normalization. 3
NormalizerBase::addCacheableDependency protected function Adds cacheability if applicable.
NormalizerBase::checkFormat protected function Checks if the provided format is supported by this normalizer. 2
SerializedColumnNormalizerTrait::checkForSerializedStrings protected function Checks if there is a serialized string for a column.
SerializedColumnNormalizerTrait::dataHasStringForSerializeColumn protected function Checks if the data contains string value for serialize column.
SerializedColumnNormalizerTrait::getCustomSerializedPropertyNames protected function Gets the names of all properties the plugin treats as serialized data.
SerializedColumnNormalizerTrait::getSerializedPropertyNames protected function Gets the names of all serialized properties.