0e48210b772afe3f6ada0d1130d13fcc1e93e496
[Packages/TYPO3.CMS.git] / typo3 / sysext / extbase / Classes / Validation / Validator / BooleanValidator.php
1 <?php
2 namespace TYPO3\CMS\Extbase\Validation\Validator;
3
4 /**
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16 /**
17 * Validator for boolean values
18 */
19 class BooleanValidator extends AbstractValidator {
20
21 /**
22 * @var array
23 */
24 protected $supportedOptions = array(
25 // The default is set to NULL here, because we need to be backward compatible here, because this
26 // BooleanValidator is called automatically on boolean action arguments. If we would set it to TRUE,
27 // every FALSE value for an action argument would break.
28 // TODO with next patches: deprecate this BooleanValidator and introduce a BooleanValueValidator, like
29 // in Flow, which won't be called on boolean action arguments.
30 'is' => array(NULL, 'Boolean value', 'boolean|string|integer')
31 );
32
33
34 /**
35 * Returns TRUE if the given property value is a boolean matching the expectation.
36 *
37 * If at least one error occurred, the result is FALSE.
38 *
39 * Also testing for '1' (true), '0' and '' (false) because casting varies between
40 * tests and actual usage. This makes the validator loose but still keeping functionality.
41 *
42 * @param mixed $value The value that should be validated
43 * @return bool TRUE if the value is within the range, otherwise FALSE
44 */
45 public function isValid($value) {
46 // see comment above, check if expectation is NULL, then nothing to do!
47 if ($this->options['is'] === NULL) {
48 return;
49 }
50 switch (strtolower((string)$this->options['is'])) {
51 case 'true':
52 case '1':
53 $expectation = TRUE;
54 break;
55 case 'false':
56 case '':
57 case '0':
58 $expectation = FALSE;
59 break;
60 default:
61 $this->addError('The given expectation is not valid.', 1361959227);
62 return;
63 }
64
65 if ($value !== $expectation) {
66 if (!is_bool($value)) {
67 $this->addError('The given subject is not true.', 1361959230);
68 } else {
69 if ($expectation) {
70 $this->addError('The given subject is not true.', 1361959228);
71 } else {
72 $this->addError('The given subject is not false.', 1361959229);
73 }
74 }
75 }
76 }
77
78 }