-
Notifications
You must be signed in to change notification settings - Fork 15
/
ArgumentsValidator.php
51 lines (42 loc) · 1.62 KB
/
ArgumentsValidator.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
<?php
namespace Matthias\SymfonyServiceDefinitionValidator;
use Matthias\SymfonyServiceDefinitionValidator\Exception\MissingRequiredArgumentException;
class ArgumentsValidator implements ArgumentsValidatorInterface
{
private $argumentValidator;
public function __construct(ArgumentValidatorInterface $argumentValidator)
{
$this->argumentValidator = $argumentValidator;
}
public function validate(\ReflectionFunctionAbstract $method, array $arguments)
{
foreach ($method->getParameters() as $parameterNumber => $parameter) {
if (array_key_exists($parameterNumber, $arguments)) {
$this->argumentValidator->validate($parameter, $arguments[$parameterNumber]);
} else {
if ($this->shouldParameterHaveAnArgument($parameter)) {
throw new MissingRequiredArgumentException(
$parameter->getDeclaringClass()->getName(),
$parameter->getName()
);
}
}
}
}
private function shouldParameterHaveAnArgument(\ReflectionParameter $parameter)
{
if ($parameter->isOptional()) {
// any last argument with a default value is optional
return false;
}
if ($parameter->isDefaultValueAvailable()) {
// e.g. $username = 'root'
return false;
}
if ($parameter->getType() instanceof \ReflectionType && $parameter->getType()->allowsNull()) {
// e.g. LoggerInterface $logger = null
return false;
}
return true;
}
}