Completed
Push — master ( 0a56af...131f6e )
by Josh
01:52
created

Controller::errorForbidden()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
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\Pagination\Paginator;
6
use Illuminate\Support\Facades\App;
7
use Illuminate\Support\Facades\Input;
8
use Illuminate\Pagination\LengthAwarePaginator;
9
use Illuminate\Routing\Controller as BaseController;
10
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
11
use NavJobs\Transmit\Traits\QueryHelperTrait;
12
13
abstract class Controller extends BaseController
14
{
15
    use QueryHelperTrait;
16
17
    const CODE_WRONG_ARGS = 'GEN-WRONG-ARGS';
18
    const CODE_NOT_FOUND = 'GEN-NOT-FOUND';
19
    const CODE_INTERNAL_ERROR = 'GEN-INTERNAL-ERROR';
20
    const CODE_UNAUTHORIZED = 'GEN-UNAUTHORIZED';
21
    const CODE_FORBIDDEN = 'GEN-FORBIDDEN';
22
23
    protected $statusCode = 200;
24
    protected $fractal;
25
26
    public function __construct()
27
    {
28
        $this->fractal = App::make(Fractal::class);
29
30
        $this->parseIncludes();
31
    }
32
33
    /**
34
     * Parses includes from either the header or query string.
35
     *
36
     * @return mixed
37
     */
38
    protected function parseIncludes()
39
    {
40
        if (Input::header('include')) {
41
            return $this->fractal->parseIncludes(Input::header('include'));
42
        }
43
44
        if (Input::get('include')) {
45
            return $this->fractal->parseIncludes(Input::get('include'));
46
        }
47
48
        return null;
49
    }
50
51
    /**
52
     * Returns the current status code.
53
     *
54
     * @return int
55
     */
56
    protected function getStatusCode()
57
    {
58
        return $this->statusCode;
59
    }
60
61
    /**
62
     * Sets the current status code.
63
     *
64
     * @param $statusCode
65
     * @return $this
66
     */
67
    protected function setStatusCode($statusCode)
68
    {
69
        $this->statusCode = $statusCode;
70
71
        return $this;
72
    }
73
74
    /**
75
     * Returns a json response that contains the specified resource
76
     * passed through fractal and optionally a transformer.
77
     *
78
     * @param $item
79
     * @param null $callback
80
     * @param null $resourceKey
81
     * @return \Illuminate\Http\JsonResponse
82
     */
83
    protected function respondWithItem($item, $callback = null, $resourceKey = null)
84
    {
85
        $rootScope = $this->fractal->item($item, $callback, $resourceKey);
86
87
        return $this->respondWithArray($rootScope->toArray());
88
    }
89
90
    /**
91
     * Returns a json response that indicates the resource was successfully created also
92
     * returns the resource passed through fractal and optionally a transformer.
93
     *
94
     * @param $item
95
     * @param null $callback
96
     * @param null $resourceKey
97
     * @return \Illuminate\Http\JsonResponse
98
     */
99 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...
100
    {
101
        $this->setStatusCode(201);
102
        $rootScope = $this->fractal->item($item, $callback, $resourceKey);
103
104
        return $this->respondWithArray($rootScope->toArray());
105
    }
106
107
    /**
108
     * Returns a json response that contains the specified collection
109
     * passed through fractal and optionally a transformer.
110
     *
111
     * @param $collection
112
     * @param $callback
113
     * @param null $resourceKey
114
     * @return \Illuminate\Http\JsonResponse
115
     */
116
    protected function respondWithCollection($collection, $callback, $resourceKey = null)
117
    {
118
        $rootScope = $this->fractal->collection($collection, $callback, $resourceKey);
119
120
        return $this->respondWithArray($rootScope->toArray());
121
    }
122
123
    /**
124
     * Returns a json response that contains the specified paginated collection
125
     * passed through fractal and optionally a transformer.
126
     *
127
     * @param $collection
128
     * @param $callback
129
     * @param int $perPage
130
     * @param null $resourceKey
131
     * @return \Illuminate\Http\JsonResponse
132
     */
133
    protected function respondWithPaginatedCollection($collection, $callback, $perPage = 10, $resourceKey = null)
134
    {
135
        $paginator = $this->paginateCollection($collection, $perPage);
136
137
        $rootScope = $this->fractal
138
            ->collection($paginator->getCollection(), $callback, $resourceKey)
139
            ->paginateWith(new IlluminatePaginatorAdapter($paginator));
140
141
        return $this->respondWithArray($rootScope->toArray());
142
    }
143
144
    /**
145
     * @param $collection
146
     * @param $perPage
147
     * @return LengthAwarePaginator
148
     */
149
    protected function paginateCollection($collection, $perPage)
150
    {
151
        $paginator = new LengthAwarePaginator(
152
            $collection->forPage(Paginator::resolveCurrentPage(), $perPage),
153
            $collection->count(),
154
            $perPage,
155
            Paginator::resolveCurrentPage(),
156
            ['path' => Paginator::resolveCurrentPath()]
157
        );
158
        $paginator->appends($this->getQueryParameters());
159
160
        return $paginator;
161
    }
162
163
    /**
164
     * Returns an array of Query Parameters, not including pagination.
165
     *
166
     * @return array
167
     */
168
    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...
169
    {
170
        return array_diff_key($_GET, array_flip(['page']));
171
    }
172
173
    /**
174
     * Returns a json response that contains the specified array,
175
     * the current status code and optional headers.
176
     *
177
     * @param array $array
178
     * @param array $headers
179
     * @return \Illuminate\Http\JsonResponse
180
     */
181
    protected function respondWithArray(array $array, array $headers = [])
182
    {
183
        return response()->json($array, $this->statusCode, $headers);
184
    }
185
186
    /**
187
     * Returns a response that indicates success but no content returned.
188
     *
189
     * @return \Illuminate\Http\Response
190
     */
191
    protected function respondWithNoContent()
192
    {
193
        return response()->make('', 204);
194
    }
195
196
    /**
197
     * Returns a response that indicates a 403 Forbidden.
198
     *
199
     * @param string $message
200
     * @return \Illuminate\Http\JsonResponse
201
     */
202
    protected function errorForbidden($message = 'Forbidden')
203
    {
204
        return $this->setStatusCode(403)->respondWithError($message, self::CODE_FORBIDDEN);
205
    }
206
207
    /**
208
     * Returns a response that indicates an Internal Error has occurred.
209
     *
210
     * @param string $message
211
     * @return \Illuminate\Http\JsonResponse
212
     */
213
    protected function errorInternalError($message = 'Internal Error')
214
    {
215
        return $this->setStatusCode(500)->respondWithError($message, self::CODE_INTERNAL_ERROR);
216
    }
217
218
    /**
219
     * Returns a response that indicates a 404 Not Found.
220
     *
221
     * @param string $message
222
     * @return \Illuminate\Http\JsonResponse
223
     */
224
    protected function errorNotFound($message = 'Resource Not Found')
225
    {
226
        return $this->setStatusCode(404)->respondWithError($message, self::CODE_NOT_FOUND);
227
    }
228
229
    /**
230
     * Returns a response that indicates a 401 Unauthorized.
231
     *
232
     * @param string $message
233
     * @return \Illuminate\Http\JsonResponse
234
     */
235
    protected function errorUnauthorized($message = 'Unauthorized')
236
    {
237
        return $this->setStatusCode(401)->respondWithError($message, self::CODE_UNAUTHORIZED);
238
    }
239
240
    /**
241
     * Returns a response that indicates the wrong arguments were specified.
242
     *
243
     * @param string $message
244
     * @return \Illuminate\Http\JsonResponse
245
     */
246
    protected function errorWrongArgs($message = 'Wrong Arguments')
247
    {
248
        return $this->setStatusCode(400)->respondWithError($message, self::CODE_WRONG_ARGS);
249
    }
250
251
    /**
252
     * Returns a response that indicates an an error occurred.
253
     *
254
     * @param $message
255
     * @param $errorCode
256
     * @return \Illuminate\Http\JsonResponse
257
     */
258
    private function respondWithError($message, $errorCode)
259
    {
260
        return $this->respondWithArray([
261
            'error' => [
262
                'code'      => $errorCode,
263
                'http_code' => $this->statusCode,
264
                'message'   => $message,
265
            ]
266
        ]);
267
    }
268
}
269