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\Validation\Constraints;
13:
14: /**
15: * Class ExactlyOneOfConstraint.
16: *
17: * @author Eduardo Trujillo <ed@chromabits.com>
18: * @package Chromabits\Nucleus\Validation\Constraints
19: */
20: class ExactlyOneOfConstraint extends AtLeastOneOfConstraint
21: {
22: /**
23: * Check if the constraint is met.
24: *
25: * @param mixed $value
26: * @param array $context
27: *
28: * @return mixed
29: */
30: public function check($value, array $context = [])
31: {
32: $count = 0;
33:
34: foreach ($context as $field => $value) {
35: if (in_array($field, $this->fields)) {
36: $count++;
37: }
38: }
39:
40: return ($count === 1);
41: }
42:
43: /**
44: * Get string representation of this constraint.
45: *
46: * @return mixed
47: */
48: public function toString()
49: {
50: return vsprintf(
51: '{exactlyOneOf: ["%s"]}',
52: [implode('", "', $this->fields)]
53: );
54: }
55:
56: /**
57: * Get a description of the constraint.
58: *
59: * @return string
60: */
61: public function getDescription()
62: {
63: return vsprintf(
64: 'Only one of the following should be provided: ["%s"]}',
65: [implode('", "', $this->fields)]
66: );
67: }
68: }
69: