/src/Symfony/Component/Validator/Constraint.php

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