Constraint.php 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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\Validator;
  11. use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
  12. use Symfony\Component\Validator\Exception\InvalidArgumentException;
  13. use Symfony\Component\Validator\Exception\InvalidOptionsException;
  14. use Symfony\Component\Validator\Exception\MissingOptionsException;
  15. /**
  16. * Contains the properties of a constraint definition.
  17. *
  18. * A constraint can be defined on a class, a property or a getter method.
  19. * The Constraint class encapsulates all the configuration required for
  20. * validating this class, property or getter result successfully.
  21. *
  22. * Constraint instances are immutable and serializable.
  23. *
  24. * @property string[] $groups The groups that the constraint belongs to
  25. *
  26. * @author Bernhard Schussek <bschussek@gmail.com>
  27. */
  28. abstract class Constraint
  29. {
  30. /**
  31. * The name of the group given to all constraints with no explicit group.
  32. */
  33. public const DEFAULT_GROUP = 'Default';
  34. /**
  35. * Marks a constraint that can be put onto classes.
  36. */
  37. public const CLASS_CONSTRAINT = 'class';
  38. /**
  39. * Marks a constraint that can be put onto properties.
  40. */
  41. public const PROPERTY_CONSTRAINT = 'property';
  42. /**
  43. * Maps error codes to the names of their constants.
  44. */
  45. protected static $errorNames = [];
  46. /**
  47. * Domain-specific data attached to a constraint.
  48. *
  49. * @var mixed
  50. */
  51. public $payload;
  52. /**
  53. * Returns the name of the given error code.
  54. *
  55. * @param string $errorCode The error code
  56. *
  57. * @return string The name of the error code
  58. *
  59. * @throws InvalidArgumentException If the error code does not exist
  60. */
  61. public static function getErrorName($errorCode)
  62. {
  63. if (!isset(static::$errorNames[$errorCode])) {
  64. throw new InvalidArgumentException(sprintf('The error code "%s" does not exist for constraint of type "%s".', $errorCode, static::class));
  65. }
  66. return static::$errorNames[$errorCode];
  67. }
  68. /**
  69. * Initializes the constraint with options.
  70. *
  71. * You should pass an associative array. The keys should be the names of
  72. * existing properties in this class. The values should be the value for these
  73. * properties.
  74. *
  75. * Alternatively you can override the method getDefaultOption() to return the
  76. * name of an existing property. If no associative array is passed, this
  77. * property is set instead.
  78. *
  79. * You can force that certain options are set by overriding
  80. * getRequiredOptions() to return the names of these options. If any
  81. * option is not set here, an exception is thrown.
  82. *
  83. * @param mixed $options The options (as associative array)
  84. * or the value for the default
  85. * option (any other type)
  86. * @param string[] $groups An array of validation groups
  87. * @param mixed $payload Domain-specific data attached to a constraint
  88. *
  89. * @throws InvalidOptionsException When you pass the names of non-existing
  90. * options
  91. * @throws MissingOptionsException When you don't pass any of the options
  92. * returned by getRequiredOptions()
  93. * @throws ConstraintDefinitionException When you don't pass an associative
  94. * array, but getDefaultOption() returns
  95. * null
  96. */
  97. public function __construct($options = null, array $groups = null, $payload = null)
  98. {
  99. $options = $this->normalizeOptions($options);
  100. if (null !== $groups) {
  101. $options['groups'] = $groups;
  102. }
  103. $options['payload'] = $payload ?? $options['payload'] ?? null;
  104. foreach ($options as $name => $value) {
  105. $this->$name = $value;
  106. }
  107. }
  108. protected function normalizeOptions($options): array
  109. {
  110. $normalizedOptions = [];
  111. $defaultOption = $this->getDefaultOption();
  112. $invalidOptions = [];
  113. $missingOptions = array_flip((array) $this->getRequiredOptions());
  114. $knownOptions = get_class_vars(static::class);
  115. // The "groups" option is added to the object lazily
  116. $knownOptions['groups'] = true;
  117. if (\is_array($options) && isset($options['value']) && !property_exists($this, 'value')) {
  118. if (null === $defaultOption) {
  119. throw new ConstraintDefinitionException(sprintf('No default option is configured for constraint "%s".', static::class));
  120. }
  121. $options[$defaultOption] = $options['value'];
  122. unset($options['value']);
  123. }
  124. if (\is_array($options)) {
  125. reset($options);
  126. }
  127. if ($options && \is_array($options) && \is_string(key($options))) {
  128. foreach ($options as $option => $value) {
  129. if (\array_key_exists($option, $knownOptions)) {
  130. $normalizedOptions[$option] = $value;
  131. unset($missingOptions[$option]);
  132. } else {
  133. $invalidOptions[] = $option;
  134. }
  135. }
  136. } elseif (null !== $options && !(\is_array($options) && 0 === \count($options))) {
  137. if (null === $defaultOption) {
  138. throw new ConstraintDefinitionException(sprintf('No default option is configured for constraint "%s".', static::class));
  139. }
  140. if (\array_key_exists($defaultOption, $knownOptions)) {
  141. $normalizedOptions[$defaultOption] = $options;
  142. unset($missingOptions[$defaultOption]);
  143. } else {
  144. $invalidOptions[] = $defaultOption;
  145. }
  146. }
  147. if (\count($invalidOptions) > 0) {
  148. throw new InvalidOptionsException(sprintf('The options "%s" do not exist in constraint "%s".', implode('", "', $invalidOptions), static::class), $invalidOptions);
  149. }
  150. if (\count($missingOptions) > 0) {
  151. throw new MissingOptionsException(sprintf('The options "%s" must be set for constraint "%s".', implode('", "', array_keys($missingOptions)), static::class), array_keys($missingOptions));
  152. }
  153. return $normalizedOptions;
  154. }
  155. /**
  156. * Sets the value of a lazily initialized option.
  157. *
  158. * Corresponding properties are added to the object on first access. Hence
  159. * this method will be called at most once per constraint instance and
  160. * option name.
  161. *
  162. * @param mixed $value The value to set
  163. *
  164. * @throws InvalidOptionsException If an invalid option name is given
  165. */
  166. public function __set(string $option, $value)
  167. {
  168. if ('groups' === $option) {
  169. $this->groups = (array) $value;
  170. return;
  171. }
  172. throw new InvalidOptionsException(sprintf('The option "%s" does not exist in constraint "%s".', $option, static::class), [$option]);
  173. }
  174. /**
  175. * Returns the value of a lazily initialized option.
  176. *
  177. * Corresponding properties are added to the object on first access. Hence
  178. * this method will be called at most once per constraint instance and
  179. * option name.
  180. *
  181. * @param string $option The option name
  182. *
  183. * @return mixed The value of the option
  184. *
  185. * @throws InvalidOptionsException If an invalid option name is given
  186. *
  187. * @internal this method should not be used or overwritten in userland code
  188. */
  189. public function __get(string $option)
  190. {
  191. if ('groups' === $option) {
  192. $this->groups = [self::DEFAULT_GROUP];
  193. return $this->groups;
  194. }
  195. throw new InvalidOptionsException(sprintf('The option "%s" does not exist in constraint "%s".', $option, static::class), [$option]);
  196. }
  197. /**
  198. * @param string $option The option name
  199. *
  200. * @return bool
  201. */
  202. public function __isset(string $option)
  203. {
  204. return 'groups' === $option;
  205. }
  206. /**
  207. * Adds the given group if this constraint is in the Default group.
  208. *
  209. * @param string $group
  210. */
  211. public function addImplicitGroupName($group)
  212. {
  213. if (\in_array(self::DEFAULT_GROUP, $this->groups) && !\in_array($group, $this->groups)) {
  214. $this->groups[] = $group;
  215. }
  216. }
  217. /**
  218. * Returns the name of the default option.
  219. *
  220. * Override this method to define a default option.
  221. *
  222. * @return string|null
  223. *
  224. * @see __construct()
  225. */
  226. public function getDefaultOption()
  227. {
  228. return null;
  229. }
  230. /**
  231. * Returns the name of the required options.
  232. *
  233. * Override this method if you want to define required options.
  234. *
  235. * @return string[]
  236. *
  237. * @see __construct()
  238. */
  239. public function getRequiredOptions()
  240. {
  241. return [];
  242. }
  243. /**
  244. * Returns the name of the class that validates this constraint.
  245. *
  246. * By default, this is the fully qualified name of the constraint class
  247. * suffixed with "Validator". You can override this method to change that
  248. * behavior.
  249. *
  250. * @return string
  251. */
  252. public function validatedBy()
  253. {
  254. return static::class.'Validator';
  255. }
  256. /**
  257. * Returns whether the constraint can be put onto classes, properties or
  258. * both.
  259. *
  260. * This method should return one or more of the constants
  261. * Constraint::CLASS_CONSTRAINT and Constraint::PROPERTY_CONSTRAINT.
  262. *
  263. * @return string|string[] One or more constant values
  264. */
  265. public function getTargets()
  266. {
  267. return self::PROPERTY_CONSTRAINT;
  268. }
  269. /**
  270. * Optimizes the serialized value to minimize storage space.
  271. *
  272. * @internal
  273. */
  274. public function __sleep()
  275. {
  276. // Initialize "groups" option if it is not set
  277. $this->groups;
  278. return array_keys(get_object_vars($this));
  279. }
  280. }