VariationCartNormalizer.php with whitelisted fields for response
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_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