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;
13:
14: use Chromabits\Nucleus\Foundation\BaseObject;
15: use Chromabits\Nucleus\Meditation\Constraints\AbstractConstraint;
16: use Chromabits\Nucleus\Meditation\Exceptions\InvalidArgumentException;
17:
18: /**
19: * Class Arguments.
20: *
21: * @author Eduardo Trujillo <ed@chromabits.com>
22: * @package Chromabits\Nucleus\Meditation
23: */
24: class Arguments extends BaseObject
25: {
26: /**
27: * Constraints for the checker.
28: *
29: * @var AbstractConstraint[]
30: */
31: protected $constraints;
32:
33: /**
34: * Construct an instance of an Arguments.
35: *
36: * @param AbstractConstraint[] ...$constraints
37: */
38: public function __construct(...$constraints)
39: {
40: parent::__construct();
41:
42: $this->constraints = $constraints;
43: }
44:
45: /**
46: * Construct an instance of an Argument.
47: *
48: * @param AbstractConstraint[] $constraints
49: *
50: * @deprecated See Arguments::define
51: * @return static
52: */
53: public static function contain(...$constraints)
54: {
55: return new static(...$constraints);
56: }
57:
58: /**
59: * Construct an instance of an Argument.
60: *
61: * @param AbstractConstraint[] $constraints
62: *
63: * @return static
64: */
65: public static function define(...$constraints)
66: {
67: return new static(...$constraints);
68: }
69:
70: /**
71: * Check that the parameters are met.
72: *
73: * @param AbstractConstraint[] ...$args
74: *
75: * @throws InvalidArgumentException
76: */
77: public function check(...$args)
78: {
79: if (count($args) !== count($this->constraints)) {
80: throw new InvalidArgumentException(
81: 'Argument number mismatch.'
82: );
83: }
84:
85: foreach ($args as $key => $arg) {
86: if (!$this->constraints[$key]->check($arg, $args)) {
87: throw new InvalidArgumentException(vsprintf(
88: 'Argument %s does not meet its constraints.'
89: . "\nFailed constraint: %s\nValue provided:%s",
90: [
91: $key,
92: $this->constraints[$key]->toString(),
93: print_r($arg, true)
94: ]
95: ));
96: }
97: }
98: }
99: }
100: