Completed
Push — master ( 0ee51e...87b17e )
by Josh
13:36
created

Controller::errorArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace NavJobs\Transmit;
4
5
use Illuminate\Database\Eloquent\Builder;
6
use Illuminate\Support\Facades\App;
7
use Illuminate\Support\Facades\Input;
8
use NavJobs\Transmit\Traits\QueryHelperTrait;
9
use Illuminate\Routing\Controller as BaseController;
10
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
11
12
abstract class Controller extends BaseController
13
{
14
    use QueryHelperTrait;
15
16
    protected $statusCode = 200;
17
    protected $fractal;
18
19
    public function __construct()
20
    {
21
        $this->fractal = App::make(Fractal::class);
22
23
        $this->parseIncludes();
24
    }
25
26
    /**
27
     * Parses includes from either the header or query string.
28
     *
29
     * @return mixed
30
     */
31
    protected function parseIncludes()
32
    {
33
        if (Input::header('include')) {
34
            return $this->fractal->parseIncludes(Input::header('include'));
35
        }
36
37
        if (Input::get('include')) {
38
            return $this->fractal->parseIncludes(Input::get('include'));
39
        }
40
41
        return null;
42
    }
43
44
    /**
45
     * Returns the current status code.
46
     *
47
     * @return int
48
     */
49
    protected function getStatusCode()
50
    {
51
        return $this->statusCode;
52
    }
53
54
    /**
55
     * Sets the current status code.
56
     *
57
     * @param $statusCode
58
     * @return $this
59
     */
60
    protected function setStatusCode($statusCode)
61
    {
62
        $this->statusCode = $statusCode;
63
64
        return $this;
65
    }
66
67
    /**
68
     * Returns a json response that contains the specified resource
69
     * passed through fractal and optionally a transformer.
70
     *
71
     * @param $item
72
     * @param null $callback
73
     * @param null $resourceKey
74
     * @return \Illuminate\Http\JsonResponse
75
     */
76
    protected function respondWithItem($item, $callback = null, $resourceKey = null)
77
    {
78
        $rootScope = $this->fractal->item($item, $callback, $resourceKey);
79
80
        return $this->respondWithArray($rootScope->toArray());
81
    }
82
83
    /**
84
     * Returns a json response that indicates the resource was successfully created also
85
     * returns the resource passed through fractal and optionally a transformer.
86
     *
87
     * @param $item
88
     * @param null $callback
89
     * @param null $resourceKey
90
     * @return \Illuminate\Http\JsonResponse
91
     */
92 View Code Duplication
    protected function respondWithItemCreated($item, $callback = null, $resourceKey = null)
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...
93
    {
94
        $this->setStatusCode(201);
95
        $rootScope = $this->fractal->item($item, $callback, $resourceKey);
96
97
        return $this->respondWithArray($rootScope->toArray());
98
    }
99
100
    /**
101
     * Returns a json response that contains the specified collection
102
     * passed through fractal and optionally a transformer.
103
     *
104
     * @param $collection
105
     * @param $callback
106
     * @param null $resourceKey
107
     * @return \Illuminate\Http\JsonResponse
108
     */
109
    protected function respondWithCollection($collection, $callback, $resourceKey = null)
110
    {
111
        $rootScope = $this->fractal->collection($collection, $callback, $resourceKey);
112
113
        return $this->respondWithArray($rootScope->toArray());
114
    }
115
116
    /**
117
     * Returns a json response that contains the specified paginated collection
118
     * passed through fractal and optionally a transformer.
119
     *
120
     * @param $builder
121
     * @param $callback
122
     * @param int $perPage
123
     * @param null $resourceKey
124
     * @return \Illuminate\Http\JsonResponse
125
     */
126
    protected function respondWithPaginatedCollection(Builder $builder, $callback, $perPage = 10, $resourceKey = null)
127
    {
128
        $paginator = $builder->paginate($perPage);
129
        $paginator->appends($this->getQueryParameters());
130
131
        $rootScope = $this->fractal
132
            ->collection($paginator->getCollection(), $callback, $resourceKey)
133
            ->paginateWith(new IlluminatePaginatorAdapter($paginator));
134
135
        return $this->respondWithArray($rootScope->toArray());
136
    }
137
138
    /**
139
     * Returns an array of Query Parameters, not including pagination.
140
     *
141
     * @return array
142
     */
143
    protected function getQueryParameters()
0 ignored issues
show
Coding Style introduced by
getQueryParameters uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
144
    {
145
        return array_diff_key($_GET, array_flip(['page']));
146
    }
147
148
    /**
149
     * Returns a json response that contains the specified array,
150
     * the current status code and optional headers.
151
     *
152
     * @param array $array
153
     * @param array $headers
154
     * @return \Illuminate\Http\JsonResponse
155
     */
156
    protected function respondWithArray(array $array, array $headers = [])
157
    {
158
        return response()->json($array, $this->statusCode, $headers);
159
    }
160
161
    /**
162
     * Returns a response that indicates success but no content returned.
163
     *
164
     * @return \Illuminate\Http\Response
165
     */
166
    protected function respondWithNoContent()
167
    {
168
        return response()->make('', 204);
169
    }
170
171
    /**
172
     * Returns a response that indicates a 403 Forbidden.
173
     *
174
     * @param string $message
175
     * @return \Illuminate\Http\JsonResponse
176
     */
177
    protected function errorForbidden($message = 'Forbidden')
178
    {
179
        return $this->setStatusCode(403)->respondWithError($message);
180
    }
181
182
    /**
183
     * Returns a response that indicates an Internal Error has occurred.
184
     *
185
     * @param string $message
186
     * @return \Illuminate\Http\JsonResponse
187
     */
188
    protected function errorInternalError($message = 'Internal Error')
189
    {
190
        return $this->setStatusCode(500)->respondWithError($message);
191
    }
192
193
    /**
194
     * Returns a response that indicates a 404 Not Found.
195
     *
196
     * @param string $message
197
     * @return \Illuminate\Http\JsonResponse
198
     */
199
    protected function errorNotFound($message = 'Resource Not Found')
200
    {
201
        return $this->setStatusCode(404)->respondWithError($message);
202
    }
203
204
    /**
205
     * Returns a response that indicates a 401 Unauthorized.
206
     *
207
     * @param string $message
208
     * @return \Illuminate\Http\JsonResponse
209
     */
210
    protected function errorUnauthorized($message = 'Unauthorized')
211
    {
212
        return $this->setStatusCode(401)->respondWithError($message);
213
    }
214
215
    /**
216
     * Returns a response that indicates a 422 Unprocessable Entity.
217
     *
218
     * @param string $message
219
     * @return \Illuminate\Http\JsonResponse
220
     */
221
    protected function errorUnprocessableEntity($message = 'Unprocessable Entity')
222
    {
223
        return $this->setStatusCode(422)->respondWithError($message);
224
    }
225
226
    /**
227
     * Returns a response that indicates the wrong arguments were specified.
228
     *
229
     * @param string $message
230
     * @return \Illuminate\Http\JsonResponse
231
     */
232
    protected function errorWrongArgs($message = 'Wrong Arguments')
233
    {
234
        return $this->setStatusCode(400)->respondWithError($message);
235
    }
236
237
    /**
238
     * Returns a response that indicates custom error type.
239
     *
240
     * @param $message
241
     * @param $statusCode
242
     * @return \Illuminate\Http\JsonResponse
243
     */
244
    protected function errorCustomType($message, $statusCode = 400)
245
    {
246
        return $this->setStatusCode($statusCode)->respondWithError($message);
247
    }
248
249
    /**
250
     * Returns a response that indicates multiple errors in an array.
251
     *
252
     * @param array $errors
253
     * @return \Illuminate\Http\JsonResponse
254
     */
255
    protected function errorArray(array $errors)
256
    {
257
        return $this->setStatusCode(422)->respondWithArray(['errors' => $errors]);
258
    }
259
260
    /**
261
     * Returns a response that indicates an an error occurred.
262
     *
263
     * @param $message
264
     * @return \Illuminate\Http\JsonResponse
265
     */
266
    private function respondWithError($message)
267
    {
268
        return $this->respondWithArray([
269
            'errors' => [
270
                'http_code' => $this->statusCode,
271
                'message'   => $message,
272
            ]
273
        ]);
274
    }
275
}
276