|
1
|
|
|
<?php |
|
2
|
|
|
namespace Desmond; |
|
3
|
|
|
use Desmond\exceptions\ArgumentException; |
|
4
|
|
|
|
|
5
|
|
|
trait ArgumentHelper |
|
6
|
|
|
{ |
|
7
|
215 |
|
public function expectArguments($function, array $expected, array $actual) |
|
8
|
|
|
{ |
|
9
|
215 |
|
foreach ($expected as $argIndex => $types) { |
|
10
|
215 |
|
if (!isset($actual[$argIndex])) { |
|
11
|
31 |
|
$this->failException($function, $argIndex, $types); |
|
12
|
|
|
} |
|
13
|
193 |
|
$actualArg = $actual[$argIndex]; |
|
14
|
193 |
|
$requiredTypes = $this->classPaths($types); |
|
15
|
193 |
|
if (!in_array(get_class($actualArg), $requiredTypes)) { |
|
16
|
19 |
|
$this->failException($function, $argIndex, $types); |
|
17
|
|
|
} |
|
18
|
|
|
} |
|
19
|
169 |
|
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
|
193 |
|
public function classPaths(array $types) |
|
37
|
|
|
{ |
|
38
|
193 |
|
$paths = []; |
|
39
|
193 |
|
foreach ($types as $type) { |
|
40
|
193 |
|
$paths[] = $this->typeClassPath($type); |
|
41
|
|
|
} |
|
42
|
193 |
|
return $paths; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
263 |
|
public function typeClassPath($type) |
|
46
|
|
|
{ |
|
47
|
263 |
|
return 'Desmond\\data_types\\' . $type . 'Type'; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
103 |
|
public function isDesmondType($type, $object) { |
|
51
|
103 |
|
$class = $this->typeClassPath($type); |
|
52
|
103 |
|
return $object instanceof $class; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
152 |
|
public function newReturnType($type, $arg=null) |
|
56
|
|
|
{ |
|
57
|
152 |
|
$class = $this->typeClassPath($type); |
|
58
|
152 |
|
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
|
|
|
|