PageRenderTime 56ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/vendor/symfony/symfony/src/Symfony/Component/Serializer/Normalizer/GetSetMethodNormalizer.php

https://gitlab.com/mohamedchiheb.bida/workshopFOS
PHP | 318 lines | 169 code | 45 blank | 104 comment | 26 complexity | a2ea26df8fb1cd2d4d8cd99caba70cbe MD5 | raw file
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Serializer\Normalizer;
  11. use Symfony\Component\Serializer\Exception\CircularReferenceException;
  12. use Symfony\Component\Serializer\Exception\InvalidArgumentException;
  13. use Symfony\Component\Serializer\Exception\LogicException;
  14. use Symfony\Component\Serializer\Exception\RuntimeException;
  15. /**
  16. * Converts between objects with getter and setter methods and arrays.
  17. *
  18. * The normalization process looks at all public methods and calls the ones
  19. * which have a name starting with get and take no parameters. The result is a
  20. * map from property names (method name stripped of the get prefix and converted
  21. * to lower case) to property values. Property values are normalized through the
  22. * serializer.
  23. *
  24. * The denormalization first looks at the constructor of the given class to see
  25. * if any of the parameters have the same name as one of the properties. The
  26. * constructor is then called with all parameters or an exception is thrown if
  27. * any required parameters were not present as properties. Then the denormalizer
  28. * walks through the given map of property names to property values to see if a
  29. * setter method exists for any of the properties. If a setter exists it is
  30. * called with the property value. No automatic denormalization of the value
  31. * takes place.
  32. *
  33. * @author Nils Adermann <naderman@naderman.de>
  34. * @author Kévin Dunglas <dunglas@gmail.com>
  35. */
  36. class GetSetMethodNormalizer extends SerializerAwareNormalizer implements NormalizerInterface, DenormalizerInterface
  37. {
  38. protected $circularReferenceLimit = 1;
  39. protected $circularReferenceHandler;
  40. protected $callbacks = array();
  41. protected $ignoredAttributes = array();
  42. protected $camelizedAttributes = array();
  43. /**
  44. * Set circular reference limit.
  45. *
  46. * @param $circularReferenceLimit limit of iterations for the same object
  47. *
  48. * @return self
  49. */
  50. public function setCircularReferenceLimit($circularReferenceLimit)
  51. {
  52. $this->circularReferenceLimit = $circularReferenceLimit;
  53. return $this;
  54. }
  55. /**
  56. * Set circular reference handler.
  57. *
  58. * @param callable $circularReferenceHandler
  59. *
  60. * @return self
  61. *
  62. * @throws InvalidArgumentException
  63. */
  64. public function setCircularReferenceHandler($circularReferenceHandler)
  65. {
  66. if (!is_callable($circularReferenceHandler)) {
  67. throw new InvalidArgumentException('The given circular reference handler is not callable.');
  68. }
  69. $this->circularReferenceHandler = $circularReferenceHandler;
  70. return $this;
  71. }
  72. /**
  73. * Set normalization callbacks.
  74. *
  75. * @param callable[] $callbacks help normalize the result
  76. *
  77. * @throws InvalidArgumentException if a non-callable callback is set
  78. *
  79. * @return self
  80. */
  81. public function setCallbacks(array $callbacks)
  82. {
  83. foreach ($callbacks as $attribute => $callback) {
  84. if (!is_callable($callback)) {
  85. throw new InvalidArgumentException(sprintf('The given callback for attribute "%s" is not callable.', $attribute));
  86. }
  87. }
  88. $this->callbacks = $callbacks;
  89. return $this;
  90. }
  91. /**
  92. * Set ignored attributes for normalization.
  93. *
  94. * @param array $ignoredAttributes
  95. *
  96. * @return self
  97. */
  98. public function setIgnoredAttributes(array $ignoredAttributes)
  99. {
  100. $this->ignoredAttributes = $ignoredAttributes;
  101. return $this;
  102. }
  103. /**
  104. * Set attributes to be camelized on denormalize.
  105. *
  106. * @param array $camelizedAttributes
  107. *
  108. * @return self
  109. */
  110. public function setCamelizedAttributes(array $camelizedAttributes)
  111. {
  112. $this->camelizedAttributes = $camelizedAttributes;
  113. return $this;
  114. }
  115. /**
  116. * {@inheritdoc}
  117. */
  118. public function normalize($object, $format = null, array $context = array())
  119. {
  120. $objectHash = spl_object_hash($object);
  121. if (isset($context['circular_reference_limit'][$objectHash])) {
  122. if ($context['circular_reference_limit'][$objectHash] >= $this->circularReferenceLimit) {
  123. unset($context['circular_reference_limit'][$objectHash]);
  124. if ($this->circularReferenceHandler) {
  125. return call_user_func($this->circularReferenceHandler, $object);
  126. }
  127. throw new CircularReferenceException(sprintf('A circular reference has been detected (configured limit: %d).', $this->circularReferenceLimit));
  128. }
  129. $context['circular_reference_limit'][$objectHash]++;
  130. } else {
  131. $context['circular_reference_limit'][$objectHash] = 1;
  132. }
  133. $reflectionObject = new \ReflectionObject($object);
  134. $reflectionMethods = $reflectionObject->getMethods(\ReflectionMethod::IS_PUBLIC);
  135. $attributes = array();
  136. foreach ($reflectionMethods as $method) {
  137. if ($this->isGetMethod($method)) {
  138. $attributeName = lcfirst(substr($method->name, 0 === strpos($method->name, 'is') ? 2 : 3));
  139. if (in_array($attributeName, $this->ignoredAttributes)) {
  140. continue;
  141. }
  142. $attributeValue = $method->invoke($object);
  143. if (array_key_exists($attributeName, $this->callbacks)) {
  144. $attributeValue = call_user_func($this->callbacks[$attributeName], $attributeValue);
  145. }
  146. if (null !== $attributeValue && !is_scalar($attributeValue)) {
  147. if (!$this->serializer instanceof NormalizerInterface) {
  148. throw new LogicException(sprintf('Cannot normalize attribute "%s" because injected serializer is not a normalizer', $attributeName));
  149. }
  150. $attributeValue = $this->serializer->normalize($attributeValue, $format, $context);
  151. }
  152. $attributes[$attributeName] = $attributeValue;
  153. }
  154. }
  155. return $attributes;
  156. }
  157. /**
  158. * {@inheritdoc}
  159. */
  160. public function denormalize($data, $class, $format = null, array $context = array())
  161. {
  162. if (is_array($data) || is_object($data) && $data instanceof \ArrayAccess) {
  163. $normalizedData = $data;
  164. } elseif (is_object($data)) {
  165. $normalizedData = array();
  166. foreach ($data as $attribute => $value) {
  167. $normalizedData[$attribute] = $value;
  168. }
  169. } else {
  170. $normalizedData = array();
  171. }
  172. $reflectionClass = new \ReflectionClass($class);
  173. $constructor = $reflectionClass->getConstructor();
  174. if ($constructor) {
  175. $constructorParameters = $constructor->getParameters();
  176. $params = array();
  177. foreach ($constructorParameters as $constructorParameter) {
  178. $paramName = lcfirst($this->formatAttribute($constructorParameter->name));
  179. if (isset($normalizedData[$paramName])) {
  180. $params[] = $normalizedData[$paramName];
  181. // don't run set for a parameter passed to the constructor
  182. unset($normalizedData[$paramName]);
  183. } elseif ($constructorParameter->isOptional()) {
  184. $params[] = $constructorParameter->getDefaultValue();
  185. } else {
  186. throw new RuntimeException(
  187. 'Cannot create an instance of '.$class.
  188. ' from serialized data because its constructor requires '.
  189. 'parameter "'.$constructorParameter->name.
  190. '" to be present.');
  191. }
  192. }
  193. $object = $reflectionClass->newInstanceArgs($params);
  194. } else {
  195. $object = new $class();
  196. }
  197. foreach ($normalizedData as $attribute => $value) {
  198. $setter = 'set'.$this->formatAttribute($attribute);
  199. if (method_exists($object, $setter)) {
  200. $object->$setter($value);
  201. }
  202. }
  203. return $object;
  204. }
  205. /**
  206. * Format attribute name to access parameters or methods
  207. * As option, if attribute name is found on camelizedAttributes array
  208. * returns attribute name in camelcase format.
  209. *
  210. * @param string $attributeName
  211. *
  212. * @return string
  213. */
  214. protected function formatAttribute($attributeName)
  215. {
  216. if (in_array($attributeName, $this->camelizedAttributes)) {
  217. return preg_replace_callback(
  218. '/(^|_|\.)+(.)/', function ($match) {
  219. return ('.' === $match[1] ? '_' : '').strtoupper($match[2]);
  220. }, $attributeName
  221. );
  222. }
  223. return $attributeName;
  224. }
  225. /**
  226. * {@inheritdoc}
  227. */
  228. public function supportsNormalization($data, $format = null)
  229. {
  230. return is_object($data) && $this->supports(get_class($data));
  231. }
  232. /**
  233. * {@inheritdoc}
  234. */
  235. public function supportsDenormalization($data, $type, $format = null)
  236. {
  237. return $this->supports($type);
  238. }
  239. /**
  240. * Checks if the given class has any get{Property} method.
  241. *
  242. * @param string $class
  243. *
  244. * @return bool
  245. */
  246. private function supports($class)
  247. {
  248. $class = new \ReflectionClass($class);
  249. $methods = $class->getMethods(\ReflectionMethod::IS_PUBLIC);
  250. foreach ($methods as $method) {
  251. if ($this->isGetMethod($method)) {
  252. return true;
  253. }
  254. }
  255. return false;
  256. }
  257. /**
  258. * Checks if a method's name is get.* or is.*, and can be called without parameters.
  259. *
  260. * @param \ReflectionMethod $method the method to check
  261. *
  262. * @return bool whether the method is a getter or boolean getter.
  263. */
  264. private function isGetMethod(\ReflectionMethod $method)
  265. {
  266. $methodLength = strlen($method->name);
  267. return (
  268. ((0 === strpos($method->name, 'get') && 3 < $methodLength) ||
  269. (0 === strpos($method->name, 'is') && 2 < $methodLength)) &&
  270. 0 === $method->getNumberOfRequiredParameters()
  271. );
  272. }
  273. }