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\Exceptions\LackOfCoffeeException;
15: use Chromabits\Nucleus\Meditation\TypeHound;
16: use Chromabits\Nucleus\Support\Std;
17: use Closure;
18:
19: /**
20: * Class ClosureConstraint.
21: *
22: * @author Eduardo Trujillo <ed@chromabits.com>
23: * @package Chromabits\Nucleus\Meditation\Constraints
24: */
25: class ClosureConstraint extends AbstractConstraint
26: {
27: /**
28: * @var Closure
29: */
30: protected $closure;
31:
32: /**
33: * @var string
34: */
35: protected $description;
36:
37: /**
38: * Construct an instance of a ClosureConstraint.
39: *
40: * @param Closure $closure
41: * @param string|null $description
42: */
43: public function __construct(Closure $closure, $description = null)
44: {
45: parent::__construct();
46:
47: $this->closure = $closure;
48: $this->description = Std::coalesce(
49: $description,
50: 'The value is expected to meet the constraint.'
51: );
52: }
53:
54: /**
55: * Check if the constraint is met.
56: *
57: * @param mixed $value
58: * @param array $context
59: *
60: * @throws LackOfCoffeeException
61: * @return mixed
62: */
63: public function check($value, array $context = [])
64: {
65: $closure = $this->closure;
66: $result = $closure($value, $context);
67:
68: if (!is_bool($result)) {
69: throw new LackOfCoffeeException(
70: vsprintf(
71: 'Inner closure of constraint was expected to return a'
72: . ' boolean value. Got %s instead.',
73: [TypeHound::fetch($result)]
74: )
75: );
76: }
77:
78: return $result;
79: }
80:
81: /**
82: * Get string representation of this constraint.
83: *
84: * @return string
85: */
86: public function toString()
87: {
88: return 'custom';
89: }
90:
91: /**
92: * Get the description of the constraint.
93: *
94: * @return string
95: */
96: public function getDescription()
97: {
98: return $this->description;
99: }
100: }
101: