FieldNormalizer.php in Commerce Cart API 8
File
src/Normalizer/FieldNormalizer.php
View source
<?php
namespace Drupal\commerce_cart_api\Normalizer;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\serialization\Normalizer\FieldNormalizer as CoreFieldNormalizer;
class FieldNormalizer extends CoreFieldNormalizer {
protected $routeMatch;
public function __construct(RouteMatchInterface $route_match) {
$this->routeMatch = $route_match;
}
public function supportsNormalization($data, $format = NULL) {
$supported = parent::supportsNormalization($data, $format);
if ($supported) {
$route = $this->routeMatch
->getRouteObject();
return $route && $route
->hasRequirement('_cart_api');
}
return $supported;
}
public function normalize($field_item, $format = NULL, array $context = []) {
$cardinality = $field_item
->getFieldDefinition()
->getFieldStorageDefinition()
->getCardinality();
$data = parent::normalize($field_item, $format, $context);
if ($cardinality > 1 || $cardinality == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
return $data;
}
if (empty($data)) {
return NULL;
}
return reset($data);
}
public function denormalize($data, $class, $format = NULL, array $context = []) {
if (!is_array($data)) {
$data = [
$data,
];
}
return parent::denormalize($data, $class, $format, $context);
}
}