annotate vendor/symfony/serializer/Normalizer/AbstractNormalizer.php @ 14:1fec387a4317

Update Drupal core to 8.5.2 via Composer
author Chris Cannam
date Mon, 23 Apr 2018 09:46:53 +0100
parents 7a779792577d
children c2387f117808
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 /*
Chris@0 4 * This file is part of the Symfony package.
Chris@0 5 *
Chris@0 6 * (c) Fabien Potencier <fabien@symfony.com>
Chris@0 7 *
Chris@0 8 * For the full copyright and license information, please view the LICENSE
Chris@0 9 * file that was distributed with this source code.
Chris@0 10 */
Chris@0 11
Chris@0 12 namespace Symfony\Component\Serializer\Normalizer;
Chris@0 13
Chris@0 14 use Symfony\Component\Serializer\Exception\CircularReferenceException;
Chris@0 15 use Symfony\Component\Serializer\Exception\InvalidArgumentException;
Chris@0 16 use Symfony\Component\Serializer\Exception\LogicException;
Chris@0 17 use Symfony\Component\Serializer\Exception\RuntimeException;
Chris@0 18 use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
Chris@0 19 use Symfony\Component\Serializer\Mapping\AttributeMetadataInterface;
Chris@0 20 use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
Chris@0 21 use Symfony\Component\Serializer\SerializerAwareInterface;
Chris@0 22
Chris@0 23 /**
Chris@0 24 * Normalizer implementation.
Chris@0 25 *
Chris@0 26 * @author Kévin Dunglas <dunglas@gmail.com>
Chris@0 27 */
Chris@0 28 abstract class AbstractNormalizer extends SerializerAwareNormalizer implements NormalizerInterface, DenormalizerInterface, SerializerAwareInterface
Chris@0 29 {
Chris@14 30 use ObjectToPopulateTrait;
Chris@14 31
Chris@0 32 const CIRCULAR_REFERENCE_LIMIT = 'circular_reference_limit';
Chris@0 33 const OBJECT_TO_POPULATE = 'object_to_populate';
Chris@0 34 const GROUPS = 'groups';
Chris@14 35 const ATTRIBUTES = 'attributes';
Chris@14 36 const ALLOW_EXTRA_ATTRIBUTES = 'allow_extra_attributes';
Chris@0 37
Chris@0 38 /**
Chris@0 39 * @var int
Chris@0 40 */
Chris@0 41 protected $circularReferenceLimit = 1;
Chris@0 42
Chris@0 43 /**
Chris@0 44 * @var callable
Chris@0 45 */
Chris@0 46 protected $circularReferenceHandler;
Chris@0 47
Chris@0 48 /**
Chris@0 49 * @var ClassMetadataFactoryInterface|null
Chris@0 50 */
Chris@0 51 protected $classMetadataFactory;
Chris@0 52
Chris@0 53 /**
Chris@0 54 * @var NameConverterInterface|null
Chris@0 55 */
Chris@0 56 protected $nameConverter;
Chris@0 57
Chris@0 58 /**
Chris@0 59 * @var array
Chris@0 60 */
Chris@0 61 protected $callbacks = array();
Chris@0 62
Chris@0 63 /**
Chris@0 64 * @var array
Chris@0 65 */
Chris@0 66 protected $ignoredAttributes = array();
Chris@0 67
Chris@0 68 /**
Chris@0 69 * @var array
Chris@0 70 */
Chris@0 71 protected $camelizedAttributes = array();
Chris@0 72
Chris@0 73 /**
Chris@0 74 * Sets the {@link ClassMetadataFactoryInterface} to use.
Chris@0 75 */
Chris@0 76 public function __construct(ClassMetadataFactoryInterface $classMetadataFactory = null, NameConverterInterface $nameConverter = null)
Chris@0 77 {
Chris@0 78 $this->classMetadataFactory = $classMetadataFactory;
Chris@0 79 $this->nameConverter = $nameConverter;
Chris@0 80 }
Chris@0 81
Chris@0 82 /**
Chris@0 83 * Set circular reference limit.
Chris@0 84 *
Chris@14 85 * @param int $circularReferenceLimit Limit of iterations for the same object
Chris@0 86 *
Chris@0 87 * @return self
Chris@0 88 */
Chris@0 89 public function setCircularReferenceLimit($circularReferenceLimit)
Chris@0 90 {
Chris@0 91 $this->circularReferenceLimit = $circularReferenceLimit;
Chris@0 92
Chris@0 93 return $this;
Chris@0 94 }
Chris@0 95
Chris@0 96 /**
Chris@0 97 * Set circular reference handler.
Chris@0 98 *
Chris@0 99 * @param callable $circularReferenceHandler
Chris@0 100 *
Chris@0 101 * @return self
Chris@0 102 */
Chris@0 103 public function setCircularReferenceHandler(callable $circularReferenceHandler)
Chris@0 104 {
Chris@0 105 $this->circularReferenceHandler = $circularReferenceHandler;
Chris@0 106
Chris@0 107 return $this;
Chris@0 108 }
Chris@0 109
Chris@0 110 /**
Chris@0 111 * Set normalization callbacks.
Chris@0 112 *
Chris@14 113 * @param callable[] $callbacks Help normalize the result
Chris@0 114 *
Chris@0 115 * @return self
Chris@0 116 *
Chris@0 117 * @throws InvalidArgumentException if a non-callable callback is set
Chris@0 118 */
Chris@0 119 public function setCallbacks(array $callbacks)
Chris@0 120 {
Chris@0 121 foreach ($callbacks as $attribute => $callback) {
Chris@14 122 if (!\is_callable($callback)) {
Chris@0 123 throw new InvalidArgumentException(sprintf(
Chris@0 124 'The given callback for attribute "%s" is not callable.',
Chris@0 125 $attribute
Chris@0 126 ));
Chris@0 127 }
Chris@0 128 }
Chris@0 129 $this->callbacks = $callbacks;
Chris@0 130
Chris@0 131 return $this;
Chris@0 132 }
Chris@0 133
Chris@0 134 /**
Chris@0 135 * Set ignored attributes for normalization and denormalization.
Chris@0 136 *
Chris@0 137 * @return self
Chris@0 138 */
Chris@0 139 public function setIgnoredAttributes(array $ignoredAttributes)
Chris@0 140 {
Chris@0 141 $this->ignoredAttributes = $ignoredAttributes;
Chris@0 142
Chris@0 143 return $this;
Chris@0 144 }
Chris@0 145
Chris@0 146 /**
Chris@0 147 * Detects if the configured circular reference limit is reached.
Chris@0 148 *
Chris@0 149 * @param object $object
Chris@0 150 * @param array $context
Chris@0 151 *
Chris@0 152 * @return bool
Chris@0 153 *
Chris@0 154 * @throws CircularReferenceException
Chris@0 155 */
Chris@0 156 protected function isCircularReference($object, &$context)
Chris@0 157 {
Chris@0 158 $objectHash = spl_object_hash($object);
Chris@0 159
Chris@0 160 if (isset($context[static::CIRCULAR_REFERENCE_LIMIT][$objectHash])) {
Chris@0 161 if ($context[static::CIRCULAR_REFERENCE_LIMIT][$objectHash] >= $this->circularReferenceLimit) {
Chris@0 162 unset($context[static::CIRCULAR_REFERENCE_LIMIT][$objectHash]);
Chris@0 163
Chris@0 164 return true;
Chris@0 165 }
Chris@0 166
Chris@0 167 ++$context[static::CIRCULAR_REFERENCE_LIMIT][$objectHash];
Chris@0 168 } else {
Chris@0 169 $context[static::CIRCULAR_REFERENCE_LIMIT][$objectHash] = 1;
Chris@0 170 }
Chris@0 171
Chris@0 172 return false;
Chris@0 173 }
Chris@0 174
Chris@0 175 /**
Chris@0 176 * Handles a circular reference.
Chris@0 177 *
Chris@0 178 * If a circular reference handler is set, it will be called. Otherwise, a
Chris@0 179 * {@class CircularReferenceException} will be thrown.
Chris@0 180 *
Chris@0 181 * @param object $object
Chris@0 182 *
Chris@0 183 * @return mixed
Chris@0 184 *
Chris@0 185 * @throws CircularReferenceException
Chris@0 186 */
Chris@0 187 protected function handleCircularReference($object)
Chris@0 188 {
Chris@0 189 if ($this->circularReferenceHandler) {
Chris@14 190 return \call_user_func($this->circularReferenceHandler, $object);
Chris@0 191 }
Chris@0 192
Chris@14 193 throw new CircularReferenceException(sprintf('A circular reference has been detected when serializing the object of class "%s" (configured limit: %d)', \get_class($object), $this->circularReferenceLimit));
Chris@0 194 }
Chris@0 195
Chris@0 196 /**
Chris@0 197 * Gets attributes to normalize using groups.
Chris@0 198 *
Chris@0 199 * @param string|object $classOrObject
Chris@0 200 * @param array $context
Chris@0 201 * @param bool $attributesAsString If false, return an array of {@link AttributeMetadataInterface}
Chris@0 202 *
Chris@0 203 * @return string[]|AttributeMetadataInterface[]|bool
Chris@0 204 */
Chris@0 205 protected function getAllowedAttributes($classOrObject, array $context, $attributesAsString = false)
Chris@0 206 {
Chris@14 207 if (!$this->classMetadataFactory) {
Chris@14 208 return false;
Chris@14 209 }
Chris@14 210
Chris@14 211 $groups = false;
Chris@14 212 if (isset($context[static::GROUPS]) && \is_array($context[static::GROUPS])) {
Chris@14 213 $groups = $context[static::GROUPS];
Chris@14 214 } elseif (!isset($context[static::ALLOW_EXTRA_ATTRIBUTES]) || $context[static::ALLOW_EXTRA_ATTRIBUTES]) {
Chris@0 215 return false;
Chris@0 216 }
Chris@0 217
Chris@0 218 $allowedAttributes = array();
Chris@0 219 foreach ($this->classMetadataFactory->getMetadataFor($classOrObject)->getAttributesMetadata() as $attributeMetadata) {
Chris@0 220 $name = $attributeMetadata->getName();
Chris@0 221
Chris@0 222 if (
Chris@14 223 (false === $groups || array_intersect($attributeMetadata->getGroups(), $groups)) &&
Chris@0 224 $this->isAllowedAttribute($classOrObject, $name, null, $context)
Chris@0 225 ) {
Chris@0 226 $allowedAttributes[] = $attributesAsString ? $name : $attributeMetadata;
Chris@0 227 }
Chris@0 228 }
Chris@0 229
Chris@0 230 return $allowedAttributes;
Chris@0 231 }
Chris@0 232
Chris@0 233 /**
Chris@0 234 * Is this attribute allowed?
Chris@0 235 *
Chris@0 236 * @param object|string $classOrObject
Chris@0 237 * @param string $attribute
Chris@0 238 * @param string|null $format
Chris@0 239 * @param array $context
Chris@0 240 *
Chris@0 241 * @return bool
Chris@0 242 */
Chris@0 243 protected function isAllowedAttribute($classOrObject, $attribute, $format = null, array $context = array())
Chris@0 244 {
Chris@14 245 if (in_array($attribute, $this->ignoredAttributes)) {
Chris@14 246 return false;
Chris@14 247 }
Chris@14 248
Chris@14 249 if (isset($context[self::ATTRIBUTES][$attribute])) {
Chris@14 250 // Nested attributes
Chris@14 251 return true;
Chris@14 252 }
Chris@14 253
Chris@14 254 if (isset($context[self::ATTRIBUTES]) && is_array($context[self::ATTRIBUTES])) {
Chris@14 255 return in_array($attribute, $context[self::ATTRIBUTES], true);
Chris@14 256 }
Chris@14 257
Chris@14 258 return true;
Chris@0 259 }
Chris@0 260
Chris@0 261 /**
Chris@0 262 * Normalizes the given data to an array. It's particularly useful during
Chris@0 263 * the denormalization process.
Chris@0 264 *
Chris@0 265 * @param object|array $data
Chris@0 266 *
Chris@0 267 * @return array
Chris@0 268 */
Chris@0 269 protected function prepareForDenormalization($data)
Chris@0 270 {
Chris@0 271 return (array) $data;
Chris@0 272 }
Chris@0 273
Chris@0 274 /**
Chris@0 275 * Returns the method to use to construct an object. This method must be either
Chris@0 276 * the object constructor or static.
Chris@0 277 *
Chris@0 278 * @param array $data
Chris@0 279 * @param string $class
Chris@0 280 * @param array $context
Chris@0 281 * @param \ReflectionClass $reflectionClass
Chris@0 282 * @param array|bool $allowedAttributes
Chris@0 283 *
Chris@0 284 * @return \ReflectionMethod|null
Chris@0 285 */
Chris@0 286 protected function getConstructor(array &$data, $class, array &$context, \ReflectionClass $reflectionClass, $allowedAttributes)
Chris@0 287 {
Chris@0 288 return $reflectionClass->getConstructor();
Chris@0 289 }
Chris@0 290
Chris@0 291 /**
Chris@0 292 * Instantiates an object using constructor parameters when needed.
Chris@0 293 *
Chris@0 294 * This method also allows to denormalize data into an existing object if
Chris@0 295 * it is present in the context with the object_to_populate. This object
Chris@0 296 * is removed from the context before being returned to avoid side effects
Chris@0 297 * when recursively normalizing an object graph.
Chris@0 298 *
Chris@0 299 * @param array $data
Chris@0 300 * @param string $class
Chris@0 301 * @param array $context
Chris@0 302 * @param \ReflectionClass $reflectionClass
Chris@0 303 * @param array|bool $allowedAttributes
Chris@0 304 * @param string|null $format
Chris@0 305 *
Chris@0 306 * @return object
Chris@0 307 *
Chris@0 308 * @throws RuntimeException
Chris@0 309 */
Chris@14 310 protected function instantiateObject(array &$data, $class, array &$context, \ReflectionClass $reflectionClass, $allowedAttributes/*, string $format = null*/)
Chris@0 311 {
Chris@14 312 if (\func_num_args() >= 6) {
Chris@14 313 $format = \func_get_arg(5);
Chris@0 314 } else {
Chris@14 315 if (__CLASS__ !== \get_class($this)) {
Chris@0 316 $r = new \ReflectionMethod($this, __FUNCTION__);
Chris@0 317 if (__CLASS__ !== $r->getDeclaringClass()->getName()) {
Chris@14 318 @trigger_error(sprintf('Method %s::%s() will have a 6th `string $format = null` argument in version 4.0. Not defining it is deprecated since Symfony 3.2.', get_class($this), __FUNCTION__), E_USER_DEPRECATED);
Chris@0 319 }
Chris@0 320 }
Chris@0 321
Chris@0 322 $format = null;
Chris@0 323 }
Chris@0 324
Chris@14 325 if (null !== $object = $this->extractObjectToPopulate($class, $context, static::OBJECT_TO_POPULATE)) {
Chris@0 326 unset($context[static::OBJECT_TO_POPULATE]);
Chris@0 327
Chris@0 328 return $object;
Chris@0 329 }
Chris@0 330
Chris@0 331 $constructor = $this->getConstructor($data, $class, $context, $reflectionClass, $allowedAttributes);
Chris@0 332 if ($constructor) {
Chris@0 333 $constructorParameters = $constructor->getParameters();
Chris@0 334
Chris@0 335 $params = array();
Chris@0 336 foreach ($constructorParameters as $constructorParameter) {
Chris@0 337 $paramName = $constructorParameter->name;
Chris@0 338 $key = $this->nameConverter ? $this->nameConverter->normalize($paramName) : $paramName;
Chris@0 339
Chris@14 340 $allowed = false === $allowedAttributes || \in_array($paramName, $allowedAttributes);
Chris@14 341 $ignored = !$this->isAllowedAttribute($class, $paramName, $format, $context);
Chris@0 342 if (method_exists($constructorParameter, 'isVariadic') && $constructorParameter->isVariadic()) {
Chris@0 343 if ($allowed && !$ignored && (isset($data[$key]) || array_key_exists($key, $data))) {
Chris@14 344 if (!\is_array($data[$paramName])) {
Chris@0 345 throw new RuntimeException(sprintf('Cannot create an instance of %s from serialized data because the variadic parameter %s can only accept an array.', $class, $constructorParameter->name));
Chris@0 346 }
Chris@0 347
Chris@0 348 $params = array_merge($params, $data[$paramName]);
Chris@0 349 }
Chris@0 350 } elseif ($allowed && !$ignored && (isset($data[$key]) || array_key_exists($key, $data))) {
Chris@0 351 $parameterData = $data[$key];
Chris@0 352 try {
Chris@0 353 if (null !== $constructorParameter->getClass()) {
Chris@0 354 if (!$this->serializer instanceof DenormalizerInterface) {
Chris@0 355 throw new LogicException(sprintf('Cannot create an instance of %s from serialized data because the serializer inject in "%s" is not a denormalizer', $constructorParameter->getClass(), static::class));
Chris@0 356 }
Chris@0 357 $parameterClass = $constructorParameter->getClass()->getName();
Chris@14 358 $parameterData = $this->serializer->denormalize($parameterData, $parameterClass, $format, $this->createChildContext($context, $paramName));
Chris@0 359 }
Chris@0 360 } catch (\ReflectionException $e) {
Chris@0 361 throw new RuntimeException(sprintf('Could not determine the class of the parameter "%s".', $key), 0, $e);
Chris@0 362 }
Chris@0 363
Chris@0 364 // Don't run set for a parameter passed to the constructor
Chris@0 365 $params[] = $parameterData;
Chris@0 366 unset($data[$key]);
Chris@0 367 } elseif ($constructorParameter->isDefaultValueAvailable()) {
Chris@0 368 $params[] = $constructorParameter->getDefaultValue();
Chris@0 369 } else {
Chris@0 370 throw new RuntimeException(
Chris@0 371 sprintf(
Chris@0 372 'Cannot create an instance of %s from serialized data because its constructor requires parameter "%s" to be present.',
Chris@0 373 $class,
Chris@0 374 $constructorParameter->name
Chris@0 375 )
Chris@0 376 );
Chris@0 377 }
Chris@0 378 }
Chris@0 379
Chris@0 380 if ($constructor->isConstructor()) {
Chris@0 381 return $reflectionClass->newInstanceArgs($params);
Chris@0 382 } else {
Chris@0 383 return $constructor->invokeArgs(null, $params);
Chris@0 384 }
Chris@0 385 }
Chris@0 386
Chris@0 387 return new $class();
Chris@0 388 }
Chris@14 389
Chris@14 390 /**
Chris@14 391 * @param array $parentContext
Chris@14 392 * @param string $attribute
Chris@14 393 *
Chris@14 394 * @return array
Chris@14 395 *
Chris@14 396 * @internal
Chris@14 397 */
Chris@14 398 protected function createChildContext(array $parentContext, $attribute)
Chris@14 399 {
Chris@14 400 if (isset($parentContext[self::ATTRIBUTES][$attribute])) {
Chris@14 401 $parentContext[self::ATTRIBUTES] = $parentContext[self::ATTRIBUTES][$attribute];
Chris@14 402 } else {
Chris@14 403 unset($parentContext[self::ATTRIBUTES]);
Chris@14 404 }
Chris@14 405
Chris@14 406 return $parentContext;
Chris@14 407 }
Chris@0 408 }