Completed
Push — master ( bf9518...963b04 )
by David
04:31
created

ApiController::create()   B

Complexity

Conditions 5
Paths 20

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 3
Metric Value
c 4
b 0
f 3
dl 0
loc 19
rs 8.8571
cc 5
eloc 14
nc 20
nop 1
1
<?php 
2
3
namespace App\Http\Controllers\Api\V1;
4
5
use App\LaravelRestCms\ApiInterface;
6
use \Chrisbjr\ApiGuard\Http\Controllers\ApiGuardController;
7
use Illuminate\Database\Eloquent\MassAssignmentException;
8
use Illuminate\Database\Eloquent\ModelNotFoundException;
9
use Illuminate\Contracts\Validation\ValidationException;
10
use Illuminate\Foundation\Bus\DispatchesCommands;
11
use Illuminate\Foundation\Validation\ValidatesRequests;
12
use Illuminate\Http\Request;
13
use Illuminate\Routing\Controller as BaseController;
14
15
abstract class ApiController extends ApiGuardController implements ApiInterface
16
{
17
    /**
18
     * Laraponse object, which abstracts Fractal
19
     * 
20
     * @var \EllipseSynergie\ApiResponse\Laravel\Response
21
     */
22
    public $response;
23
    
24
    /**
25
     * The string name of the Eloquent Model
26
     * 
27
     * @var string
28
     */
29
    protected $modelName;
30
    
31
    /**
32
     * The Eloquent Model
33
     * 
34
     * @var \Illuminate\Database\Eloquent\Model
35
     */
36
    protected $model;
37
    
38
    /**
39
     * The string name of the Transformer class
40
     * 
41
     * @var string
42
     */
43
    protected $transformerName;
44
    
45
    /**
46
     * The name of the collection that is returned in the JSON response
47
     * 
48
     * @var string
49
     */
50
    protected $collectionName;
51
    
52
    /**
53
     * The Fractal Manager
54
     * 
55
     * @var \League\Fractal\Manager
56
     */
57
    public $manager;
58
59
60
    /**
61
     * Constructor
62
     */
63
    public function __construct()
64
    {
65
        $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...
66
        
67
        if (!empty($this->modelName)) {
68
            $this->model = new $this->modelName;
69
        }
70
71
        // if no collection name provided, use the model's table name
72
        if (empty($this->collectionName)) {
73
            $this->collectionName = $this->model->getTable();
74
        }
75
        
76
        // parse includes
77
        if (\Input::get('include') != '') {
78
            $this->manager = new \League\Fractal\Manager;
79
            $this->manager->parseIncludes(explode(',', \Input::get('include')));
80
        }
81
82
        parent::__construct();
83
    }
84
85
    /**
86
     * Creates an item
87
     *
88
     * @param \Illuminate\Http\Request $data
89
     * @return \Illuminate\Http\JsonResponse
90
     */
91
    public function create(Request $data = null)
92
    {   
93
        $data = $data ?: \Input::json();
94
        $json = $data->all();
95
        $json = $this->addAttribution($json);
96
97
        try {
98
            $this->model->validate($json);
99
            $item = $this->model->create($json);
100
            return $this->showByObject($item);
101
        
102
        } catch (ValidationException $e) {
103
            return $this->response->setStatusCode(422)->withError($e->errors()->all(), 'GEN-UNPROCESSABLE-ENTITY');
0 ignored issues
show
Documentation introduced by
$e->errors()->all() is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
104
        } catch (MassAssignmentException $e) {
105
            return $this->response->setStatusCode(422)->withError("Cannot mass assign " . $e->getMessage(), 'GEN-UNPROCESSABLE-ENTITY');
106
        }  catch (\Exception $e) {
107
            return $this->response->setStatusCode(422)->withError($e->getMessage(), 'GEN-UNPROCESSABLE-ENTITY');
108
        }
109
    }
110
111
    /**
112
     * Adds created_by and updated_by to the array if the model supports it
113
     *
114
     * @param array $data
115
     * @return array $data
116
     */
117
    protected function addAttribution(array $data)
118
    {   
119
        if ($this->model->attirbution) {
120
            $data['created_by'] = $this->apiKey->user_id;
121
            $data['updated_by'] = $this->apiKey->user_id;
122
        }
123
124
        return $data;
125
    }
126
127
    /**
128
     * Returns a single item
129
     * 
130
     * @param  int $id
131
     * @return \Illuminate\Http\JsonResponse
132
     */
133
    public function show($id)
134
    {        
135
        try {
136
            
137
            return $this->response->withItem($this->model->findOrFail($id), new $this->transformerName);
138
        
139
        } catch (ModelNotFoundException $e) {
140
141
            return $this->respondNotFound();
142
        }
143
    }
144
145
    /**
146
     * Returns a single item
147
     * 
148
     * @param  object $object
149
     * @return \Illuminate\Http\JsonResponse
150
     */
151
    public function showByObject($object)
152
    {        
153
        try {
154
            return $this->response->withItem($object, new $this->transformerName);
155
        
156
        } catch (ModelNotFoundException $e) {
157
158
            return $this->respondNotFound();
159
        }
160
    }
161
162
    /**
163
     * Returns a paginated collection
164
     * 
165
     * @return \Illuminate\Http\JsonResponse
166
     */
167
    public function collection()
168
    {
169
        $limit = \Input::get('limit') ?: 10;
170
        $model = $this->model;
171
        
172
        if (\Request::has('order')) {
173
            list($orderCol, $orderBy) = explode('|', \Input::get('order'));
174
            $model = $model->orderBy($orderCol, $orderBy);
175
        }
176
177
        return $this->response->withPaginator($model->paginate($limit), new $this->transformerName, $this->collectionName);
178
    }
179
180
    /**
181
     * Handles 404 errors
182
     * 
183
     * @param  string $msg
184
     * @return \Illuminate\Http\JsonResponse
185
     */
186
    public function respondNotFound($msg = 'Not found!')
187
    {
188
        return \Response::json([
189
            'error' => [
190
                'message' => $msg,
191
                'status_code' => 404
192
            ]
193
        ], 404);
194
    }
195
}