Completed
Push — master ( 2d5c6f...ea456d )
by Alexander
06:30
created

ErrorResponseFactory::make()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 3
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Flugg\Responder\Factories;
4
5
use Illuminate\Http\JsonResponse;
6
7
/**
8
 *
9
 *
10
 * @package Laravel Responder
11
 * @author  Alexander Tømmerås <[email protected]>
12
 * @license The MIT License
13
 */
14
class ErrorResponseFactory extends ResponseFactory
15
{
16
    /**
17
     * Generate a successful JSON response.
18
     *
19
     * @param  mixed $errorCode
20
     * @param  int   $statusCode
21
     * @param  array $message
22
     * @return JsonResponse
23
     */
24
    public function make( $errorCode, $statusCode = 500, $message = [ ] ):JsonResponse
25
    {
26
        $response = $this->getErrorResponse( $errorCode, $statusCode );
27
        $messages = $this->getErrorMessages( $errorCode, $message );
28
29
        if ( count( $messages ) === 1 ) {
30
            $response[ 'error' ][ 'message' ] = $messages[ 0 ];
31
        } else if ( count( $messages ) > 1 ) {
32
            $response[ 'error' ][ 'messages' ] = $messages;
33
        }
34
35
        return response()->json( $response, $statusCode );
36
    }
37
38
    /**
39
     * Get the skeleton for an error response.
40
     *
41
     * @param string $errorCode
42
     * @param int    $statusCode
43
     * @return array
44
     */
45
    protected function getErrorResponse( string $errorCode, int $statusCode ):array
46
    {
47
        $response = [
48
            'success' => false,
49
            'error' => [
50
                'code' => $errorCode
51
            ]
52
        ];
53
54
        return $this->includeStatusCode( $statusCode, $response );
55
    }
56
57
    /**
58
     * Get any error messages for the response. If no message can be found it will
59
     * try to resolve a set message from the translator.
60
     *
61
     * @param  string $errorCode
62
     * @param  mixed  $message
63
     * @return array
64
     */
65
    protected function getErrorMessages( string $errorCode, $message ):array
66
    {
67
        if ( is_array( $message ) ) {
68
            return $message;
69
70
        } elseif ( is_string( $message ) ) {
71
            if ( strlen( $message ) === 0 ) {
72
                return [ ];
73
            }
74
75
            return [ $message ];
76
        }
77
78
        return [ app( 'translator' )->trans( 'errors.' . $errorCode ) ];
79
    }
80
}