-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathConditionHandler.php
53 lines (42 loc) · 1.12 KB
/
ConditionHandler.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
namespace duncan3dc\Laravel;
use function array_key_exists;
class ConditionHandler
{
/**
* @var array $conditions The conditions registered.
*/
private $conditions = [];
/**
* Register an custom conditional directive.
*
* @param string $name
* @param callable $handler
*
* @return $this
*/
public function add(string $name, callable $handler): ConditionHandler
{
if (array_key_exists($name, $this->conditions)) {
throw new \UnexpectedValueException("A conditional by this name already exists: @{$name}");
}
$this->conditions[$name] = $handler;
return $this;
}
/**
* Call a registered conditional directive.
*
* @param string $name
* @param mixed ...$params
*
* @return mixed
*/
public function check(string $name, ...$params)
{
if (!array_key_exists($name, $this->conditions)) {
throw new \UnexpectedValueException("Unknown conditional: @{$name}");
}
$function = $this->conditions[$name];
return $function(...$params);
}
}