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.
39 const DEFAULT_GROUP = 'Default';
42 * Marks a constraint that can be put onto classes.
46 const CLASS_CONSTRAINT = 'class';
49 * Marks a constraint that can be put onto properties.
53 const PROPERTY_CONSTRAINT = 'property';
56 * Maps error codes to the names of their constants.
60 protected static $errorNames = array();
63 * Domain-specific data attached to a constraint.
70 * Returns the name of the given error code.
72 * @param string $errorCode The error code
74 * @return string The name of the error code
76 * @throws InvalidArgumentException If the error code does not exist
78 public static function getErrorName($errorCode)
80 if (!isset(static::$errorNames[$errorCode])) {
81 throw new InvalidArgumentException(sprintf(
82 'The error code "%s" does not exist for constraint of type "%s".',
88 return static::$errorNames[$errorCode];
92 * Initializes the constraint with options.
94 * You should pass an associative array. The keys should be the names of
95 * existing properties in this class. The values should be the value for these
98 * Alternatively you can override the method getDefaultOption() to return the
99 * name of an existing property. If no associative array is passed, this
100 * property is set instead.
102 * You can force that certain options are set by overriding
103 * getRequiredOptions() to return the names of these options. If any
104 * option is not set here, an exception is thrown.
106 * @param mixed $options The options (as associative array)
107 * or the value for the default
108 * option (any other type)
110 * @throws InvalidOptionsException When you pass the names of non-existing
112 * @throws MissingOptionsException When you don't pass any of the options
113 * returned by getRequiredOptions()
114 * @throws ConstraintDefinitionException When you don't pass an associative
115 * array, but getDefaultOption() returns
118 public function __construct($options = null)
120 $invalidOptions = array();
121 $missingOptions = array_flip((array) $this->getRequiredOptions());
122 $knownOptions = get_object_vars($this);
124 // The "groups" option is added to the object lazily
125 $knownOptions['groups'] = true;
127 if (is_array($options) && count($options) >= 1 && isset($options['value']) && !property_exists($this, 'value')) {
128 $options[$this->getDefaultOption()] = $options['value'];
129 unset($options['value']);
132 if (is_array($options)) {
135 if (is_array($options) && count($options) > 0 && is_string(key($options))) {
136 foreach ($options as $option => $value) {
137 if (array_key_exists($option, $knownOptions)) {
138 $this->$option = $value;
139 unset($missingOptions[$option]);
141 $invalidOptions[] = $option;
144 } elseif (null !== $options && !(is_array($options) && count($options) === 0)) {
145 $option = $this->getDefaultOption();
147 if (null === $option) {
148 throw new ConstraintDefinitionException(
149 sprintf('No default option is configured for constraint %s', get_class($this))
153 if (array_key_exists($option, $knownOptions)) {
154 $this->$option = $options;
155 unset($missingOptions[$option]);
157 $invalidOptions[] = $option;
161 if (count($invalidOptions) > 0) {
162 throw new InvalidOptionsException(
163 sprintf('The options "%s" do not exist in constraint %s', implode('", "', $invalidOptions), get_class($this)),
168 if (count($missingOptions) > 0) {
169 throw new MissingOptionsException(
170 sprintf('The options "%s" must be set for constraint %s', implode('", "', array_keys($missingOptions)), get_class($this)),
171 array_keys($missingOptions)
177 * Sets the value of a lazily initialized option.
179 * Corresponding properties are added to the object on first access. Hence
180 * this method will be called at most once per constraint instance and
183 * @param string $option The option name
184 * @param mixed $value The value to set
186 * @throws InvalidOptionsException If an invalid option name is given
188 public function __set($option, $value)
190 if ('groups' === $option) {
191 $this->groups = (array) $value;
196 throw new InvalidOptionsException(sprintf('The option "%s" does not exist in constraint %s', $option, get_class($this)), array($option));
200 * Returns the value of a lazily initialized option.
202 * Corresponding properties are added to the object on first access. Hence
203 * this method will be called at most once per constraint instance and
206 * @param string $option The option name
208 * @return mixed The value of the option
210 * @throws InvalidOptionsException If an invalid option name is given
212 * @internal This method should not be used or overwritten in userland code.
214 public function __get($option)
216 if ('groups' === $option) {
217 $this->groups = array(self::DEFAULT_GROUP);
219 return $this->groups;
222 throw new InvalidOptionsException(sprintf('The option "%s" does not exist in constraint %s', $option, get_class($this)), array($option));
226 * Adds the given group if this constraint is in the Default group.
228 * @param string $group
230 public function addImplicitGroupName($group)
232 if (in_array(self::DEFAULT_GROUP, $this->groups) && !in_array($group, $this->groups)) {
233 $this->groups[] = $group;
238 * Returns the name of the default option.
240 * Override this method to define a default option.
246 public function getDefaultOption()
251 * Returns the name of the required options.
253 * Override this method if you want to define required options.
259 public function getRequiredOptions()
265 * Returns the name of the class that validates this constraint.
267 * By default, this is the fully qualified name of the constraint class
268 * suffixed with "Validator". You can override this method to change that
273 public function validatedBy()
275 return get_class($this).'Validator';
279 * Returns whether the constraint can be put onto classes, properties or
282 * This method should return one or more of the constants
283 * Constraint::CLASS_CONSTRAINT and Constraint::PROPERTY_CONSTRAINT.
285 * @return string|array One or more constant values
287 public function getTargets()
289 return self::PROPERTY_CONSTRAINT;
293 * Optimizes the serialized value to minimize storage space.
295 * @return array The properties to serialize
297 * @internal This method may be replaced by an implementation of
298 * {@link \Serializable} in the future. Please don't use or
301 public function __sleep()
303 // Initialize "groups" option if it is not set
306 return array_keys(get_object_vars($this));