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(
74 'The error code "%s" does not exist for constraint of type "%s".',
80 return static::$errorNames[$errorCode];
84 * Initializes the constraint with options.
86 * You should pass an associative array. The keys should be the names of
87 * existing properties in this class. The values should be the value for these
90 * Alternatively you can override the method getDefaultOption() to return the
91 * name of an existing property. If no associative array is passed, this
92 * property is set instead.
94 * You can force that certain options are set by overriding
95 * getRequiredOptions() to return the names of these options. If any
96 * option is not set here, an exception is thrown.
98 * @param mixed $options The options (as associative array)
99 * or the value for the default
100 * option (any other type)
102 * @throws InvalidOptionsException When you pass the names of non-existing
104 * @throws MissingOptionsException When you don't pass any of the options
105 * returned by getRequiredOptions()
106 * @throws ConstraintDefinitionException When you don't pass an associative
107 * array, but getDefaultOption() returns
110 public function __construct($options = null)
112 $invalidOptions = array();
113 $missingOptions = array_flip((array) $this->getRequiredOptions());
114 $knownOptions = get_object_vars($this);
116 // The "groups" option is added to the object lazily
117 $knownOptions['groups'] = true;
119 if (is_array($options) && count($options) >= 1 && isset($options['value']) && !property_exists($this, 'value')) {
120 $options[$this->getDefaultOption()] = $options['value'];
121 unset($options['value']);
124 if (is_array($options)) {
127 if (is_array($options) && count($options) > 0 && is_string(key($options))) {
128 foreach ($options as $option => $value) {
129 if (array_key_exists($option, $knownOptions)) {
130 $this->$option = $value;
131 unset($missingOptions[$option]);
133 $invalidOptions[] = $option;
136 } elseif (null !== $options && !(is_array($options) && 0 === count($options))) {
137 $option = $this->getDefaultOption();
139 if (null === $option) {
140 throw new ConstraintDefinitionException(
141 sprintf('No default option is configured for constraint %s', get_class($this))
145 if (array_key_exists($option, $knownOptions)) {
146 $this->$option = $options;
147 unset($missingOptions[$option]);
149 $invalidOptions[] = $option;
153 if (count($invalidOptions) > 0) {
154 throw new InvalidOptionsException(
155 sprintf('The options "%s" do not exist in constraint %s', implode('", "', $invalidOptions), get_class($this)),
160 if (count($missingOptions) > 0) {
161 throw new MissingOptionsException(
162 sprintf('The options "%s" must be set for constraint %s', implode('", "', array_keys($missingOptions)), get_class($this)),
163 array_keys($missingOptions)
169 * Sets the value of a lazily initialized option.
171 * Corresponding properties are added to the object on first access. Hence
172 * this method will be called at most once per constraint instance and
175 * @param string $option The option name
176 * @param mixed $value The value to set
178 * @throws InvalidOptionsException If an invalid option name is given
180 public function __set($option, $value)
182 if ('groups' === $option) {
183 $this->groups = (array) $value;
188 throw new InvalidOptionsException(sprintf('The option "%s" does not exist in constraint %s', $option, get_class($this)), array($option));
192 * Returns the value of a lazily initialized option.
194 * Corresponding properties are added to the object on first access. Hence
195 * this method will be called at most once per constraint instance and
198 * @param string $option The option name
200 * @return mixed The value of the option
202 * @throws InvalidOptionsException If an invalid option name is given
204 * @internal this method should not be used or overwritten in userland code
206 public function __get($option)
208 if ('groups' === $option) {
209 $this->groups = array(self::DEFAULT_GROUP);
211 return $this->groups;
214 throw new InvalidOptionsException(sprintf('The option "%s" does not exist in constraint %s', $option, get_class($this)), array($option));
218 * @param string $option The option name
222 public function __isset($option)
224 return 'groups' === $option;
228 * Adds the given group if this constraint is in the Default group.
230 * @param string $group
232 public function addImplicitGroupName($group)
234 if (in_array(self::DEFAULT_GROUP, $this->groups) && !in_array($group, $this->groups)) {
235 $this->groups[] = $group;
240 * Returns the name of the default option.
242 * Override this method to define a default option.
248 public function getDefaultOption()
253 * Returns the name of the required options.
255 * Override this method if you want to define required options.
261 public function getRequiredOptions()
267 * Returns the name of the class that validates this constraint.
269 * By default, this is the fully qualified name of the constraint class
270 * suffixed with "Validator". You can override this method to change that
275 public function validatedBy()
277 return get_class($this).'Validator';
281 * Returns whether the constraint can be put onto classes, properties or
284 * This method should return one or more of the constants
285 * Constraint::CLASS_CONSTRAINT and Constraint::PROPERTY_CONSTRAINT.
287 * @return string|array One or more constant values
289 public function getTargets()
291 return self::PROPERTY_CONSTRAINT;
295 * Optimizes the serialized value to minimize storage space.
297 * @return array The properties to serialize
299 * @internal This method may be replaced by an implementation of
300 * {@link \Serializable} in the future. Please don't use or
303 public function __sleep()
305 // Initialize "groups" option if it is not set
308 return array_keys(get_object_vars($this));