EntityReferenceNormalizer.php in Commerce Cart API 8
File
src/Normalizer/EntityReferenceNormalizer.php
View source
<?php
namespace Drupal\commerce_cart_api\Normalizer;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\serialization\Normalizer\EntityReferenceFieldItemNormalizer;
class EntityReferenceNormalizer extends EntityReferenceFieldItemNormalizer {
protected $routeMatch;
protected $allowedFields;
public function __construct(EntityRepositoryInterface $entity_repository, RouteMatchInterface $route_match, array $commerce_cart_api) {
parent::__construct($entity_repository);
$this->routeMatch = $route_match;
$this->allowedFields = $commerce_cart_api['normalized_entity_references'];
}
public function supportsNormalization($data, $format = NULL) {
$supported = parent::supportsNormalization($data, $format);
if ($supported) {
$route = $this->routeMatch
->getRouteObject();
$name = $data
->getFieldDefinition()
->getName();
return $route && in_array($name, $this
->getSupportedFields(), TRUE) && $route
->hasRequirement('_cart_api');
}
return FALSE;
}
public function normalize($field_item, $format = NULL, array $context = []) {
assert($field_item instanceof EntityReferenceItem);
$entity = $field_item
->get('entity')
->getValue();
return $this->serializer
->normalize($entity, $format, $context);
}
protected function getSupportedFields() {
return $this->allowedFields;
}
}