Completed
Push — master ( 5ddd97...6a45b5 )
by Arjay
9s
created

DataTablesEditor::attributes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Yajra\DataTables;
4
5
use Illuminate\Contracts\Validation\Validator;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Database\QueryException;
8
use Illuminate\Foundation\Validation\ValidatesRequests;
9
use Illuminate\Http\JsonResponse;
10
use Illuminate\Http\Request;
11
12
abstract class DataTablesEditor
13
{
14
    use ValidatesRequests;
15
16
    /**
17
     * Allowed dataTables editor actions.
18
     *
19
     * @var array
20
     */
21
    protected $actions = ['create', 'edit', 'remove'];
22
23
    /**
24
     * @var \Illuminate\Database\Eloquent\Model
25
     */
26
    protected $model = null;
27
28
    /**
29
     * Process dataTables editor action request.
30
     *
31
     * @param Request $request
32
     * @return JsonResponse|mixed
33
     * @throws DataTablesEditorException
34
     */
35
    public function process(Request $request)
36
    {
37
        $action = $request->get('action');
38
39
        if (! in_array($action, $this->actions)) {
40
            throw new DataTablesEditorException('Requested action not supported!');
41
        }
42
43
        return $this->{$action}($request);
44
    }
45
46
    /**
47
     * Process create action request.
48
     *
49
     * @param Request $request
50
     * @return JsonResponse
51
     */
52
    public function create(Request $request)
53
    {
54
        $instance   = $this->resolveModel();
55
        $connection = $instance->getConnection();
56
        $affected   = [];
57
        $errors     = [];
58
59
        $connection->beginTransaction();
60
        foreach ($request->get('data') as $data) {
61
            $validator = $this->getValidationFactory()->make($data, $this->createRules(), $this->createMessages(), $this->attributes());
62
            if ($validator->fails()) {
63
                foreach ($this->formatErrors($validator) as $error) {
64
                    $errors[] = $error;
65
                };
66
67
                continue;
68
            }
69
70
            if (method_exists($this, 'creating')) {
71
                $data = $this->creating($instance, $data);
0 ignored issues
show
Bug introduced by
The method creating() does not seem to exist on object<Yajra\DataTables\DataTablesEditor>.

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...
72
            }
73
74
            $model = $instance->newQuery()->create($data);
75
            $model->setAttribute('DT_RowId', $model->getKey());
76
77
            if (method_exists($this, 'created')) {
78
                $this->created($model, $data);
0 ignored issues
show
Bug introduced by
The method created() does not exist on Yajra\DataTables\DataTablesEditor. Did you maybe mean create()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
79
            }
80
81
            $affected[] = $model;
82
        }
83
84
        if (! $errors) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errors of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
85
            $connection->commit();
86
        } else {
87
            $connection->rollBack();
88
        }
89
90
        return $this->toJson($affected, $errors);
91
    }
92
93
    /**
94
     * Resolve model to used.
95
     *
96
     * @return Model
97
     */
98
    protected function resolveModel()
99
    {
100
        if ($this->model instanceof Model) {
101
            return $this->model;
102
        }
103
104
        return new $this->model;
105
    }
106
107
    /**
108
     * Get create action validation rules.
109
     *
110
     * @return array
111
     */
112
    abstract public function createRules();
113
114
    /**
115
     * Get create validation messages.
116
     *
117
     * @return array
118
     */
119
    protected function createMessages()
120
    {
121
        return [];
122
    }
123
124
    /**
125
     * @param Validator $validator
126
     * @return array
127
     */
128
    protected function formatErrors(Validator $validator)
129
    {
130
        $errors = [];
131
132
        collect($validator->errors())->each(function ($error, $key) use (&$errors) {
133
            $errors[] = [
134
                'name'   => $key,
135
                'status' => $error[0],
136
            ];
137
        });
138
139
        return $errors;
140
    }
141
142
    /**
143
     * Display success data in dataTables editor format.
144
     *
145
     * @param array $data
146
     * @param array $errors
147
     * @return JsonResponse
148
     */
149
    protected function toJson(array $data, array $errors = [])
150
    {
151
        $response = ['data' => $data];
152
        if ($errors) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errors of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
153
            $response['fieldErrors'] = $errors;
154
        }
155
156
        return new JsonResponse($response, 200);
157
    }
158
159
    /**
160
     * Process edit action request.
161
     *
162
     * @param Request $request
163
     * @return JsonResponse
164
     */
165
    public function edit(Request $request)
166
    {
167
        $instance   = $this->resolveModel();
168
        $connection = $instance->getConnection();
169
        $affected   = [];
170
        $errors     = [];
171
172
        $connection->beginTransaction();
173
        foreach ($request->get('data') as $key => $data) {
174
            $model     = $instance->newQuery()->find($key);
175
            $validator = $this->getValidationFactory()->make($data, $this->editRules($model), $this->editMessages(), $this->attributes());
0 ignored issues
show
Documentation introduced by
$model is of type object|null, but the function expects a object<Illuminate\Database\Eloquent\Model>.

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...
176
            if ($validator->fails()) {
177
                foreach ($this->formatErrors($validator) as $error) {
178
                    $errors[] = $error;
179
                };
180
181
                continue;
182
            }
183
184
            if (method_exists($this, 'updating')) {
185
                $data = $this->updating($model, $data);
0 ignored issues
show
Bug introduced by
The method updating() does not seem to exist on object<Yajra\DataTables\DataTablesEditor>.

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...
186
            }
187
188
            $model->update($data);
189
190
            if (method_exists($this, 'updated')) {
191
                $this->updated($model, $data);
0 ignored issues
show
Bug introduced by
The method updated() does not seem to exist on object<Yajra\DataTables\DataTablesEditor>.

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...
192
            }
193
194
            $model->setAttribute('DT_RowId', $model->getKey());
195
            $affected[] = $model;
196
        }
197
198
        if (! $errors) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errors of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
199
            $connection->commit();
200
        } else {
201
            $connection->rollBack();
202
        }
203
204
        return $this->toJson($affected, $errors);
205
    }
206
207
    /**
208
     * Get edit action validation rules.
209
     *
210
     * @param Model $model
211
     * @return array
212
     */
213
    abstract public function editRules(Model $model);
214
215
    /**
216
     * Get edit validation messages.
217
     *
218
     * @return array
219
     */
220
    protected function editMessages()
221
    {
222
        return [];
223
    }
224
225
    /**
226
     * Process remove action request.
227
     *
228
     * @param Request $request
229
     * @return JsonResponse
230
     */
231
    public function remove(Request $request)
232
    {
233
        $instance   = $this->resolveModel();
234
        $connection = $instance->getConnection();
235
        $affected   = [];
236
        $errors     = [];
237
238
        $connection->beginTransaction();
239
        foreach ($request->get('data') as $key => $data) {
240
            $model     = $instance->newQuery()->find($key);
241
            $validator = $this->getValidationFactory()
242
                              ->make($data, $this->removeRules($model), $this->removeMessages(), $this->attributes());
0 ignored issues
show
Documentation introduced by
$model is of type object|null, but the function expects a object<Illuminate\Database\Eloquent\Model>.

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...
243
            if ($validator->fails()) {
244
                foreach ($this->formatErrors($validator) as $error) {
245
                    $errors[] = $error['status'];
246
                };
247
248
                continue;
249
            }
250
251
            try {
252
                if (method_exists($this, 'deleting')) {
253
                    $this->deleting($model, $data);
0 ignored issues
show
Bug introduced by
The method deleting() does not seem to exist on object<Yajra\DataTables\DataTablesEditor>.

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...
254
                }
255
256
                $model->delete();
257
258
                if (method_exists($this, 'deleted')) {
259
                    $this->deleted($model, $data);
0 ignored issues
show
Bug introduced by
The method deleted() does not seem to exist on object<Yajra\DataTables\DataTablesEditor>.

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...
260
                }
261
            } catch (QueryException $exception) {
262
                $error    = config('app.debug') ? $exception->errorInfo[2] : $this->removeExceptionMessage($exception, $model);
0 ignored issues
show
Documentation introduced by
$model is of type object|null, but the function expects a object<Illuminate\Database\Eloquent\Model>.

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...
263
                $errors[] = $error;
264
            }
265
266
            $affected[] = $model;
267
        }
268
269
        if (! $errors) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errors of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
270
            $connection->commit();
271
        } else {
272
            $connection->rollBack();
273
        }
274
275
        $response = ['data' => $affected];
276
        if ($errors) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errors of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
277
            $response['error'] = implode("\n", $errors);
278
        }
279
280
        return new JsonResponse($response, 200);
281
    }
282
283
    /**
284
     * Get remove action validation rules.
285
     *
286
     * @param Model $model
287
     * @return array
288
     */
289
    abstract public function removeRules(Model $model);
290
291
    /**
292
     * Get remove validation messages.
293
     *
294
     * @return array
295
     */
296
    protected function removeMessages()
297
    {
298
        return [];
299
    }
300
301
    /**
302
     * Get remove query exception message.
303
     *
304
     * @param QueryException $exception
305
     * @param Model          $model
306
     * @return string
307
     */
308
    protected function removeExceptionMessage(QueryException $exception, Model $model)
0 ignored issues
show
Unused Code introduced by
The parameter $exception is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
309
    {
310
        return "Record {$model->getKey()} is protected and cannot be deleted!";
311
    }
312
313
    /**
314
     * Display dataTables editor validation errors.
315
     *
316
     * @param Validator $validator
317
     * @return JsonResponse
318
     */
319
    protected function displayValidationErrors(Validator $validator)
320
    {
321
        $errors = $this->formatErrors($validator);
322
323
        return new JsonResponse([
324
            'data'        => [],
325
            'fieldErrors' => $errors,
326
        ]);
327
    }
328
329
    /**
330
	 * Get custom attributes for validator errors.
331
	 *
332
	 * @return array
333
	 */
334
	public function attributes()
335
	{
336
		return [];
337
	}
338
}
339