-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathContainerHasParameterConstraint.php
94 lines (77 loc) · 2.81 KB
/
ContainerHasParameterConstraint.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
namespace Matthias\SymfonyDependencyInjectionTest\PhpUnit;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\Constraint\IsEqual;
use PHPUnit\Framework\Constraint\IsIdentical;
use PHPUnit\Util\Exporter;
use Symfony\Component\DependencyInjection\ContainerInterface;
final class ContainerHasParameterConstraint extends Constraint
{
private $parameterName;
private $expectedParameterValue;
private $checkParameterValue;
private $strict;
public function __construct(
string $parameterName,
$expectedParameterValue = null,
bool $checkParameterValue = false,
bool $strict = false
) {
$this->parameterName = $parameterName;
$this->expectedParameterValue = $expectedParameterValue;
$this->checkParameterValue = $checkParameterValue;
$this->strict = $strict;
}
public function toString(): string
{
return sprintf(
'has a parameter "%s" with the given value',
$this->parameterName
);
}
public function evaluate($other, string $description = '', bool $returnResult = false): bool
{
if (!($other instanceof ContainerInterface)) {
throw new \InvalidArgumentException(
'Expected an instance of Symfony\Component\DependencyInjection\ContainerInterface'
);
}
if (!$this->evaluateParameterName($other, $returnResult)) {
return false;
}
if ($this->checkParameterValue && !$this->evaluateParameterValue($other, $returnResult)) {
return false;
}
return true;
}
private function evaluateParameterName(ContainerInterface $container, bool $returnResult): bool
{
if (!$container->hasParameter($this->parameterName)) {
if ($returnResult) {
return false;
}
$this->fail($container, sprintf(
'The container has no "%s" parameter',
$this->parameterName
));
}
return true;
}
private function evaluateParameterValue(ContainerInterface $container, bool $returnResult): bool
{
$actualValue = $container->getParameter($this->parameterName);
$constraint = $this->strict ? new IsIdentical($this->expectedParameterValue) : new IsEqual($this->expectedParameterValue);
if (!$constraint->evaluate($actualValue, '', true)) {
if ($returnResult) {
return false;
}
$this->fail($container, sprintf(
'The value of parameter "%s" (%s) does not match the expected value (%s)',
$this->parameterName,
Exporter::export($actualValue),
Exporter::export($this->expectedParameterValue)
));
}
return true;
}
}