JsonApiRequest::formatErrors()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.4285
c 0
b 0
f 0
nc 3
cc 3
eloc 10
nop 1
1
<?php
2
3
namespace Huntie\JsonApi\Http\Requests;
4
5
use Huntie\JsonApi\Http\JsonApiResponse;
6
use Illuminate\Contracts\Validation\Validator;
7
use Illuminate\Foundation\Http\FormRequest;
8
use Illuminate\Http\Response;
9
10
abstract class JsonApiRequest extends FormRequest
11
{
12
    /**
13
     * Format the errors from the given Validator instance.
14
     *
15
     * {@inheritdoc}
16
     */
17
    protected function formatErrors(Validator $validator)
18
    {
19
        $errors = [];
20
21
        foreach ($validator->getMessageBag()->messages() as $field => $messages) {
22
            foreach ($messages as $message) {
23
                $errors[] = [
24
                    'source' => [
25
                        'pointer' => str_replace('.', '/', $field),
26
                    ],
27
                    'title' => 'Invalid attribute',
28
                    'detail' => str_replace('data.attributes.', '', $message),
29
                ];
30
            }
31
        }
32
33
        return compact('errors');
34
    }
35
36
    /**
37
     * Get the proper failed validation response for the request.
38
     *
39
     * @param array $errors
40
     *
41
     * @return JsonApiResponse
42
     */
43
    public function response(array $errors)
44
    {
45
        return new JsonApiResponse($errors, Response::HTTP_UNPROCESSABLE_ENTITY);
46
    }
47
}
48