1 | <?php |
||
10 | class RequestObjectBinder |
||
11 | { |
||
12 | /** |
||
13 | * @var ValidatorInterface |
||
14 | */ |
||
15 | private $validator; |
||
16 | |||
17 | /** |
||
18 | * @var PayloadResolver |
||
19 | */ |
||
20 | private $payloadResolver; |
||
21 | |||
22 | /** |
||
23 | * @var ErrorResponseProvider|null |
||
24 | */ |
||
25 | private $errorResponseProvider; |
||
26 | |||
27 | /** |
||
28 | * RequestObjectBinder constructor. |
||
29 | * |
||
30 | * @param PayloadResolver $payloadResolver |
||
31 | * @param ValidatorInterface $validator |
||
32 | * @param ErrorResponseProvider|null $errorResponseProvider |
||
33 | */ |
||
34 | public function __construct( |
||
43 | |||
44 | /** |
||
45 | * @param Request $request |
||
46 | * @param callable $action |
||
47 | * |
||
48 | * @return Response|void |
||
49 | */ |
||
50 | public function bind(Request $request, callable $action) |
||
51 | { |
||
52 | $matchedArguments = $this->matchActionArguments($action); |
||
53 | if (!array_key_exists('requestObject', $matchedArguments)) { |
||
54 | return; |
||
55 | } |
||
56 | |||
57 | $requestObjectClass = $matchedArguments['requestObject']->getClass()->name; |
||
58 | /** @var RequestObject $requestObject */ |
||
59 | $requestObject = new $requestObjectClass(); |
||
60 | $request->attributes->set( |
||
61 | $matchedArguments['requestObject']->name, |
||
62 | $requestObject |
||
63 | ); |
||
64 | |||
65 | $payload = $this->resolvePayload($requestObject, $request); |
||
66 | |||
67 | $errors = $this->validator->validate( |
||
68 | $payload, |
||
69 | $requestObject->rules(), |
||
70 | $requestObject->validationGroup($payload) |
||
71 | ); |
||
72 | |||
73 | $requestObject->setPayload($payload); |
||
74 | if (array_key_exists('errors', $matchedArguments)) { |
||
75 | $request->attributes->set($matchedArguments['errors']->name, $errors); |
||
76 | } elseif ($errors && 0 !== $errors->count()) { |
||
77 | return $this->providerErrorResponse($requestObject, $errors); |
||
78 | } |
||
79 | } |
||
80 | |||
81 | /** |
||
82 | * @param RequestObject $requestObject |
||
83 | * @param ConstraintViolationListInterface $errors |
||
84 | * |
||
85 | * @return Response |
||
86 | * |
||
87 | * @throws InvalidRequestPayloadException |
||
88 | */ |
||
89 | private function providerErrorResponse(RequestObject $requestObject, ConstraintViolationListInterface $errors) |
||
101 | |||
102 | /** |
||
103 | * @param callable $action |
||
104 | * |
||
105 | * @return array |
||
106 | */ |
||
107 | private function matchActionArguments(callable $action) |
||
133 | |||
134 | private function resolvePayload(RequestObject $requestObject, Request $request) |
||
142 | |||
143 | /** |
||
144 | * @param \ReflectionParameter $argument |
||
145 | * @param string $subtype |
||
146 | * |
||
147 | * @return bool |
||
148 | */ |
||
149 | private function isArgumentIsSubtypeOf(\ReflectionParameter $argument, $subtype) |
||
157 | } |
||
158 |