Completed
Push — api/develop ( 3871d2...0419b5 )
by Bertrand
05:55
created

CustomFieldsController::deleteOldOptions()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 8
ccs 0
cts 8
cp 0
rs 9.4285
cc 3
eloc 4
nc 3
nop 2
crap 12
1
<?php
2
3
/**
4
 * This file is part of the HRis Software package.
5
 *
6
 * HRis - Human Resource and Payroll System
7
 *
8
 * @link    http://github.com/HB-Co/HRis
9
 */
10
namespace HRis\Api\Controllers\PIM\Configuration;
11
12
use Exception;
13
use HRis\Api\Controllers\BaseController;
14
use HRis\Api\Eloquent\CustomField;
15
use HRis\Api\Eloquent\CustomFieldOption;
16
use HRis\Api\Eloquent\CustomFieldSection;
17
use HRis\Api\Eloquent\CustomFieldType;
18
use HRis\Api\Eloquent\Navlink;
19
use HRis\Api\Requests\PIM\CustomFieldRequest;
20
use HRis\Api\Requests\PIM\CustomFieldSectionsRequest;
21
use Illuminate\Http\Request;
22
use Illuminate\Support\Facades\DB;
23
24
/**
25
 * Class CustomFieldsController.
26
 */
27
class CustomFieldsController extends BaseController
28
{
29
    /**
30
     * @var CustomFieldSection
31
     */
32
    protected $custom_field_section;
33
34
    /**
35
     * @var CustomField
36
     */
37
    protected $custom_field;
38
39
    /**
40
     * @var CustomFieldType
41
     */
42
    protected $custom_field_type;
43
44
    /**
45
     * @param CustomFieldSection $custom_field_section
46
     * @param CustomField        $custom_field
47
     * @param CustomFieldType    $custom_field_type
48
     * @param CustomFieldOption  $custom_field_option
49
     *
50
     * @author Bertrand Kintanar <[email protected]>
51
     */
52
    public function __construct(CustomFieldSection $custom_field_section, CustomField $custom_field, CustomFieldType $custom_field_type, CustomFieldOption $custom_field_option)
53
    {
54
        $this->custom_field = $custom_field;
55
        $this->custom_field_section = $custom_field_section;
56
        $this->custom_field_type = $custom_field_type;
57
        $this->custom_field_option = $custom_field_option;
0 ignored issues
show
Bug introduced by
The property custom_field_option does not seem to exist. Did you mean custom_field?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
58
    }
59
60
    /**
61
     * Delete the PIM - Custom Field Section.
62
     *
63
     * @param CustomFieldSectionsRequest $request
64
     *
65
     * @return \Dingo\Api\Http\Response
66
     *
67
     * @author Bertrand Kintanar <[email protected]>
68
     */
69
    public function destroy(CustomFieldSectionsRequest $request)
70
    {
71
        return $this->destroyModel($request, $this->custom_field_section);
72
    }
73
74
    public function destroyCustomField(CustomFieldRequest $request)
75
    {
76
        return $this->destroyModel($request, $this->custom_field);
77
    }
78
79
    /**
80
     * Show the PIM - Custom Fields.
81
     *
82
     * @return \Dingo\Api\Http\Response
83
     *
84
     * @author Bertrand Kintanar <[email protected]>
85
     */
86
    public function index()
87
    {
88
        $custom_field_sections = $this->custom_field_section->with('screen')->paginate(ROWS_PER_PAGE);
89
90
        if (!$custom_field_sections) {
91
            return $this->responseAPI(404, UNABLE_RETRIEVE_MESSAGE);
92
        }
93
94
        return $this->responseAPI(200, SUCCESS_RETRIEVE_MESSAGE, ['data' => $custom_field_sections, 'table' => $this->setupDataTable($custom_field_sections)]);
95
    }
96
97
    /**
98
     * Setup table for custom field section.
99
     *
100
     * @param $custom_field_sections
101
     *
102
     * @return array
103
     *
104
     * @author Bertrand Kintanar <[email protected]>
105
     */
106
    public function setupDataTable($custom_field_sections)
107
    {
108
        $table = [];
109
110
        $table['title'] = 'Custom Field Sections';
111
        $table['permission'] = 'pim.configuration.custom-field-sections';
112
        $table['headers'] = ['Id', 'Name', 'Screen'];
113
        $table['model'] = [
114
            'singular' => 'custom_field_section',
115
            'plural'   => 'custom_field_sections',
116
            'dashed'   => 'custom-field-sections',
117
        ];
118
        $table['items'] = $custom_field_sections;
119
120
        return $table;
121
    }
122
123
    /**
124
     * Show a PIM - Custom Field Section.
125
     *
126
     * @param Request $request
127
     *
128
     * @return \Dingo\Api\Http\Response
129
     *
130
     * @author Bertrand Kintanar <[email protected]>
131
     */
132
    public function show(Request $request)
133
    {
134
        $custom_field_section_id = $request->get('custom_field_section_id');
135
        $custom_field_section = $this->custom_field_section->whereId($custom_field_section_id)->first();
0 ignored issues
show
Documentation Bug introduced by
The method whereId does not exist on object<HRis\Api\Eloquent\CustomFieldSection>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
136
137
        if (!$custom_field_section) {
138
            return $this->responseAPI(404, UNABLE_RETRIEVE_MESSAGE);
139
        }
140
141
        $custom_fields = $this->custom_field->with('type', 'options')->whereCustomFieldSectionId($custom_field_section_id)->paginate(ROWS_PER_PAGE);
142
143
        return $this->responseAPI(200, SUCCESS_RETRIEVE_MESSAGE, ['data' => $custom_fields, 'table' => $this->setupDataTable($custom_fields)]);
144
    }
145
146
    /**
147
     * Setup table for custom field.
148
     *
149
     * @param $custom_fields
150
     *
151
     * @return array
152
     *
153
     * @author Bertrand Kintanar <[email protected]>
154
     */
155
    public function setupDataTableCustomField($custom_fields)
156
    {
157
        $table = [];
158
159
        $table['title'] = 'Custom Fields';
160
        $table['permission'] = 'pim.configuration.custom-fields';
161
        $table['headers'] = ['Id', 'Name', 'Type', 'Mask', 'Has Options', 'Required'];
162
        $table['model'] = [
163
            'singular' => 'custom_field',
164
            'plural'   => 'custom_fields',
165
            'dashed'   => 'custom-fields',
166
        ];
167
        $table['items'] = $custom_fields;
168
169
        return $table;
170
    }
171
172
    /**
173
     * Save the PIM - Custom Field Section.
174
     *
175
     * @param CustomFieldSectionsRequest $request
176
     *
177
     * @return \Dingo\Api\Http\Response
178
     *
179
     * @author Bertrand Kintanar <[email protected]>
180
     */
181
    public function store(CustomFieldSectionsRequest $request)
182
    {
183
        return $this->storeModel($request, $this->custom_field_section, 'custom_field_section');
184
    }
185
186
    /**
187
     * Save the PIM - Custom Field.
188
     *
189
     * @param CustomFieldRequest $request
190
     *
191
     * @return \Dingo\Api\Http\Response
192
     *
193
     * @author Bertrand Kintanar <[email protected]>
194
     */
195
    public function storeCustomField(CustomFieldRequest $request)
196
    {
197
        $custom_field_section_id = $request->get('custom_field_section_id');
198
        try {
199
            DB::beginTransaction();
200
201
            $custom_field_section = $this->custom_field_section->whereId($custom_field_section_id)->first();
0 ignored issues
show
Documentation Bug introduced by
The method whereId does not exist on object<HRis\Api\Eloquent\CustomFieldSection>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
202
203
            $data = [
204
                'custom_field_type_id' => $request->get('type_id'),
205
                'name'                 => $request->get('name'),
206
                'required'             => $request->get('required'),
207
                'mask'                 => $request->has('mask') ? $request->get('mask') : null,
208
            ];
209
210
            // Create CustomField and attach it to the CustomFieldSection
211
            $custom_field = $custom_field_section->customFields()->create($data);
212
213
            $custom_field_type = $this->custom_field_type->whereId($data['custom_field_type_id'])->first();
0 ignored issues
show
Documentation Bug introduced by
The method whereId does not exist on object<HRis\Api\Eloquent\CustomFieldType>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
214
215
            // Checks if the CustomFieldType has options
216
            if ($custom_field_type->has_options) {
217
                $options = explode(',', $request->get('custom_field_options'));
218
219
                foreach ($options as $option) {
220
                    $custom_field->options()->create(['name' => $option]);
221
                }
222
            }
223
        } catch (Exception $e) {
224
            DB::rollback();
225
226
            return $this->responseAPI(422, UNABLE_ADD_MESSAGE);
227
        }
228
229
        DB::commit();
230
231
        $custom_field = $this->custom_field->with('type', 'options')->whereId($custom_field->id)->first();
232
233
        return $this->responseAPI(201, SUCCESS_ADD_MESSAGE, compact('custom_field'));
234
    }
235
236
    /**
237
     * Update the PIM - Custom Field Section.
238
     *
239
     * @param CustomFieldSectionsRequest $request
240
     *
241
     * @return \Dingo\Api\Http\Response
242
     *
243
     * @author Bertrand Kintanar <[email protected]>
244
     */
245
    public function update(CustomFieldSectionsRequest $request)
246
    {
247
        try {
248
            DB::beginTransaction();
249
250
            $custom_field_section = CustomFieldSection::whereId($request->get('custom_field_section_id'))->first();
251
252
            $custom_field_section->update($request->only(['name', 'screen_id']));
253
        } catch (Exception $e) {
254
            DB::rollback();
255
256
            return $this->responseAPI(422, UNABLE_UPDATE_MESSAGE);
257
        }
258
259
        DB::commit();
260
261
        return $this->responseAPI(200, SUCCESS_UPDATE_MESSAGE);
262
    }
263
264
    /**
265
     * Update the PIM - Custom Field.
266
     *
267
     * @param CustomFieldRequest $request
268
     *
269
     * @return \Dingo\Api\Http\Response
270
     *
271
     * @author Bertrand Kintanar <[email protected]>
272
     */
273
    public function updateCustomField(CustomFieldRequest $request)
274
    {
275
        try {
276
            DB::beginTransaction();
277
278
            $custom_field = $this->custom_field->whereId($request->get('custom_field_id'))->first();
0 ignored issues
show
Documentation Bug introduced by
The method whereId does not exist on object<HRis\Api\Eloquent\CustomField>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
279
280
            $data = [
281
                'custom_field_type_id' => $request->get('type_id'),
282
                'name'                 => $request->get('name'),
283
                'required'             => $request->get('required'),
284
                'mask'                 => $request->has('mask') ? $request->get('mask') : null,
285
            ];
286
287
            $custom_field->update($data);
288
289
            $custom_field_type = $this->custom_field_type->whereId($data['custom_field_type_id'])->first();
0 ignored issues
show
Documentation Bug introduced by
The method whereId does not exist on object<HRis\Api\Eloquent\CustomFieldType>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
290
291
            // Checks if the CustomFieldType has options.
292
            if ($custom_field_type->has_options) {
293
                $old_options = $this->custom_field_option->whereCustomFieldId($custom_field->id)->get();
0 ignored issues
show
Bug introduced by
The property custom_field_option does not seem to exist. Did you mean custom_field?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
294
                $options = explode(',', $request->get('custom_field_options'));
295
296
                // Delete database entry that aren't in the new option list.
297
                $this->deleteOldOptions($options, $old_options);
298
299
                // Assign / Create database entry basing on the new option list.
300
                $this->createNewOptions($options, $custom_field);
301
            }
302
        } catch (Exception $e) {
303
            DB::rollback();
304
305
            return $this->responseAPI(422, UNABLE_UPDATE_MESSAGE);
306
        }
307
308
        DB::commit();
309
310
        return $this->responseAPI(200, SUCCESS_UPDATE_MESSAGE);
311
    }
312
313
    /**
314
     * Get Custom Field Sections by Screen Id.
315
     *
316
     * @param Request $request
317
     * @return \Dingo\Api\Http\Response
318
     *
319
     * @author Bertrand Kintanar <[email protected]>
320
     */
321
    public function getCustomFieldSectionsByScreenId(Request $request)
322
    {
323
        $screen_id = Navlink::whereName($request->get('screen_name'))->pluck('id');
324
325
        $custom_field_sections = $this->custom_field_section->with('customFields.options')->whereScreenId($screen_id)->get();
326
327
        $custom_field_sections->each(function ($custom_field_section) {
328
            $custom_fields = $custom_field_section->customFields;
329
330
            $custom_field_section->fields = array_chunk($custom_fields->toArray(), 2);
331
        });
332
333
        return $this->responseAPI(200, SUCCESS_RETRIEVE_MESSAGE, compact('custom_field_sections'));
334
    }
335
336
    /**
337
     * Delete database entry that aren't in the new option list.
338
     *
339
     * @param $options
340
     * @param $old_options
341
     *
342
     * @author Bertrand Kintanar <[email protected]>
343
     */
344
    private function deleteOldOptions($options, $old_options)
345
    {
346
        foreach ($old_options as $option) {
347
            if (!in_array($option->name, $options)) {
348
                $option->delete();
349
            }
350
        }
351
    }
352
353
    /**
354
     * Create database entry basing on the new option list.
355
     *
356
     * @param $options
357
     * @param $custom_field
358
     *
359
     * @author Bertrand Kintanar <[email protected]>
360
     */
361
    private function createNewOptions($options, $custom_field)
362
    {
363
        foreach ($options as $option) {
364
            $custom_field_option = $this->custom_field_option->whereCustomFieldId($custom_field->id)->whereName($option)->count();
0 ignored issues
show
Bug introduced by
The property custom_field_option does not seem to exist. Did you mean custom_field?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
365
366
            // Only add to database those options that aren't there yet.
367
            if (!$custom_field_option) {
368
                $custom_field->options()->create(['name' => $option]);
369
            }
370
        }
371
    }
372
}
373