1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* This file is part of the reva2/jsonapi. |
4
|
|
|
* |
5
|
|
|
* (c) Sergey Revenko <[email protected]> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
|
12
|
|
|
namespace Reva2\JsonApi\Services; |
13
|
|
|
|
14
|
|
|
use Neomerx\JsonApi\Contracts\Encoder\Parameters\EncodingParametersInterface; |
15
|
|
|
use Neomerx\JsonApi\Document\Error; |
16
|
|
|
use Reva2\JsonApi\Contracts\Services\ValidationServiceInterface; |
17
|
|
|
use Symfony\Component\Validator\Validator\ValidatorInterface; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* JSON API validation service that use symfony/validator component |
21
|
|
|
* |
22
|
|
|
* @package Reva2\JsonApi\Services |
23
|
|
|
* @author Sergey Revenko <[email protected]> |
24
|
|
|
*/ |
25
|
|
|
class ValidationService implements ValidationServiceInterface |
26
|
|
|
{ |
27
|
|
|
/** |
28
|
|
|
* @var ValidatorInterface |
29
|
|
|
*/ |
30
|
|
|
protected $validator; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* ValidationService constructor. |
34
|
|
|
* @param ValidatorInterface $validator |
35
|
|
|
*/ |
36
|
6 |
|
public function __construct(ValidatorInterface $validator) |
37
|
|
|
{ |
38
|
6 |
|
$this->validator = $validator; |
39
|
6 |
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @inheritdoc |
43
|
|
|
*/ |
44
|
1 |
|
public function validate($data, array $groups = null) |
45
|
|
|
{ |
46
|
1 |
|
$errors = []; |
47
|
|
|
|
48
|
1 |
|
$violations = $this->validator->validate($data, null, $groups); |
|
|
|
|
49
|
1 |
|
foreach ($violations as $violation) { |
50
|
|
|
/* @var $violation \Symfony\Component\Validator\ConstraintViolationInterface */ |
51
|
|
|
|
52
|
|
|
if ($data instanceof EncodingParametersInterface) { |
53
|
|
|
$source = ['parameter' => $violation->getPropertyPath()]; |
54
|
|
|
} else { |
55
|
|
|
$source = ['pointer' => $this->prepareSourcePath($violation->getPropertyPath())]; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
$errors[] = new Error( |
59
|
|
|
rand(), |
60
|
|
|
null, |
61
|
|
|
422, |
62
|
|
|
$violation->getCode(), |
63
|
|
|
$violation->getMessage(), |
64
|
|
|
null, |
65
|
|
|
$source |
66
|
|
|
); |
67
|
1 |
|
} |
68
|
|
|
|
69
|
1 |
|
return $errors; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @param string $path |
74
|
|
|
* @return string |
75
|
|
|
*/ |
76
|
|
|
private function prepareSourcePath($path) |
77
|
|
|
{ |
78
|
|
|
return '/' . trim(preg_replace('~[\/]+~si', '/', str_replace(['.', '[', ']'], '/', (string) $path)), '/'); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
This check looks at variables that have been passed in as parameters and are passed out again to other methods.
If the outgoing method call has stricter type requirements than the method itself, an issue is raised.
An additional type check may prevent trouble.