Constraint.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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 array $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. const DEFAULT_GROUP = 'Default';
  34. /**
  35. * Marks a constraint that can be put onto classes.
  36. */
  37. const CLASS_CONSTRAINT = 'class';
  38. /**
  39. * Marks a constraint that can be put onto properties.
  40. */
  41. const PROPERTY_CONSTRAINT = 'property';
  42. /**
  43. * Maps error codes to the names of their constants.
  44. */
  45. protected static $errorNames = array();
  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, \get_called_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. *
  87. * @throws InvalidOptionsException When you pass the names of non-existing
  88. * options
  89. * @throws MissingOptionsException When you don't pass any of the options
  90. * returned by getRequiredOptions()
  91. * @throws ConstraintDefinitionException When you don't pass an associative
  92. * array, but getDefaultOption() returns
  93. * null
  94. */
  95. public function __construct($options = null)
  96. {
  97. $invalidOptions = array();
  98. $missingOptions = array_flip((array) $this->getRequiredOptions());
  99. $knownOptions = get_object_vars($this);
  100. // The "groups" option is added to the object lazily
  101. $knownOptions['groups'] = true;
  102. if (\is_array($options) && \count($options) >= 1 && isset($options['value']) && !property_exists($this, 'value')) {
  103. $options[$this->getDefaultOption()] = $options['value'];
  104. unset($options['value']);
  105. }
  106. if (\is_array($options)) {
  107. reset($options);
  108. }
  109. if (\is_array($options) && \count($options) > 0 && \is_string(key($options))) {
  110. foreach ($options as $option => $value) {
  111. if (array_key_exists($option, $knownOptions)) {
  112. $this->$option = $value;
  113. unset($missingOptions[$option]);
  114. } else {
  115. $invalidOptions[] = $option;
  116. }
  117. }
  118. } elseif (null !== $options && !(\is_array($options) && 0 === \count($options))) {
  119. $option = $this->getDefaultOption();
  120. if (null === $option) {
  121. throw new ConstraintDefinitionException(sprintf('No default option is configured for constraint %s', \get_class($this)));
  122. }
  123. if (array_key_exists($option, $knownOptions)) {
  124. $this->$option = $options;
  125. unset($missingOptions[$option]);
  126. } else {
  127. $invalidOptions[] = $option;
  128. }
  129. }
  130. if (\count($invalidOptions) > 0) {
  131. throw new InvalidOptionsException(sprintf('The options "%s" do not exist in constraint %s', implode('", "', $invalidOptions), \get_class($this)), $invalidOptions);
  132. }
  133. if (\count($missingOptions) > 0) {
  134. throw new MissingOptionsException(sprintf('The options "%s" must be set for constraint %s', implode('", "', array_keys($missingOptions)), \get_class($this)), array_keys($missingOptions));
  135. }
  136. }
  137. /**
  138. * Sets the value of a lazily initialized option.
  139. *
  140. * Corresponding properties are added to the object on first access. Hence
  141. * this method will be called at most once per constraint instance and
  142. * option name.
  143. *
  144. * @param string $option The option name
  145. * @param mixed $value The value to set
  146. *
  147. * @throws InvalidOptionsException If an invalid option name is given
  148. */
  149. public function __set($option, $value)
  150. {
  151. if ('groups' === $option) {
  152. $this->groups = (array) $value;
  153. return;
  154. }
  155. throw new InvalidOptionsException(sprintf('The option "%s" does not exist in constraint %s', $option, \get_class($this)), array($option));
  156. }
  157. /**
  158. * Returns the value of a lazily initialized option.
  159. *
  160. * Corresponding properties are added to the object on first access. Hence
  161. * this method will be called at most once per constraint instance and
  162. * option name.
  163. *
  164. * @param string $option The option name
  165. *
  166. * @return mixed The value of the option
  167. *
  168. * @throws InvalidOptionsException If an invalid option name is given
  169. *
  170. * @internal this method should not be used or overwritten in userland code
  171. */
  172. public function __get($option)
  173. {
  174. if ('groups' === $option) {
  175. $this->groups = array(self::DEFAULT_GROUP);
  176. return $this->groups;
  177. }
  178. throw new InvalidOptionsException(sprintf('The option "%s" does not exist in constraint %s', $option, \get_class($this)), array($option));
  179. }
  180. /**
  181. * @param string $option The option name
  182. *
  183. * @return bool
  184. */
  185. public function __isset($option)
  186. {
  187. return 'groups' === $option;
  188. }
  189. /**
  190. * Adds the given group if this constraint is in the Default group.
  191. *
  192. * @param string $group
  193. */
  194. public function addImplicitGroupName($group)
  195. {
  196. if (\in_array(self::DEFAULT_GROUP, $this->groups) && !\in_array($group, $this->groups)) {
  197. $this->groups[] = $group;
  198. }
  199. }
  200. /**
  201. * Returns the name of the default option.
  202. *
  203. * Override this method to define a default option.
  204. *
  205. * @return string
  206. *
  207. * @see __construct()
  208. */
  209. public function getDefaultOption()
  210. {
  211. }
  212. /**
  213. * Returns the name of the required options.
  214. *
  215. * Override this method if you want to define required options.
  216. *
  217. * @return array
  218. *
  219. * @see __construct()
  220. */
  221. public function getRequiredOptions()
  222. {
  223. return array();
  224. }
  225. /**
  226. * Returns the name of the class that validates this constraint.
  227. *
  228. * By default, this is the fully qualified name of the constraint class
  229. * suffixed with "Validator". You can override this method to change that
  230. * behaviour.
  231. *
  232. * @return string
  233. */
  234. public function validatedBy()
  235. {
  236. return \get_class($this).'Validator';
  237. }
  238. /**
  239. * Returns whether the constraint can be put onto classes, properties or
  240. * both.
  241. *
  242. * This method should return one or more of the constants
  243. * Constraint::CLASS_CONSTRAINT and Constraint::PROPERTY_CONSTRAINT.
  244. *
  245. * @return string|array One or more constant values
  246. */
  247. public function getTargets()
  248. {
  249. return self::PROPERTY_CONSTRAINT;
  250. }
  251. /**
  252. * Optimizes the serialized value to minimize storage space.
  253. *
  254. * @return array The properties to serialize
  255. *
  256. * @internal This method may be replaced by an implementation of
  257. * {@link \Serializable} in the future. Please don't use or
  258. * overwrite it.
  259. */
  260. public function __sleep()
  261. {
  262. // Initialize "groups" option if it is not set
  263. $this->groups;
  264. return array_keys(get_object_vars($this));
  265. }
  266. }