Constraint.php 9.4 KB

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