1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Happyr\DoctrineSpecification\Operand; |
4
|
|
|
|
5
|
|
|
use Happyr\DoctrineSpecification\Exception\NotConvertibleException; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* This service is intended for backward compatibility and may be removed in the future. |
9
|
|
|
*/ |
10
|
|
|
class ArgumentToOperandConverter |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* Convert the argument into the field operand if it is not an operand. |
14
|
|
|
* |
15
|
|
|
* @param Operand|string $argument |
16
|
|
|
* |
17
|
|
|
* @return Operand |
18
|
|
|
*/ |
19
|
|
|
public static function toField($argument) |
20
|
|
|
{ |
21
|
|
|
if ($argument instanceof Operand) { |
22
|
|
|
return $argument; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
return new Field($argument); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Convert the argument into the value operand if it is not an operand. |
30
|
|
|
* |
31
|
|
|
* @param Operand|string $argument |
32
|
|
|
* |
33
|
|
|
* @return Operand |
34
|
|
|
*/ |
35
|
|
|
public static function toValue($argument) |
36
|
|
|
{ |
37
|
|
|
if ($argument instanceof Operand) { |
38
|
|
|
return $argument; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
return new Value($argument); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Are all arguments is a operands? |
46
|
|
|
* |
47
|
|
|
* @param array $arguments |
48
|
|
|
* |
49
|
|
|
* @return bool |
50
|
|
|
*/ |
51
|
|
|
public static function isAllOperands(array $arguments) |
52
|
|
|
{ |
53
|
|
|
foreach ($arguments as $argument) { |
54
|
|
|
if (!($argument instanceof Operand)) { |
55
|
|
|
return false; |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
return true; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* Convert all possible arguments to operands. |
64
|
|
|
* |
65
|
|
|
* @param Operand[]|string[] $arguments |
66
|
|
|
* |
67
|
|
|
* @throws NotConvertibleException |
68
|
|
|
* |
69
|
|
|
* @return Operand[] |
70
|
|
|
*/ |
71
|
|
|
public static function convert(array $arguments) |
72
|
|
|
{ |
73
|
|
|
$result = []; |
74
|
|
|
$size = count($arguments); |
75
|
|
|
foreach (array_values($arguments) as $i => $argument) { |
76
|
|
|
if (0 === $i) { |
77
|
|
|
// always try convert the first argument to the field operand |
78
|
|
|
$argument = self::toField($argument); |
79
|
|
|
} elseif ($i === $size - 1) { |
80
|
|
|
// always try convert the last argument to the value operand |
81
|
|
|
$argument = self::toValue($argument); |
82
|
|
|
} elseif (!($argument instanceof Operand)) { |
83
|
|
|
throw new NotConvertibleException('You passed arguments not all of which are operands.'); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
$result[] = $argument; |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
return $result; |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|