Completed
Push — master ( a60631...6c51f7 )
by Elf
02:53
created

ApiResponse::statusCode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
ccs 0
cts 4
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace ElfSundae\Laravel\Api;
4
5
use Illuminate\Http\JsonResponse;
6
use Illuminate\Database\Eloquent\Model;
7
8
class ApiResponse extends JsonResponse
9
{
10
    /**
11
     * The api result code.
12
     *
13
     * @var int
14
     */
15
    protected $code;
16
17
    /**
18
     * The keys which value should be clean.
19
     *
20
     * @var array|null
21
     */
22
    protected $cleanKeys;
23
24
    /**
25
     * Create an ApiResponse instance.
26
     *
27
     * @param  mixed  $data
28
     * @param  int|null  $code
29
     * @param  array  $headers
30
     * @param  int  $options
31
     */
32
    public function __construct($data = null, $code = null, $headers = [], $options = 0)
33
    {
34
        $this->code = is_null($code) ? static::successCode() : (int) $code;
35
36
        parent::__construct($data, 200, $headers, $options);
37
    }
38
39
    /**
40
     * Get the code key.
41
     *
42
     * @return string
43
     */
44
    public static function codeKey()
45
    {
46
        static $codeKey = null;
47
48
        if (is_null($codeKey)) {
49
            $codeKey = config('api.response.key.code', 'code');
50
        }
51
52
        return $codeKey;
53
    }
54
55
    /**
56
     * Get the message key.
57
     *
58
     * @return string
59
     */
60
    public static function messageKey()
61
    {
62
        static $messageKey = null;
63
64
        if (is_null($messageKey)) {
65
            $messageKey = config('api.response.key.message', 'msg');
66
        }
67
68
        return $messageKey;
69
    }
70
71
    /**
72
     * Get the success code.
73
     *
74
     * @return int
75
     */
76
    public static function successCode()
77
    {
78
        static $successCode = null;
79
80
        if (is_null($successCode)) {
81
            $successCode = (int) config('api.response.code.success', 1);
82
        }
83
84
        return $successCode;
85
    }
86
87
    /**
88
     * Sets the data to be sent as JSON.
89
     *
90
     * @param  mixed  $data
91
     * @return $this
92
     */
93
    public function setData($data = null)
94
    {
95
        if ($data instanceof Model) {
0 ignored issues
show
Bug introduced by
The class Illuminate\Database\Eloquent\Model does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
96
            $data = [
97
                snake_case(class_basename($data)) => $this->convertObjectToArray($data),
98
            ];
99
        } elseif (is_object($data)) {
100
            $data = $this->convertObjectToArray($data);
101
        } elseif (is_null($data)) {
102
            $data = [];
103
        } elseif (is_string($data)) {
104
            $data = [static::messageKey() => $data];
105
        } elseif (! is_array($data)) {
106
            $data = [static::messageKey() => json_encode($data)];
107
        }
108
109
        if (! array_key_exists(static::codeKey(), $data)) {
110
            $data[static::codeKey()] = $this->getCode();
111
        }
112
113
        if (! is_null($this->cleanKeys)) {
114
            $data = $this->cleanArray($data, $this->cleanKeys);
115
        }
116
117
        return parent::setData($data);
118
    }
119
120
    /**
121
     * Convert an object to array.
122
     *
123
     * @param  mixed  $object
124
     * @return array
125
     */
126
    protected function convertObjectToArray($object)
127
    {
128
        if (method_exists($object, 'toArray')) {
129
            return $object->toArray();
130
        }
131
132
        return json_decode(json_encode($object, true), true);
133
    }
134
135
    /**
136
     * Clean the given array.
137
     *
138
     * @param  array  $array
139
     * @param  array|null  $keys
140
     * @return array
141
     */
142
    protected function cleanArray($array, $keys = null)
143
    {
144
        $keys = $keys ?: array_keys($array);
145
146
        foreach ($keys as $key) {
147
            if (is_array($value = array_get($array, $key))) {
148
                array_set($array, $key, array_filter($value));
149
            }
150
        }
151
152
        return $array;
153
    }
154
155
    /**
156
     * Merge new data into the current data.
157
     *
158
     * @param  array  ...$data
159
     * @return $this
160
     */
161
    public function mergeData(array ...$data)
162
    {
163
        return $this->setData(array_replace($this->getData(true), ...$data));
164
    }
165
166
    /**
167
     * Get the api result code.
168
     *
169
     * @return int
170
     */
171
    public function getCode()
172
    {
173
        return $this->code;
174
    }
175
176
    /**
177
     * Set the api result code.
178
     *
179
     * @param  int  $code
180
     * @return $this
181
     */
182
    public function setCode($code)
183
    {
184
        $this->code = (int) $code;
185
186
        return $this->mergeData([static::codeKey() => $this->code]);
187
    }
188
189
    /**
190
     * Set the api result code.
191
     *
192
     * @param  int  $code
193
     * @return $this
194
     */
195
    public function code($code)
196
    {
197
        return $this->setCode($code);
198
    }
199
200
    /**
201
     * Get the api result message.
202
     *
203
     * @return string
204
     */
205
    public function getMessage()
206
    {
207
        return array_get($this->getData(true), static::messageKey());
208
    }
209
210
    /**
211
     * Set the api result message.
212
     *
213
     * @param  string  $message
214
     * @return $this
215
     */
216
    public function setMessage($message)
217
    {
218
        return $this->mergeData([static::messageKey() => (string) $message]);
219
    }
220
221
    /**
222
     * Set the api result message.
223
     *
224
     * @param  string  $message
225
     * @return $this
226
     */
227
    public function message($message)
228
    {
229
        return $this->setMessage($message);
230
    }
231
232
    /**
233
     * Get the keys which value should be clean.
234
     *
235
     * @return array|null
236
     */
237
    public function getCleanKeys()
238
    {
239
        return $this->cleanKeys;
240
    }
241
242
    /**
243
     * Set the keys which value should be clean, then clean data.
244
     * The passed $keys can be "dot" notation.
245
     *
246
     * $keys example:
247
     *
248
     * null             -> do not clean anything
249
     * []               -> clean values associated with all root keys
250
     * 'foo', 'foo.bar' -> clean values associated with 'foo' and 'foo'>'bar'
251
     * ['a.b.c', 'd']
252
     *
253
     * @param  string|null|string[]  $keys
254
     * @return $this
255
     */
256
    public function clean($keys = [])
257
    {
258
        if (is_null($keys)) {
259
            $this->cleanKeys = null;
260
261
            return $this;
262
        }
263
264
        $this->cleanKeys = is_array($keys) ? $keys : func_get_args();
265
266
        return $this->setData($this->getData(true));
267
    }
268
269
    /**
270
     * Set the response status code.
271
     *
272
     * @param  int  $code
273
     * @param  mixed  $text
274
     * @return $this
275
     */
276
    public function statusCode($code, $text = null)
277
    {
278
        return $this->setStatusCode($code, $text);
279
    }
280
}
281