Completed
Push — master ( c7cd36...6536dd )
by Arjay
01:17
created

DataTablesEditor::removeExceptionMessage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
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());
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
     * @param Validator $validator
116
     * @return array
117
     */
118
    protected function formatErrors(Validator $validator)
119
    {
120
        $errors = [];
121
122
        collect($validator->errors())->each(function ($error, $key) use (&$errors) {
123
            $errors[] = [
124
                'name'   => $key,
125
                'status' => $error[0],
126
            ];
127
        });
128
129
        return $errors;
130
    }
131
132
    /**
133
     * Display success data in dataTables editor format.
134
     *
135
     * @param array $data
136
     * @param array $errors
137
     * @return JsonResponse
138
     */
139
    protected function toJson(array $data, array $errors = [])
140
    {
141
        $response = ['data' => $data];
142
        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...
143
            $response['fieldErrors'] = $errors;
144
        }
145
146
        return new JsonResponse($response, 200);
147
    }
148
149
    /**
150
     * Process edit action request.
151
     *
152
     * @param Request $request
153
     * @return JsonResponse
154
     */
155
    public function edit(Request $request)
156
    {
157
        $instance   = $this->resolveModel();
158
        $connection = $instance->getConnection();
159
        $affected   = [];
160
        $errors     = [];
161
162
        $connection->beginTransaction();
163
        foreach ($request->get('data') as $key => $data) {
164
            $model     = $instance->newQuery()->find($key);
165
            $validator = $this->getValidationFactory()->make($data, $this->editRules($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...
166
            if ($validator->fails()) {
167
                foreach ($this->formatErrors($validator) as $error) {
168
                    $errors[] = $error;
169
                };
170
171
                continue;
172
            }
173
174
            if (method_exists($this, 'updating')) {
175
                $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...
176
            }
177
178
            $model->update($data);
179
180
            if (method_exists($this, 'updated')) {
181
                $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...
182
            }
183
184
            $model->setAttribute('DT_RowId', $model->getKey());
185
            $affected[] = $model;
186
        }
187
188
        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...
189
            $connection->commit();
190
        } else {
191
            $connection->rollBack();
192
        }
193
194
        return $this->toJson($affected, $errors);
195
    }
196
197
    /**
198
     * Get edit action validation rules.
199
     *
200
     * @param Model $model
201
     * @return array
202
     */
203
    abstract public function editRules(Model $model);
204
205
    /**
206
     * Process remove action request.
207
     *
208
     * @param Request $request
209
     * @return JsonResponse
210
     */
211
    public function remove(Request $request)
212
    {
213
        $instance   = $this->resolveModel();
214
        $connection = $instance->getConnection();
215
        $affected   = [];
216
        $errors     = [];
217
218
        $connection->beginTransaction();
219
        foreach ($request->get('data') as $key => $data) {
220
            $model     = $instance->newQuery()->find($key);
221
            $validator = $this->getValidationFactory()->make($data, $this->removeRules($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...
222
            if ($validator->fails()) {
223
                foreach ($this->formatErrors($validator) as $error) {
224
                    $errors[] = $error;
225
                };
226
227
                continue;
228
            }
229
230
            try {
231
                if (method_exists($this, 'deleting')) {
232
                    $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...
233
                }
234
235
                $model->delete();
236
237
                if (method_exists($this, 'deleted')) {
238
                    $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...
239
                }
240
            } catch (QueryException $exception) {
241
                $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...
242
                $errors[] = $error;
243
            }
244
245
            $affected[] = $model;
246
        }
247
248
        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...
249
            $connection->commit();
250
        } else {
251
            $connection->rollBack();
252
        }
253
254
        $response = ['data' => $affected];
255
        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...
256
            $response['error'] = implode("\n", $errors);
257
        }
258
259
        return new JsonResponse($response, 200);
260
    }
261
262
    /**
263
     * Get remove action validation rules.
264
     *
265
     * @param Model $model
266
     * @return array
267
     */
268
    abstract public function removeRules(Model $model);
269
270
    /**
271
     * Get remove query exception message.
272
     *
273
     * @param QueryException $exception
274
     * @param Model          $model
275
     * @return string
276
     */
277
    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...
278
    {
279
        return "Record {$model->getKey()} is protected and cannot be deleted!";
280
    }
281
282
    /**
283
     * Display dataTables editor validation errors.
284
     *
285
     * @param Validator $validator
286
     * @return JsonResponse
287
     */
288
    protected function displayValidationErrors(Validator $validator)
289
    {
290
        $errors = $this->formatErrors($validator);
291
292
        return new JsonResponse([
293
            'data'        => [],
294
            'fieldErrors' => $errors,
295
        ]);
296
    }
297
}
298