Skip to content

Instantly share code, notes, and snippets.

@onesixromcom
Created May 12, 2023 05:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onesixromcom/ba8ce1858af4a85d31283800ea87d4d2 to your computer and use it in GitHub Desktop.
Save onesixromcom/ba8ce1858af4a85d31283800ea87d4d2 to your computer and use it in GitHub Desktop.
<?php
namespace Drupal\my_module\Normalizer;
use Drupal\commerce_product\Entity\ProductVariationInterface;
use Drupal\Core\TypedData\TypedDataInternalPropertiesHelper;
use Drupal\serialization\Normalizer\NormalizerBase;
/**
* Converts typed data objects to arrays.
*/
class VariationCartNormalizer extends NormalizerBase {
/**
* The interface or class that this Normalizer supports.
*
* @var string
*/
protected $supportedInterfaceOrClass = ProductVariationInterface::class;
/**
* {@inheritdoc}
*/
public function normalize($entity, $format = NULL, array $context = []) {
$context += [
'account' => NULL,
];
$attributes = [];
foreach (TypedDataInternalPropertiesHelper::getNonInternalProperties($entity->getTypedData()) as $name => $field_items) {
if ($field_items->access('view', $context['account'])) {
$attributes[$name] = $this->serializer->normalize($field_items, $format, $context);
}
}
$images = $entity->getProduct()->field_product_images;
if (!empty($images) && isset($images->entity)) {
$original_image = $images->entity->getFileUri();
$style = \Drupal::entityTypeManager()
->getStorage('image_style')
->load('thumbnail');
$destination = $style->buildUri($original_image);
if (!file_exists($destination)) {
$style->createDerivative($original_image, $destination);
}
$attributes['image'] = $style->buildUrl($original_image);
}
return $attributes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment