1
|
|
|
<?php |
2
|
|
|
namespace Desmond; |
3
|
|
|
use Desmond\exceptions\ArgumentException; |
4
|
|
|
|
5
|
|
|
trait ArgumentHelper |
6
|
|
|
{ |
7
|
190 |
|
public function expectArguments($function, array $expected, array $actual) |
8
|
|
|
{ |
9
|
190 |
|
foreach ($expected as $argIndex => $types) { |
10
|
190 |
|
if (!isset($actual[$argIndex])) { |
11
|
31 |
|
$this->failException($function, $argIndex, $types); |
12
|
|
|
} |
13
|
168 |
|
$actualArg = $actual[$argIndex]; |
14
|
168 |
|
$requiredTypes = $this->classPaths($types); |
15
|
168 |
|
if (!in_array(get_class($actualArg), $requiredTypes)) { |
16
|
168 |
|
$this->failException($function, $argIndex, $types); |
17
|
|
|
} |
18
|
|
|
} |
19
|
144 |
|
return true; |
20
|
|
|
} |
21
|
|
|
|
22
|
50 |
|
public function failException($function, $arg, $types) |
23
|
|
|
{ |
24
|
50 |
|
if (count($types) > 1) { |
25
|
30 |
|
$message = sprintf( |
26
|
30 |
|
'"%s" expects argument %d to be one of [%s].', |
27
|
30 |
|
$function, $arg+1, implode(', ', $types)); |
28
|
|
|
} else { |
29
|
20 |
|
$message = sprintf( |
30
|
20 |
|
'"%s" expects argument %d to be a %s.', |
31
|
20 |
|
$function, $arg+1, $types[0]); |
32
|
|
|
} |
33
|
50 |
|
throw new ArgumentException($message); |
34
|
|
|
} |
35
|
|
|
|
36
|
168 |
|
public function classPaths(array $types) |
37
|
|
|
{ |
38
|
168 |
|
$paths = []; |
39
|
168 |
|
foreach ($types as $type) { |
40
|
168 |
|
$paths[] = $this->typeClassPath($type); |
41
|
|
|
} |
42
|
168 |
|
return $paths; |
43
|
|
|
} |
44
|
|
|
|
45
|
237 |
|
public function typeClassPath($type) |
46
|
|
|
{ |
47
|
237 |
|
return 'Desmond\\data_types\\' . $type . 'Type'; |
48
|
|
|
} |
49
|
|
|
|
50
|
82 |
|
public function isDesmondType($type, $object) { |
51
|
82 |
|
$class = $this->typeClassPath($type); |
52
|
82 |
|
return $object instanceof $class; |
53
|
|
|
} |
54
|
|
|
|
55
|
131 |
|
public function newReturnType($type, $arg=null) |
56
|
|
|
{ |
57
|
131 |
|
$class = $this->typeClassPath($type); |
58
|
131 |
|
return $arg === null ? new $class() : new $class($arg); |
59
|
|
|
} |
60
|
|
|
|
61
|
25 |
|
public function cloneArgs(array $args) |
62
|
|
|
{ |
63
|
25 |
|
$newArgs = []; |
64
|
25 |
|
foreach ($args as $arg) { |
65
|
21 |
|
$newArgs[] = clone($arg); |
66
|
|
|
} |
67
|
25 |
|
return $newArgs; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|