You are here

protected function ImageEntityNormalizer::buildVariantValues in Consumer Image Styles 8

Same name and namespace in other branches
  1. 8.2 src/Normalizer/ImageEntityNormalizer.php \Drupal\consumer_image_styles\Normalizer\ImageEntityNormalizer::buildVariantValues()

Parameters

\Drupal\Core\Entity\EntityInterface $entity:

array $context:

Return value

\Drupal\jsonapi\Normalizer\Value\ValueExtractorInterface

1 call to ImageEntityNormalizer::buildVariantValues()
ImageEntityNormalizer::normalize in src/Normalizer/ImageEntityNormalizer.php
Normalizes an object into a set of arrays/scalars.

File

src/Normalizer/ImageEntityNormalizer.php, line 124

Class

ImageEntityNormalizer

Namespace

Drupal\consumer_image_styles\Normalizer

Code

protected function buildVariantValues(EntityInterface $entity, array $context = []) {
  $request = empty($context['request']) ? NULL : $context['request'];
  $consumer = $this->consumerNegotiator
    ->negotiateFromRequest($request);
  $output = new NullFieldNormalizerValue();
  if ($consumer) {

    // Get the image styles from the consumer.
    $image_style_ids = array_map(function ($field_value) {
      return $field_value['target_id'];
    }, $consumer
      ->get('image_styles')
      ->getValue());
    $uri = $entity
      ->get('uri')->value;
    $image_style_storage = $this->entityTypeManager
      ->getStorage('image_style');
    $urls = array_map(function ($image_style_id) use ($image_style_storage, $uri) {

      /** @var \Drupal\image\Entity\ImageStyle $image_style */
      $image_style = $image_style_storage
        ->load($image_style_id);
      return file_create_url($image_style
        ->buildUrl($uri));
    }, $image_style_ids);
    $value = array_combine($image_style_ids, $urls);
    $output = new ImageVariantItemNormalizerValue($value);
    $output
      ->addCacheableDependency($consumer);
  }
  return $output;
}