1: <?php
2:
3: /**
4: * Copyright 2015, Eduardo Trujillo
5: *
6: * For the full copyright and license information, please view the LICENSE
7: * file that was distributed with this source code.
8: *
9: * This file is part of the Nucleus package
10: */
11:
12: namespace Chromabits\Nucleus\Meditation\Constraints;
13:
14: use Chromabits\Nucleus\Support\Std;
15:
16: /**
17: * Class EitherConstraint.
18: *
19: * @author Eduardo Trujillo <ed@chromabits.com>
20: * @package Chromabits\Nucleus\Meditation\Constraints
21: */
22: class EitherConstraint extends AbstractTypeConstraint
23: {
24: /**
25: * First type.
26: *
27: * @var AbstractConstraint
28: */
29: protected $one;
30:
31: /**
32: * Second type.
33: *
34: * @var AbstractConstraint
35: */
36: protected $other;
37:
38: /**
39: * Construct an instance of an EitherConstraint.
40: *
41: * @param AbstractConstraint $one
42: * @param AbstractConstraint $other
43: */
44: public function __construct(
45: AbstractConstraint $one,
46: AbstractConstraint $other
47: ) {
48: parent::__construct();
49:
50: $this->one = $one;
51: $this->other = $other;
52: }
53:
54: /**
55: * Construct an instance of an EitherConstraint.
56: *
57: * @param AbstractConstraint $one
58: * @param AbstractConstraint $other
59: *
60: * @return static
61: */
62: public static function create(
63: AbstractConstraint $one,
64: AbstractConstraint $other
65: ) {
66: return new static($one, $other);
67: }
68:
69: /**
70: * Check if the constraint is met.
71: *
72: * @param mixed $value
73: * @param array $context
74: *
75: * @return bool
76: */
77: public function check($value, array $context = [])
78: {
79: return Std::truthy(
80: $this->one->check($value),
81: $this->other->check($value)
82: );
83: }
84:
85: /**
86: * Return whether the constraint is defined by an union of types.
87: *
88: * @return bool
89: */
90: public function isUnion()
91: {
92: return true;
93: }
94:
95: /**
96: * Get string representation of this constraint.
97: *
98: * @return mixed
99: */
100: public function toString()
101: {
102: $one = $this->one->toString();
103: $other = $this->other->toString();
104:
105: if ($this->one instanceof AbstractTypeConstraint) {
106: $one = $this->one->isUnion() ? sprintf('(%s)', $one) : $one;
107: }
108:
109: if ($this->other instanceof AbstractTypeConstraint) {
110: $other = $this->other->isUnion() ? sprintf('(%s)', $other) : $other;
111: }
112:
113: return sprintf('%s|%s', $one, $other);
114: }
115: }
116: