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: use Chromabits\Nucleus\Meditation\Arguments;
15: use Chromabits\Nucleus\Meditation\Boa;
16: use Chromabits\Nucleus\Meditation\Constraints\AbstractConstraint;
17:
18: /**
19: * Class AtLeastOneOfConstraint.
20: *
21: * @author Eduardo Trujillo <ed@chromabits.com>
22: * @package Chromabits\Nucleus\Validation\Constraints
23: */
24: class AtLeastOneOfConstraint extends AbstractConstraint
25: {
26: /**
27: * @var string[]
28: */
29: protected $fields;
30:
31: /**
32: * Construct an instance of a AtLeastOneOfConstraint.
33: *
34: * @param array $fields
35: */
36: public function __construct(array $fields)
37: {
38: parent::__construct();
39:
40: Arguments::define(Boa::arrOf(Boa::string()))->check($fields);
41:
42: $this->fields = $fields;
43: }
44:
45: /**
46: * Check if the constraint is met.
47: *
48: * @param mixed $value
49: * @param array $context
50: *
51: * @return mixed
52: */
53: public function check($value, array $context = [])
54: {
55: foreach ($context as $field => $value) {
56: if (in_array($field, $this->fields)) {
57: return true;
58: }
59: }
60:
61: return false;
62: }
63:
64: /**
65: * Get string representation of this constraint.
66: *
67: * @return mixed
68: */
69: public function toString()
70: {
71: return vsprintf(
72: '{atLeastOneOf: ["%s"]}',
73: [implode('", "', $this->fields)]
74: );
75: }
76:
77: /**
78: * Get a description of the constraint.
79: *
80: * @return string
81: */
82: public function getDescription()
83: {
84: return vsprintf(
85: 'At least one of the following fields should be provided: ["%s"]}',
86: [implode('", "', $this->fields)]
87: );
88: }
89: }
90: