Completed
Push — master ( 1459ee...4560a8 )
by David
03:37
created

ApiController::respondNotFound()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 9
rs 9.6667
cc 1
eloc 6
nc 1
nop 1
1
<?php 
2
3
namespace App\Http\Controllers\Api\V1;
4
5
use Illuminate\Database\Eloquent\ModelNotFoundException;
6
use Illuminate\Contracts\Validation\ValidationException;
7
use Illuminate\Foundation\Bus\DispatchesCommands;
8
use Illuminate\Foundation\Validation\ValidatesRequests;
9
use Illuminate\Routing\Controller as BaseController;
10
11
use Chrisbjr\ApiGuard\Http\Controllers\ApiGuardController;
12
13
abstract class ApiController extends ApiGuardController
14
{
15
    /**
16
     * Laraponse object, which abstracts Fractal
17
     * 
18
     * @var EllipseSynergie\ApiResponse\Laravel\Response
19
     */
20
    public $response;
21
    
22
    /**
23
     * The string name of the Eloquen Model
24
     * 
25
     * @var string
26
     */
27
    protected $modelName;
28
    
29
    /**
30
     * The Eloquent Model
31
     * 
32
     * @var Illuminate\Database\Eloquent\Model
33
     */
34
    protected $model;
35
    
36
    /**
37
     * The string name of the Transformer class
38
     * 
39
     * @var string
40
     */
41
    protected $transformerName;
42
    
43
    /**
44
     * The name of the collection that is returned in the JSON response
45
     * 
46
     * @var string
47
     */
48
    protected $collectionName;
49
    
50
    /**
51
     * The Fractal Manager
52
     * 
53
     * @var \League\Fractal\Manager
54
     */
55
    public $manager;
56
57
58
    /**
59
     * Constructor
60
     */
61
    public function __construct()
62
    {
63
        $this->response =  \Response::api();
0 ignored issues
show
Bug introduced by
The method api() does not seem to exist on object<Illuminate\Contra...outing\ResponseFactory>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
64
        
65
        if (!empty($this->modelName)) {
66
            $this->model = new $this->modelName;
67
        }
68
69
        // if no collection name provided, use the model's table name
70
        if (empty($this->collectionName)) {
71
            $this->collectionName = $this->model->getTable();
72
        }
73
        
74
        // parse includes
75
        if (\Input::get('include') != '') {
76
            $this->manager = new \League\Fractal\Manager;
77
            $this->manager->parseIncludes(explode(',', \Input::get('include')));
78
        }
79
80
        parent::__construct();
81
    }
82
83
    /**
84
     * Create an item
85
     * 
86
     * @return \Illuminate\Http\JsonResponse
87
     */
88
    public function create($data = null)
89
    {   
90
        $data = $data ?: \Input::json()->all();
91
92
        try {
93
            $this->model->validate($data);
94
            $item = $this->model->create($data);
95
            
96
            return $this->showByObject($item);
97
        
98
        } catch (ValidationException $e) {
99
            return $this->response->setStatusCode(422)->withError($e->errors()->toArray(), 'GEN-UNPROCESSABLE-ENTITY');
100
        }
101
    }
102
103
    /**
104
     * Returns a single item
105
     * 
106
     * @param  int $id
107
     * @return \Illuminate\Http\JsonResponse
108
     */
109
    public function show($id)
110
    {        
111
        try {
112
            
113
            return $this->response->withItem($this->model->findOrFail($id), new $this->transformerName);
114
        
115
        } catch (ModelNotFoundException $e) {
116
117
            return $this->respondNotFound();
118
        }
119
    }
120
121
    /**
122
     * Returns a single item
123
     * 
124
     * @param  object $object
125
     * @return \Illuminate\Http\JsonResponse
126
     */
127
    public function showByObject($object)
128
    {        
129
        try {
130
            return $this->response->withItem($object, new $this->transformerName);
131
        
132
        } catch (ModelNotFoundException $e) {
133
134
            return $this->respondNotFound();
135
        }
136
    }
137
138
    /**
139
     * Returns a paginated collection
140
     * 
141
     * @return \Illuminate\Http\JsonResponse
142
     */
143
    public function collection()
144
    {
145
        $limit = \Input::get('limit') ?: 10;
146
        $model = $this->model;
147
        
148
        if (\Request::has('order')) {
149
            list($orderCol, $orderBy) = explode('|', \Input::get('order'));
150
            $model = $model->orderBy($orderCol, $orderBy);
151
        }
152
153
        return $this->response->withPaginator($model->paginate($limit), new $this->transformerName, $this->collectionName);
154
    }
155
156
    /**
157
     * Handles 404 errors
158
     * 
159
     * @param  string $msg
160
     * @return \Illuminate\Http\JsonResponse
161
     */
162
    public function respondNotFound($msg = 'Not found!')
163
    {
164
        return \Response::json([
165
            'error' => [
166
                'message' => $msg,
167
                'status_code' => 404
168
            ]
169
        ], 404);
170
    }
171
}