Created
May 12, 2023 05:36
-
-
Save onesixromcom/ba8ce1858af4a85d31283800ea87d4d2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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