Completed
Pull Request — master (#3)
by ARCANEDEV
04:49
created

FormRequest::getJsonResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
c 0
b 0
f 0
ccs 5
cts 5
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
crap 1
1
<?php namespace Arcanedev\LaravelApiHelper\Http;
2
3
use Arcanedev\Support\Http\FormRequest as BaseFormRequest;
4
use Illuminate\Http\JsonResponse;
5
6
/**
7
 * Class     FormRequest
8
 *
9
 * @package  Arcanedev\LaravelApiHelper\Http
10
 * @author   ARCANEDEV <[email protected]>
11
 */
12
abstract class FormRequest extends BaseFormRequest
13
{
14
    /* -----------------------------------------------------------------
15
     |  Properties
16
     | -----------------------------------------------------------------
17
     */
18
19
    /**
20
     * Status code when the validation fails.
21
     *
22
     * @var int
23
     */
24
    protected $statusCode = 422;
25
26
    /* -----------------------------------------------------------------
27
     |  Main Methods
28
     | -----------------------------------------------------------------
29
     */
30
31
    /**
32
     * Get the proper failed validation response for the request.
33
     *
34
     * @param  array  $errors
35
     *
36
     * @return \Symfony\Component\HttpFoundation\Response
37
     */
38 3
    public function response(array $errors)
39
    {
40 3
        return $this->expectsJson()
41 3
            ? $this->getJsonResponse($errors)
42 3
            : parent::response($errors);
43
    }
44
45
    /* -----------------------------------------------------------------
46
     |  Other Methods
47
     | -----------------------------------------------------------------
48
     */
49
50
    /**
51
     * Get the json response with validation errors.
52
     *
53
     * @param  array  $errors
54
     *
55
     * @return \Illuminate\Http\JsonResponse
56
     */
57 3
    protected function getJsonResponse($errors)
58
    {
59 3
        return new JsonResponse(
60 3
            $this->formatJsonResponseErrors($errors),
61 3
            $this->statusCode
62 1
        );
63
    }
64
65
    /**
66
     * Format the json response.
67
     *
68
     * @param  array  $errors
69
     *
70
     * @return array
71
     */
72 3
    protected function formatJsonResponseErrors(array $errors)
73
    {
74
        return [
75 3
            'code'     => 'validation_failed',
76 3
            'status'   => $this->statusCode,
77 3
            'messages' => $errors,
78 1
        ];
79
    }
80
}
81