Completed
Push — master ( 1092e2...11ab51 )
by Alexander
06:55
created

ErrorResponseBuilder::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 6
rs 9.4285
1
<?php
2
3
namespace Flugg\Responder\Http;
4
5
use Illuminate\Contracts\Routing\ResponseFactory;
6
use InvalidArgumentException;
7
use Symfony\Component\Translation\TranslatorInterface;
8
9
/**
10
 * This class represents an error response. An error response is responsible for translating
11
 * and resolving messages from error code and turning them into an error JSON response.
12
 *
13
 * @package flugger/laravel-responder
14
 * @author  Alexander Tømmerås <[email protected]>
15
 * @license The MIT License
16
 */
17
class ErrorResponseBuilder extends ResponseBuilder
18
{
19
    /**
20
     * Optional error data appended with the response.
21
     *
22
     * @var array
23
     */
24
    protected $data = [];
25
26
    /**
27
     * The error code used to identify the error.
28
     *
29
     * @var string
30
     */
31
    protected $errorCode;
32
33
    /**
34
     * A descriptive error message explaining what went wrong.
35
     *
36
     * @var string
37
     */
38
    protected $message;
39
40
    /**
41
     * Any parameters used to build the error message.
42
     *
43
     * @var array
44
     */
45
    protected $parameters = [];
46
47
    /**
48
     * The HTTP status code for the response.
49
     *
50
     * @var int
51
     */
52
    protected $statusCode = 500;
53
54
    /**
55
     * Translator service used for translating stuff.
56
     *
57
     * @var \Symfony\Component\Translation\TranslatorInterface
58
     */
59
    protected $translator;
60
61
    /**
62
     * Constructor.
63
     *
64
     * @param \Illuminate\Contracts\Routing\ResponseFactory      $responseFactory
65
     * @param \Symfony\Component\Translation\TranslatorInterface $translator
66
     */
67
    public function __construct(ResponseFactory $responseFactory, TranslatorInterface $translator)
68
    {
69
        $this->translator = $translator;
70
71
        parent::__construct($responseFactory);
72
    }
73
74
    /**
75
     * Add additonal data appended to the error object.
76
     *
77
     * @param  array $data
78
     * @return self
79
     */
80
    public function addData(array $data):ErrorResponseBuilder
81
    {
82
        $this->data = array_merge($this->data, $data);
83
84
        return $this;
85
    }
86
87
    /**
88
     * Set the error code and optionally an error message.
89
     *
90
     * @param  string            $errorCode
0 ignored issues
show
Documentation introduced by
Should the type for parameter $errorCode not be null|string?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
91
     * @param  string|array|null $message
92
     * @return self
93
     */
94
    public function setError(string $errorCode = null, $message = null):ErrorResponseBuilder
95
    {
96
        $this->errorCode = $errorCode;
97
98
        if (is_array($message)) {
99
            $this->parameters = $message;
100
        } else {
101
            $this->message = $message;
102
        }
103
104
        return $this;
105
    }
106
107
    /**
108
     * Set the HTTP status code for the response.
109
     *
110
     * @param  int $statusCode
111
     * @return self
112
     * @throws \InvalidArgumentException
113
     */
114 View Code Duplication
    public function setStatus(int $statusCode):ResponseBuilder
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
115
    {
116
        if ($statusCode < 400 || $statusCode >= 600) {
117
            throw new InvalidArgumentException("{$statusCode} is not a valid error HTTP status code.");
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $statusCode instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
118
        }
119
120
        return parent::setStatus($statusCode);
121
    }
122
123
    /**
124
     * Serialize the data and return as an array.
125
     *
126
     * @return array
127
     */
128
    public function toArray():array
129
    {
130
        return [
131
            'success' => false,
132
            'error' => $this->buildErrorData()
133
        ];
134
    }
135
136
    /**
137
     * Build the error object of the serialized response data.
138
     *
139
     * @return array|null
140
     */
141
    protected function buildErrorData()
142
    {
143
        if (is_null($this->errorCode)) {
144
            return null;
145
        }
146
147
        $data = [
148
            'code' => $this->errorCode,
149
            'message' => $this->message ?: $this->resolveMessage()
150
        ];
151
152
        return array_merge($data, $this->data);
153
    }
154
155
    /**
156
     * Resolve an error message from the translator.
157
     *
158
     * @return string|null
159
     */
160
    protected function resolveMessage()
161
    {
162
        if (! $this->translator->has($code = "errors.$this->errorCode")) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Translation\TranslatorInterface as the method has() does only exist in the following implementations of said interface: Illuminate\Translation\Translator.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $this instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
163
            return null;
164
        }
165
166
        return $this->translator->trans($code, $this->parameters);
167
    }
168
}