Version 1
[yaffs-website] / vendor / symfony / validator / Constraint.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\Validator;
13
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;
18
19 /**
20  * Contains the properties of a constraint definition.
21  *
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.
25  *
26  * Constraint instances are immutable and serializable.
27  *
28  * @property array $groups The groups that the constraint belongs to
29  *
30  * @author Bernhard Schussek <bschussek@gmail.com>
31  */
32 abstract class Constraint
33 {
34     /**
35      * The name of the group given to all constraints with no explicit group.
36      *
37      * @var string
38      */
39     const DEFAULT_GROUP = 'Default';
40
41     /**
42      * Marks a constraint that can be put onto classes.
43      *
44      * @var string
45      */
46     const CLASS_CONSTRAINT = 'class';
47
48     /**
49      * Marks a constraint that can be put onto properties.
50      *
51      * @var string
52      */
53     const PROPERTY_CONSTRAINT = 'property';
54
55     /**
56      * Maps error codes to the names of their constants.
57      *
58      * @var array
59      */
60     protected static $errorNames = array();
61
62     /**
63      * Domain-specific data attached to a constraint.
64      *
65      * @var mixed
66      */
67     public $payload;
68
69     /**
70      * Returns the name of the given error code.
71      *
72      * @param string $errorCode The error code
73      *
74      * @return string The name of the error code
75      *
76      * @throws InvalidArgumentException If the error code does not exist
77      */
78     public static function getErrorName($errorCode)
79     {
80         if (!isset(static::$errorNames[$errorCode])) {
81             throw new InvalidArgumentException(sprintf(
82                 'The error code "%s" does not exist for constraint of type "%s".',
83                 $errorCode,
84                 get_called_class()
85             ));
86         }
87
88         return static::$errorNames[$errorCode];
89     }
90
91     /**
92      * Initializes the constraint with options.
93      *
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
96      * properties.
97      *
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.
101      *
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.
105      *
106      * @param mixed $options The options (as associative array)
107      *                       or the value for the default
108      *                       option (any other type)
109      *
110      * @throws InvalidOptionsException       When you pass the names of non-existing
111      *                                       options
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
116      *                                       null
117      */
118     public function __construct($options = null)
119     {
120         $invalidOptions = array();
121         $missingOptions = array_flip((array) $this->getRequiredOptions());
122         $knownOptions = get_object_vars($this);
123
124         // The "groups" option is added to the object lazily
125         $knownOptions['groups'] = true;
126
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']);
130         }
131
132         if (is_array($options)) {
133             reset($options);
134         }
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]);
140                 } else {
141                     $invalidOptions[] = $option;
142                 }
143             }
144         } elseif (null !== $options && !(is_array($options) && count($options) === 0)) {
145             $option = $this->getDefaultOption();
146
147             if (null === $option) {
148                 throw new ConstraintDefinitionException(
149                     sprintf('No default option is configured for constraint %s', get_class($this))
150                 );
151             }
152
153             if (array_key_exists($option, $knownOptions)) {
154                 $this->$option = $options;
155                 unset($missingOptions[$option]);
156             } else {
157                 $invalidOptions[] = $option;
158             }
159         }
160
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)),
164                 $invalidOptions
165             );
166         }
167
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)
172             );
173         }
174     }
175
176     /**
177      * Sets the value of a lazily initialized option.
178      *
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
181      * option name.
182      *
183      * @param string $option The option name
184      * @param mixed  $value  The value to set
185      *
186      * @throws InvalidOptionsException If an invalid option name is given
187      */
188     public function __set($option, $value)
189     {
190         if ('groups' === $option) {
191             $this->groups = (array) $value;
192
193             return;
194         }
195
196         throw new InvalidOptionsException(sprintf('The option "%s" does not exist in constraint %s', $option, get_class($this)), array($option));
197     }
198
199     /**
200      * Returns the value of a lazily initialized option.
201      *
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
204      * option name.
205      *
206      * @param string $option The option name
207      *
208      * @return mixed The value of the option
209      *
210      * @throws InvalidOptionsException If an invalid option name is given
211      *
212      * @internal This method should not be used or overwritten in userland code.
213      */
214     public function __get($option)
215     {
216         if ('groups' === $option) {
217             $this->groups = array(self::DEFAULT_GROUP);
218
219             return $this->groups;
220         }
221
222         throw new InvalidOptionsException(sprintf('The option "%s" does not exist in constraint %s', $option, get_class($this)), array($option));
223     }
224
225     /**
226      * Adds the given group if this constraint is in the Default group.
227      *
228      * @param string $group
229      */
230     public function addImplicitGroupName($group)
231     {
232         if (in_array(self::DEFAULT_GROUP, $this->groups) && !in_array($group, $this->groups)) {
233             $this->groups[] = $group;
234         }
235     }
236
237     /**
238      * Returns the name of the default option.
239      *
240      * Override this method to define a default option.
241      *
242      * @return string
243      *
244      * @see __construct()
245      */
246     public function getDefaultOption()
247     {
248     }
249
250     /**
251      * Returns the name of the required options.
252      *
253      * Override this method if you want to define required options.
254      *
255      * @return array
256      *
257      * @see __construct()
258      */
259     public function getRequiredOptions()
260     {
261         return array();
262     }
263
264     /**
265      * Returns the name of the class that validates this constraint.
266      *
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
269      * behaviour.
270      *
271      * @return string
272      */
273     public function validatedBy()
274     {
275         return get_class($this).'Validator';
276     }
277
278     /**
279      * Returns whether the constraint can be put onto classes, properties or
280      * both.
281      *
282      * This method should return one or more of the constants
283      * Constraint::CLASS_CONSTRAINT and Constraint::PROPERTY_CONSTRAINT.
284      *
285      * @return string|array One or more constant values
286      */
287     public function getTargets()
288     {
289         return self::PROPERTY_CONSTRAINT;
290     }
291
292     /**
293      * Optimizes the serialized value to minimize storage space.
294      *
295      * @return array The properties to serialize
296      *
297      * @internal This method may be replaced by an implementation of
298      *           {@link \Serializable} in the future. Please don't use or
299      *           overwrite it.
300      */
301     public function __sleep()
302     {
303         // Initialize "groups" option if it is not set
304         $this->groups;
305
306         return array_keys(get_object_vars($this));
307     }
308 }