1: <?php
2:
3: /**
4: * Jyxo PHP Library
5: *
6: * LICENSE
7: *
8: * This source file is subject to the new BSD license that is bundled
9: * with this package in the file license.txt.
10: * It is also available through the world-wide-web at this URL:
11: * https://github.com/jyxo/php/blob/master/license.txt
12: */
13:
14: namespace Jyxo\Input\Chain;
15:
16: /**
17: * Chain of filters and validators for a single variable.
18: * The validation itself is performed after fulfilling the condition.
19: * The condition is checked by a defined validator.
20: *
21: * @category Jyxo
22: * @package Jyxo\Input
23: * @subpackage Chain
24: * @copyright Copyright (c) 2005-2011 Jyxo, s.r.o.
25: * @license https://github.com/jyxo/php/blob/master/license.txt
26: * @author Roman Řáha
27: */
28: class Conditional extends \Jyxo\Input\Chain
29: {
30: /**
31: * Condition validator.
32: *
33: * @var \Jyxo\Input\ValidatorInterface
34: */
35: private $condValidator = null;
36:
37: /**
38: * Sets the condition validator.
39: *
40: * @param \Jyxo\Input\ValidatorInterface $validator
41: */
42: public function __construct(\Jyxo\Input\ValidatorInterface $validator = null)
43: {
44: if (null !== $validator) {
45: $this->setCondValidator($validator);
46: }
47: }
48:
49: /**
50: * Validates a value.
51: *
52: * @param mixed $value Input value
53: * @return boolean
54: */
55: public function isValid($value)
56: {
57: // Validation is performed only if the condition is fulfilled
58: if (true === $this->checkCondition($value)) {
59: return parent::isValid($value);
60: }
61: // No validation -> the value is valid
62: $this->value = $value;
63: return true;
64: }
65:
66: /**
67: * Checks if the condition is fulfilled.
68: *
69: * @param mixed $value Input value
70: * @return boolean
71: */
72: private function checkCondition($value)
73: {
74: if (null === $this->condValidator) {
75: // There is no validator -> always fulfilled
76: return true;
77: }
78: return $this->condValidator->isValid($value);
79: }
80:
81: /**
82: * Sets the condition validator.
83: *
84: * @param \Jyxo\Input\ValidatorInterface $validator Condition validator
85: * @return \Jyxo\Input\Chain\Conditional
86: */
87: public function setCondValidator(\Jyxo\Input\ValidatorInterface $validator)
88: {
89: $this->condValidator = $validator;
90: return $this;
91: }
92: }
93: