Skip to content

Instantly share code, notes, and snippets.

@onesixromcom
Created June 14, 2023 08:59
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/bcc813af2934a82d781d1c97b10f30bf to your computer and use it in GitHub Desktop.
Save onesixromcom/bcc813af2934a82d781d1c97b10f30bf to your computer and use it in GitHub Desktop.
VariationCartNormalizer.php with whitelisted fields for response
<?php
namespace Drupal\my_commerce\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 {
private $whitelistFields = [
'price',
'title',
'variation_id',
'product_id',
'uuid',
];
/**
* 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 (in_array($name, $this->whitelistFields)) {
if ($field_items->access('view', $context['account'])) {
$attributes[$name] = $this->serializer->normalize($field_items, $format, $context);
}
}
}
return $attributes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment