Completed
Pull Request — master (#5)
by ARCANEDEV
02:28
created

FormRequest   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 4
c 0
b 0
f 0
lcom 1
cbo 1
dl 0
loc 69
ccs 0
cts 21
cp 0
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A response() 0 6 2
A getJsonResponse() 0 7 1
A formatJsonResponseErrors() 0 8 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
    public function response(array $errors)
39
    {
40
        return $this->expectsJson()
41
            ? $this->getJsonResponse($errors)
42
            : 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
    protected function getJsonResponse($errors)
58
    {
59
        return new JsonResponse(
60
            $this->formatJsonResponseErrors($errors),
61
            $this->statusCode
62
        );
63
    }
64
65
    /**
66
     * Format the json response.
67
     *
68
     * @param  array  $errors
69
     *
70
     * @return array
71
     */
72
    protected function formatJsonResponseErrors(array $errors)
73
    {
74
        return [
75
            'code'     => 'validation_failed',
76
            'status'   => $this->statusCode,
77
            'messages' => $errors,
78
        ];
79
    }
80
}
81