4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Validator;
14 use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
15 use Symfony\Component\Validator\Exception\InvalidArgumentException;
16 use Symfony\Component\Validator\Exception\InvalidOptionsException;
17 use Symfony\Component\Validator\Exception\MissingOptionsException;
20 * Contains the properties of a constraint definition.
22 * A constraint can be defined on a class, a property or a getter method.
23 * The Constraint class encapsulates all the configuration required for
24 * validating this class, property or getter result successfully.
26 * Constraint instances are immutable and serializable.
28 * @property array $groups The groups that the constraint belongs to
30 * @author Bernhard Schussek <bschussek@gmail.com>
32 abstract class Constraint
35 * The name of the group given to all constraints with no explicit group.
37 const DEFAULT_GROUP = 'Default';
40 * Marks a constraint that can be put onto classes.
42 const CLASS_CONSTRAINT = 'class';
45 * Marks a constraint that can be put onto properties.
47 const PROPERTY_CONSTRAINT = 'property';
50 * Maps error codes to the names of their constants.
52 protected static $errorNames = array();
55 * Domain-specific data attached to a constraint.
62 * Returns the name of the given error code.
64 * @param string $errorCode The error code
66 * @return string The name of the error code
68 * @throws InvalidArgumentException If the error code does not exist
70 public static function getErrorName($errorCode)
72 if (!isset(static::$errorNames[$errorCode])) {
73 throw new InvalidArgumentException(sprintf('The error code "%s" does not exist for constraint of type "%s".', $errorCode, \get_called_class()));
76 return static::$errorNames[$errorCode];
80 * Initializes the constraint with options.
82 * You should pass an associative array. The keys should be the names of
83 * existing properties in this class. The values should be the value for these
86 * Alternatively you can override the method getDefaultOption() to return the
87 * name of an existing property. If no associative array is passed, this
88 * property is set instead.
90 * You can force that certain options are set by overriding
91 * getRequiredOptions() to return the names of these options. If any
92 * option is not set here, an exception is thrown.
94 * @param mixed $options The options (as associative array)
95 * or the value for the default
96 * option (any other type)
98 * @throws InvalidOptionsException When you pass the names of non-existing
100 * @throws MissingOptionsException When you don't pass any of the options
101 * returned by getRequiredOptions()
102 * @throws ConstraintDefinitionException When you don't pass an associative
103 * array, but getDefaultOption() returns
106 public function __construct($options = null)
108 $invalidOptions = array();
109 $missingOptions = array_flip((array) $this->getRequiredOptions());
110 $knownOptions = get_object_vars($this);
112 // The "groups" option is added to the object lazily
113 $knownOptions['groups'] = true;
115 if (\is_array($options) && \count($options) >= 1 && isset($options['value']) && !property_exists($this, 'value')) {
116 $options[$this->getDefaultOption()] = $options['value'];
117 unset($options['value']);
120 if (\is_array($options)) {
123 if (\is_array($options) && \count($options) > 0 && \is_string(key($options))) {
124 foreach ($options as $option => $value) {
125 if (array_key_exists($option, $knownOptions)) {
126 $this->$option = $value;
127 unset($missingOptions[$option]);
129 $invalidOptions[] = $option;
132 } elseif (null !== $options && !(\is_array($options) && 0 === \count($options))) {
133 $option = $this->getDefaultOption();
135 if (null === $option) {
136 throw new ConstraintDefinitionException(sprintf('No default option is configured for constraint %s', \get_class($this)));
139 if (array_key_exists($option, $knownOptions)) {
140 $this->$option = $options;
141 unset($missingOptions[$option]);
143 $invalidOptions[] = $option;
147 if (\count($invalidOptions) > 0) {
148 throw new InvalidOptionsException(sprintf('The options "%s" do not exist in constraint %s', implode('", "', $invalidOptions), \get_class($this)), $invalidOptions);
151 if (\count($missingOptions) > 0) {
152 throw new MissingOptionsException(sprintf('The options "%s" must be set for constraint %s', implode('", "', array_keys($missingOptions)), \get_class($this)), array_keys($missingOptions));
157 * Sets the value of a lazily initialized option.
159 * Corresponding properties are added to the object on first access. Hence
160 * this method will be called at most once per constraint instance and
163 * @param string $option The option name
164 * @param mixed $value The value to set
166 * @throws InvalidOptionsException If an invalid option name is given
168 public function __set($option, $value)
170 if ('groups' === $option) {
171 $this->groups = (array) $value;
176 throw new InvalidOptionsException(sprintf('The option "%s" does not exist in constraint %s', $option, \get_class($this)), array($option));
180 * Returns the value of a lazily initialized option.
182 * Corresponding properties are added to the object on first access. Hence
183 * this method will be called at most once per constraint instance and
186 * @param string $option The option name
188 * @return mixed The value of the option
190 * @throws InvalidOptionsException If an invalid option name is given
192 * @internal this method should not be used or overwritten in userland code
194 public function __get($option)
196 if ('groups' === $option) {
197 $this->groups = array(self::DEFAULT_GROUP);
199 return $this->groups;
202 throw new InvalidOptionsException(sprintf('The option "%s" does not exist in constraint %s', $option, \get_class($this)), array($option));
206 * @param string $option The option name
210 public function __isset($option)
212 return 'groups' === $option;
216 * Adds the given group if this constraint is in the Default group.
218 * @param string $group
220 public function addImplicitGroupName($group)
222 if (\in_array(self::DEFAULT_GROUP, $this->groups) && !\in_array($group, $this->groups)) {
223 $this->groups[] = $group;
228 * Returns the name of the default option.
230 * Override this method to define a default option.
236 public function getDefaultOption()
241 * Returns the name of the required options.
243 * Override this method if you want to define required options.
249 public function getRequiredOptions()
255 * Returns the name of the class that validates this constraint.
257 * By default, this is the fully qualified name of the constraint class
258 * suffixed with "Validator". You can override this method to change that
263 public function validatedBy()
265 return \get_class($this).'Validator';
269 * Returns whether the constraint can be put onto classes, properties or
272 * This method should return one or more of the constants
273 * Constraint::CLASS_CONSTRAINT and Constraint::PROPERTY_CONSTRAINT.
275 * @return string|array One or more constant values
277 public function getTargets()
279 return self::PROPERTY_CONSTRAINT;
283 * Optimizes the serialized value to minimize storage space.
285 * @return array The properties to serialize
287 * @internal This method may be replaced by an implementation of
288 * {@link \Serializable} in the future. Please don't use or
291 public function __sleep()
293 // Initialize "groups" option if it is not set
296 return array_keys(get_object_vars($this));