Completed
Push — master ( ae09f0...319f04 )
by Arjay
01:11
created

src/DataTablesEditor.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Yajra\DataTables;
4
5
use Illuminate\Contracts\Validation\Validator;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Foundation\Validation\ValidatesRequests;
8
use Illuminate\Http\JsonResponse;
9
use Illuminate\Http\Request;
10
11
abstract class DataTablesEditor
12
{
13
    use ValidatesRequests;
14
15
    /**
16
     * Allowed dataTables editor actions.
17
     *
18
     * @var array
19
     */
20
    protected $actions = ['create', 'edit', 'remove'];
21
22
    /**
23
     * @var \Illuminate\Database\Eloquent\Model
24
     */
25
    protected $model = null;
26
27
    /**
28
     * Process dataTables editor action request.
29
     *
30
     * @param Request $request
31
     * @return JsonResponse|mixed
32
     * @throws DataTablesEditorException
33
     */
34
    public function process(Request $request)
35
    {
36
        $action = $request->get('action');
37
38
        if (! in_array($action, $this->actions)) {
39
            throw new DataTablesEditorException('Requested action not supported!');
40
        }
41
42
        return app()->call([$this, $action]);
43
    }
44
45
    /**
46
     * Process create action request.
47
     *
48
     * @param Request $request
49
     * @return JsonResponse
50
     */
51 View Code Duplication
    public function create(Request $request)
52
    {
53
        $model      = $this->resolveModel();
54
        $connection = $model->getConnection();
55
        $affected   = [];
56
        $errors     = [];
57
58
        $connection->beginTransaction();
59
        foreach ($request->get('data') as $datum) {
60
            $validator = $this->getValidationFactory()->make($datum, $this->getCreateRules());
61
            if ($validator->fails()) {
62
                foreach ($this->formatErrors($validator) as $error) {
63
                    $errors[] = $error;
64
                };
65
66
                continue;
67
            }
68
69
            $instance = $model->newQuery();
70
71
            if (method_exists($this, 'creating')) {
72
                app()->call([$this, 'creating'], ['model' => $instance]);
73
            }
74
75
            $instance = $instance->create($datum);
76
            $instance->setAttribute('DT_RowId', $instance->getKey());
77
78
            if (method_exists($this, 'created')) {
79
                app()->call([$this, 'created'], ['model' => $instance]);
80
            }
81
82
            $affected[] = $instance;
83
        }
84
85
        if (! $errors) {
86
            $connection->commit();
87
        } else {
88
            $connection->rollBack();
89
        }
90
91
        return $this->toJson($affected, $errors);
92
    }
93
94
    /**
95
     * Resolve model to used.
96
     *
97
     * @return Model
98
     */
99
    protected function resolveModel()
100
    {
101
        if ($this->model instanceof Model) {
102
            return $this->model;
103
        }
104
105
        return new $this->model;
106
    }
107
108
    /**
109
     * Get create action validation rules.
110
     *
111
     * @return array
112
     */
113
    abstract public function getCreateRules();
114
115
    /**
116
     * @param Validator $validator
117
     * @return array
118
     */
119
    protected function formatErrors(Validator $validator)
120
    {
121
        $errors = [];
122
123
        collect($validator->errors())->each(function ($error, $key) use (&$errors) {
124
            $errors[] = [
125
                'name'   => $key,
126
                'status' => $error[0],
127
            ];
128
        });
129
130
        return $errors;
131
    }
132
133
    /**
134
     * Display success data in dataTables editor format.
135
     *
136
     * @param array $data
137
     * @param array $errors
138
     * @return JsonResponse
139
     */
140
    protected function toJson(array $data, array $errors = [])
141
    {
142
        $response = ['data' => $data];
143
        if ($errors) {
144
            $response['fieldErrors'] = $errors;
145
        }
146
147
        return new JsonResponse($response, 200);
148
    }
149
150
    /**
151
     * Process edit action request.
152
     *
153
     * @param Request $request
154
     * @return JsonResponse
155
     */
156 View Code Duplication
    public function edit(Request $request)
0 ignored issues
show
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...
157
    {
158
        $model      = $this->resolveModel();
159
        $connection = $model->getConnection();
160
        $affected   = [];
161
        $errors     = [];
162
163
        $connection->beginTransaction();
164
        foreach ($request->get('data') as $key => $datum) {
165
            $instance  = $model->newQuery()->find($key);
166
            $validator = $this->getValidationFactory()->make($datum, $this->getEditRules($instance));
167
            if ($validator->fails()) {
168
                foreach ($this->formatErrors($validator) as $error) {
169
                    $errors[] = $error;
170
                };
171
172
                continue;
173
            }
174
175
            if (method_exists($this, 'updating')) {
176
                app()->call([$this, 'updating'], ['model' => $instance]);
177
            }
178
179
            $instance->update($datum);
180
181
            if (method_exists($this, 'updated')) {
182
                app()->call([$this, 'updated'], ['model' => $instance]);
183
            }
184
185
            $instance->setAttribute('DT_RowId', $instance->getKey());
186
            $affected[] = $instance;
187
        }
188
189
        if (! $errors) {
190
            $connection->commit();
191
        } else {
192
            $connection->rollBack();
193
        }
194
195
        return $this->toJson($affected, $errors);
196
    }
197
198
    /**
199
     * Get edit action validation rules.
200
     *
201
     * @param Model $model
202
     * @return array
203
     */
204
    abstract public function getEditRules(Model $model);
205
206
    /**
207
     * Process remove action request.
208
     *
209
     * @param Request $request
210
     * @return JsonResponse
211
     */
212 View Code Duplication
    public function remove(Request $request)
213
    {
214
        $model      = $this->resolveModel();
215
        $connection = $model->getConnection();
216
        $affected   = [];
217
        $errors     = [];
218
219
        $connection->beginTransaction();
220
        foreach ($request->get('data') as $key => $datum) {
221
            $instance  = $model->newQuery()->find($key);
222
            $validator = $this->getValidationFactory()->make($datum, $this->getRemoveRules($instance));
223
            if ($validator->fails()) {
224
                foreach ($this->formatErrors($validator) as $error) {
225
                    $errors[] = $error;
226
                };
227
228
                continue;
229
            }
230
231
            if (method_exists($this, 'deleting')) {
232
                app()->call([$this, 'deleting'], ['model' => $instance]);
233
            }
234
235
            $instance->delete();
236
237
            if (method_exists($this, 'deleted')) {
238
                app()->call([$this, 'deleted'], ['model' => $instance]);
239
            }
240
241
            $affected[] = $instance;
242
        }
243
244
        if (! $errors) {
245
            $connection->commit();
246
        } else {
247
            $connection->rollBack();
248
        }
249
250
        return $this->toJson($affected, $errors);
251
    }
252
253
    /**
254
     * Get remove action validation rules.
255
     *
256
     * @param Model $model
257
     * @return array
258
     */
259
    abstract public function getRemoveRules(Model $model);
260
261
    /**
262
     * Display dataTables editor validation errors.
263
     *
264
     * @param Validator $validator
265
     * @return JsonResponse
266
     */
267
    protected function displayValidationErrors(Validator $validator)
268
    {
269
        $errors = $this->formatErrors($validator);
270
271
        return new JsonResponse([
272
            'data'        => [],
273
            'fieldErrors' => $errors,
274
        ]);
275
    }
276
}
277