1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of the Ray.WebFormModule package. |
4
|
|
|
* |
5
|
|
|
* @license http://opensource.org/licenses/MIT MIT |
6
|
|
|
*/ |
7
|
|
|
namespace Ray\WebFormModule; |
8
|
|
|
|
9
|
|
|
use Doctrine\Common\Annotations\Reader; |
10
|
|
|
use Ray\Aop\MethodInvocation; |
11
|
|
|
use Ray\WebFormModule\Annotation\AbstractValidation; |
12
|
|
|
use Ray\WebFormModule\Annotation\VndError; |
13
|
|
|
use Ray\WebFormModule\Exception\ValidationException; |
14
|
|
|
|
15
|
|
|
final class VndErrorHandler implements FailureHandlerInterface |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @var Reader |
19
|
|
|
*/ |
20
|
|
|
private $reader; |
21
|
|
|
|
22
|
5 |
|
public function __construct(Reader $reader) |
23
|
|
|
{ |
24
|
5 |
|
$this->reader = $reader; |
25
|
5 |
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* {@inheritdoc} |
29
|
|
|
*/ |
30
|
4 |
|
public function handle(AbstractValidation $formValidation, MethodInvocation $invocation, AbstractForm $form) |
31
|
|
|
{ |
32
|
4 |
|
unset($formValidation); |
33
|
4 |
|
$vndError = $this->reader->getMethodAnnotation($invocation->getMethod(), VndError::class); |
34
|
4 |
|
$error = new FormValidationError($this->makeVndError($form, $vndError)); |
|
|
|
|
35
|
|
|
|
36
|
4 |
|
throw new ValidationException('Validation failed.', 400, null, $error); |
37
|
|
|
} |
38
|
|
|
|
39
|
4 |
|
private function makeVndError(AbstractForm $form, VndError $vndError = null) |
|
|
|
|
40
|
|
|
{ |
41
|
4 |
|
$body = ['message' => 'Validation failed']; |
42
|
4 |
|
$body['path'] = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : ''; |
43
|
4 |
|
$body['validation_messages'] = $form->getFailureMessages(); |
44
|
4 |
|
$body = $vndError ? $this->optionalAttribute($vndError) + $body : $body; |
45
|
|
|
|
46
|
4 |
|
return $body; |
47
|
|
|
} |
48
|
|
|
|
49
|
1 |
|
private function optionalAttribute(VndError $vndError) |
50
|
|
|
{ |
51
|
1 |
|
$body = []; |
52
|
1 |
|
if ($vndError->message) { |
53
|
1 |
|
$body['message'] = $vndError->message; |
54
|
|
|
} |
55
|
1 |
|
if ($vndError->path) { |
56
|
1 |
|
$body['path'] = $vndError->path; |
57
|
|
|
} |
58
|
1 |
|
if ($vndError->logref) { |
59
|
1 |
|
$body['logref'] = $vndError->logref; |
60
|
|
|
} |
61
|
|
|
|
62
|
1 |
|
return $body; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:
If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.