Passed
Push — master ( a68dc2...b54473 )
by Thomas
03:07
created

TabulatorGrid_ItemRequest::ajaxMove()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 28
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
eloc 19
c 2
b 1
f 1
dl 0
loc 28
rs 9.3222
cc 5
nc 6
nop 1
1
<?php
2
3
namespace LeKoala\Tabulator;
4
5
use Exception;
6
use SilverStripe\ORM\DB;
7
use SilverStripe\Forms\Form;
8
use SilverStripe\ORM\ArrayList;
9
use SilverStripe\View\SSViewer;
10
use SilverStripe\Control\Cookie;
11
use SilverStripe\ORM\DataObject;
12
use SilverStripe\View\ArrayData;
13
use SilverStripe\ORM\HasManyList;
14
use SilverStripe\Control\Director;
15
use SilverStripe\ORM\ManyManyList;
16
use SilverStripe\ORM\RelationList;
17
use SilverStripe\Control\Controller;
18
use SilverStripe\Control\HTTPRequest;
19
use SilverStripe\Control\HTTPResponse;
20
use SilverStripe\ORM\ValidationResult;
21
use SilverStripe\Control\RequestHandler;
22
use SilverStripe\Security\SecurityToken;
23
use SilverStripe\ORM\ValidationException;
24
use SilverStripe\Forms\GridField\GridFieldDetailForm_ItemRequest;
25
26
/**
27
 * Endpoint for actions related to a specific record
28
 *
29
 * It also allows to display a form to edit this record
30
 */
31
class TabulatorGrid_ItemRequest extends RequestHandler
32
{
33
34
    private static $allowed_actions = [
35
        'edit',
36
        'ajaxEdit',
37
        'ajaxMove',
38
        'view',
39
        'customAction',
40
        'ItemEditForm',
41
    ];
42
43
    protected TabulatorGrid $tabulatorGrid;
44
45
    /**
46
     * @var DataObject
47
     */
48
    protected $record;
49
50
    /**
51
     * @var array
52
     */
53
    protected $manipulatedData = null;
54
55
    /**
56
     * This represents the current parent RequestHandler (which does not necessarily need to be a Controller).
57
     * It allows us to traverse the RequestHandler chain upwards to reach the Controller stack.
58
     *
59
     * @var RequestHandler
60
     */
61
    protected $popupController;
62
63
    protected string $hash = '';
64
65
    protected string $template = '';
66
67
    private static $url_handlers = [
68
        'customAction/$CustomAction' => 'customAction',
69
        '$Action!' => '$Action',
70
        '' => 'edit',
71
    ];
72
73
    /**
74
     *
75
     * @param TabulatorGrid $tabulatorGrid
76
     * @param DataObject $record
77
     * @param RequestHandler $requestHandler
78
     */
79
    public function __construct($tabulatorGrid, $record, $requestHandler)
80
    {
81
        $this->tabulatorGrid = $tabulatorGrid;
82
        $this->record = $record;
83
        $this->popupController = $requestHandler;
84
        parent::__construct();
85
    }
86
87
    public function Link($action = null)
88
    {
89
        return Controller::join_links(
90
            $this->tabulatorGrid->Link('item'),
91
            $this->record->ID ? $this->record->ID : 'new',
92
            $action
93
        );
94
    }
95
96
    public function AbsoluteLink($action = null)
97
    {
98
        return Director::absoluteURL($this->Link($action));
99
    }
100
101
    protected function getManipulatedData(): array
102
    {
103
        if ($this->manipulatedData) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->manipulatedData 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...
104
            return $this->manipulatedData;
105
        }
106
        $grid = $this->getTabulatorGrid();
107
108
        $state = $grid->getState($this->popupController->getRequest());
109
110
        $currentPage = $state['page'];
111
        $itemsPerPage = $state['limit'];
112
113
        $limit = $itemsPerPage + 2;
114
        $offset = max(0, $itemsPerPage * ($currentPage - 1) - 1);
115
116
        $list = $grid->getManipulatedData($limit, $offset, $state['sort'], $state['filter']);
117
118
        $this->manipulatedData = $list;
119
        return $list;
120
    }
121
122
    public function index(HTTPRequest $request)
123
    {
124
        $controller = $this->getToplevelController();
125
        return $controller->redirect($this->Link('edit'));
126
    }
127
128
    protected function returnWithinContext(HTTPRequest $request, RequestHandler $controller, Form $form)
129
    {
130
        $data = $this->customise([
131
            'Backlink' => $controller->hasMethod('Backlink') ? $controller->Backlink() : $controller->Link(),
132
            'ItemEditForm' => $form,
133
        ]);
134
135
        $return = $data->renderWith('LeKoala\\Tabulator\\TabulatorGrid_ItemEditForm');
136
        if ($request->isAjax()) {
137
            return $return;
138
        }
139
        // If not requested by ajax, we need to render it within the controller context+template
140
        return $controller->customise([
141
            'Content' => $return,
142
        ]);
143
    }
144
145
    protected function editFailure(): HTTPResponse
146
    {
147
        return $this->httpError(403, _t(
148
            __CLASS__ . '.EditPermissionsFailure',
149
            'It seems you don\'t have the necessary permissions to edit "{ObjectTitle}"',
150
            ['ObjectTitle' => $this->record->singular_name()]
151
        ));
152
    }
153
154
    /**
155
     * This is responsible to display an edit form, like GridFieldDetailForm, but much simpler
156
     *
157
     * @return mixed
158
     */
159
    public function edit(HTTPRequest $request)
160
    {
161
        if (!$this->record->canEdit()) {
162
            return $this->editFailure();
163
        }
164
        $controller = $this->getToplevelController();
165
166
        $form = $this->ItemEditForm();
167
168
        return $this->returnWithinContext($request, $controller, $form);
0 ignored issues
show
Bug introduced by
$form of type SilverStripe\Control\HTTPResponse is incompatible with the type SilverStripe\Forms\Form expected by parameter $form of LeKoala\Tabulator\Tabula...::returnWithinContext(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

168
        return $this->returnWithinContext($request, $controller, /** @scrutinizer ignore-type */ $form);
Loading history...
169
    }
170
171
    public function ajaxEdit(HTTPRequest $request)
172
    {
173
        $SecurityID = $request->postVar('SecurityID');
174
        if (!SecurityToken::inst()->check($SecurityID)) {
175
            return $this->httpError(404, "Invalid SecurityID");
176
        }
177
        if (!$this->record->canEdit()) {
178
            return $this->editFailure();
179
        }
180
181
        $preventEmpty = [];
182
        if ($this->record->hasMethod('tabulatorPreventEmpty')) {
183
            $preventEmpty = $this->record->tabulatorPreventEmpty();
184
        }
185
186
        $Data = $request->postVar("Data");
0 ignored issues
show
Unused Code introduced by
The assignment to $Data is dead and can be removed.
Loading history...
187
        $Column = $request->postVar("Column");
188
        $Value = $request->postVar("Value");
189
190
        if (!$Value && in_array($Column, $preventEmpty)) {
191
            return $this->httpError(400, _t(__CLASS__ . '.ValueCannotBeEmpty', 'Value cannot be empty'));
192
        }
193
194
        try {
195
            $updatedValue = $this->executeEdit($Column, $Value);
0 ignored issues
show
Bug introduced by
It seems like $Column can also be of type null; however, parameter $Column of LeKoala\Tabulator\Tabula...mRequest::executeEdit() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

195
            $updatedValue = $this->executeEdit(/** @scrutinizer ignore-type */ $Column, $Value);
Loading history...
196
        } catch (Exception $e) {
197
            return $this->httpError(400, $e->getMessage());
198
        }
199
200
        $response = new HTTPResponse(json_encode([
201
            'success' => true,
202
            'message' => _t(__CLASS__ . '.RecordEdited', 'Record edited'),
203
            'value' => $updatedValue,
204
        ]));
205
        $response->addHeader('Content-Type', 'application/json');
206
        return $response;
207
    }
208
209
    public function executeEdit(string $Column, $Value)
210
    {
211
        $field = $Column;
212
        $rel = $relField = null;
213
        if (strpos($Column, ".") !== false) {
214
            $parts = explode(".", $Column);
215
            $rel = $parts[0];
216
            $relField = $parts[1];
217
            $field = $rel . "ID";
218
            if (!is_numeric($Value)) {
219
                return $this->httpError(400, "ID must have a numerical value");
220
            }
221
        }
222
        if (!$field) {
223
            return $this->httpError(400, "Field must not be empty");
224
        }
225
226
        $this->record->$field = $Value;
227
        $this->record->write();
228
        $updatedValue = $this->record->$field;
229
        if ($rel) {
230
            /** @var DataObject $relObject */
231
            $relObject = $this->record->$rel();
232
            $updatedValue = $relObject->relField($relField);
233
        }
234
        return $updatedValue;
235
    }
236
237
    public function ajaxMove(HTTPRequest $request)
238
    {
239
        $SecurityID = $request->postVar('SecurityID');
240
        if (!SecurityToken::inst()->check($SecurityID)) {
241
            return $this->httpError(404, "Invalid SecurityID");
242
        }
243
        if (!$this->record->canEdit()) {
244
            return $this->editFailure();
245
        }
246
        $Data = $request->postVar("Data");
247
        if (is_string($Data)) {
248
            $Data = json_decode($Data, JSON_OBJECT_AS_ARRAY);
0 ignored issues
show
Bug introduced by
LeKoala\Tabulator\JSON_OBJECT_AS_ARRAY of type integer is incompatible with the type boolean|null expected by parameter $associative of json_decode(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

248
            $Data = json_decode($Data, /** @scrutinizer ignore-type */ JSON_OBJECT_AS_ARRAY);
Loading history...
249
        }
250
        $Sort = $request->postVar("Sort");
251
252
        try {
253
            $updatedSort = $this->executeSort($Data, $Sort);
0 ignored issues
show
Bug introduced by
It seems like $Sort can also be of type null; however, parameter $Sort of LeKoala\Tabulator\Tabula...mRequest::executeSort() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

253
            $updatedSort = $this->executeSort($Data, /** @scrutinizer ignore-type */ $Sort);
Loading history...
254
        } catch (Exception $e) {
255
            return $this->httpError(400, $e->getMessage());
256
        }
257
258
        $response = new HTTPResponse(json_encode([
259
            'success' => true,
260
            'message' => _t(__CLASS__ . '.RecordMove', 'Record moved'),
261
            'value' => $updatedSort,
262
        ]));
263
        $response->addHeader('Content-Type', 'application/json');
264
        return $response;
265
    }
266
267
    public function executeSort(array $Data, int $Sort, string $sortField = 'Sort'): int
268
    {
269
        $table = DataObject::getSchema()->baseDataTable(get_class($this->record));
270
271
        if (!isset($Data[$sortField])) {
272
            return $this->httpError(403, _t(
273
                __CLASS__ . '.UnableToResolveSort',
274
                'Unable to resolve previous sort order'
275
            ));
276
        }
277
278
        $prevSort = $Data[$sortField];
279
280
        // Just make sure you don't have 0 (except first record) or equal sorts
281
        if ($prevSort < $Sort) {
282
            $set = "$sortField = $sortField - 1";
283
            $where = "$sortField > $prevSort and $sortField <= $Sort";
284
        } else {
285
            $set = "$sortField = $sortField + 1";
286
            $where = "$sortField < $prevSort and $sortField >= $Sort";
287
        }
288
        DB::query("UPDATE `$table` SET $set WHERE $where");
289
        $this->record->$sortField = $Sort;
290
        $this->record->write();
291
292
        return $this->record->Sort;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->record->Sort could return the type null which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
293
    }
294
295
    /**
296
     * @return mixed
297
     */
298
    public function view(HTTPRequest $request)
299
    {
300
        if (!$this->record->canView()) {
301
            return $this->httpError(403, _t(
302
                __CLASS__ . '.ViewPermissionsFailure',
303
                'It seems you don\'t have the necessary permissions to view "{ObjectTitle}"',
304
                ['ObjectTitle' => $this->record->singular_name()]
305
            ));
306
        }
307
308
        $controller = $this->getToplevelController();
309
310
        $form = $this->ItemEditForm();
311
        $form->makeReadonly();
0 ignored issues
show
Bug introduced by
The method makeReadonly() does not exist on SilverStripe\Control\HTTPResponse. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

311
        $form->/** @scrutinizer ignore-call */ 
312
               makeReadonly();

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...
312
313
        return $this->returnWithinContext($request, $controller, $form);
0 ignored issues
show
Bug introduced by
$form of type SilverStripe\Control\HTTPResponse is incompatible with the type SilverStripe\Forms\Form expected by parameter $form of LeKoala\Tabulator\Tabula...::returnWithinContext(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

313
        return $this->returnWithinContext($request, $controller, /** @scrutinizer ignore-type */ $form);
Loading history...
314
    }
315
316
    /**
317
     * This is responsible to forward actions to the model if necessary
318
     * @param HTTPRequest $request
319
     * @return HTTPResponse
320
     */
321
    public function customAction(HTTPRequest $request)
322
    {
323
        // This gets populated thanks to our updated URL handler
324
        $params = $request->params();
325
        $customAction = $params['CustomAction'] ?? null;
326
        $ID = $params['ID'] ?? 0;
327
328
        $dataClass = $this->tabulatorGrid->getModelClass();
329
        $record = DataObject::get_by_id($dataClass, $ID);
330
        $rowActions = $record->tabulatorRowActions();
331
        $validActions = array_keys($rowActions);
332
        if (!$customAction || !in_array($customAction, $validActions)) {
333
            return $this->httpError(403, _t(
334
                __CLASS__ . '.CustomActionPermissionsFailure',
335
                'It seems you don\'t have the necessary permissions to {ActionName} "{ObjectTitle}"',
336
                ['ActionName' => $customAction, 'ObjectTitle' => $this->record->singular_name()]
337
            ));
338
        }
339
340
        $clickedAction = $rowActions[$customAction];
341
342
        $error = false;
343
        try {
344
            $result = $record->$customAction();
345
        } catch (Exception $e) {
346
            $error = true;
347
            $result = $e->getMessage();
348
        }
349
350
        // Maybe it's a custom redirect or a file ?
351
        if ($result && $result instanceof HTTPResponse) {
352
            return $result;
353
        }
354
355
        // Show message on controller or in form
356
        $controller = $this->getToplevelController();
357
        $response = $controller->getResponse();
358
        if (Director::is_ajax()) {
359
            $responseData = [
360
                'message' => $result,
361
                'status' => $error ? 'error' : 'success',
362
            ];
363
            if (!empty($clickedAction['reload'])) {
364
                $responseData['reload'] = true;
365
            }
366
            if (!empty($clickedAction['refresh'])) {
367
                $responseData['refresh'] = true;
368
            }
369
            $response->setBody(json_encode($responseData));
370
            // 4xx status makes a red box
371
            if ($error) {
372
                $response->setStatusCode(400);
373
            }
374
            return $response;
375
        }
376
377
        $this->sessionMessage($result, $error ? "error" : "good", "html");
378
379
        $url = $this->getDefaultBackLink();
380
        return $this->redirect($url);
381
    }
382
383
    public function sessionMessage($message, $type = ValidationResult::TYPE_ERROR, $cast = ValidationResult::CAST_TEXT)
384
    {
385
        $controller = $this->getToplevelController();
386
        if ($controller->hasMethod('sessionMessage')) {
387
            $controller->sessionMessage($message, $type, $cast);
388
        } else {
389
            $form = $this->ItemEditForm();
390
            if ($form) {
0 ignored issues
show
introduced by
$form is of type SilverStripe\Control\HTTPResponse, thus it always evaluated to true.
Loading history...
391
                $form->sessionMessage($message, $type, $cast);
0 ignored issues
show
Bug introduced by
The method sessionMessage() does not exist on SilverStripe\Control\HTTPResponse. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

391
                $form->/** @scrutinizer ignore-call */ 
392
                       sessionMessage($message, $type, $cast);

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...
392
            }
393
        }
394
    }
395
396
    /**
397
     * Builds an item edit form
398
     *
399
     * @return Form|HTTPResponse
400
     */
401
    public function ItemEditForm()
402
    {
403
        $list = $this->tabulatorGrid->getList();
404
        $controller = $this->getToplevelController();
405
406
        try {
407
            $record = $this->getRecord();
408
        } catch (Exception $e) {
409
            $url = $controller->getRequest()->getURL();
410
            $noActionURL = $controller->removeAction($url);
411
            //clear the existing redirect
412
            $controller->getResponse()->removeHeader('Location');
413
            return $controller->redirect($noActionURL, 302);
414
        }
415
416
        // If we are creating a new record in a has-many list, then
417
        // pre-populate the record's foreign key.
418
        if ($list instanceof HasManyList && !$this->record->isInDB()) {
419
            $key = $list->getForeignKey();
420
            $id = $list->getForeignID();
421
            $record->$key = $id;
422
        }
423
424
        if (!$record->canView()) {
425
            return $controller->httpError(403, _t(
426
                __CLASS__ . '.ViewPermissionsFailure',
427
                'It seems you don\'t have the necessary permissions to view "{ObjectTitle}"',
428
                ['ObjectTitle' => $this->record->singular_name()]
429
            ));
430
        }
431
432
        if ($record->hasMethod("tabulatorCMSFields")) {
433
            $fields = $record->tabulatorCMSFields();
434
        } else {
435
            $fields = $record->getCMSFields();
436
        }
437
438
        // If we are creating a new record in a has-many list, then
439
        // Disable the form field as it has no effect.
440
        if ($list instanceof HasManyList && !$this->record->isInDB()) {
441
            $key = $list->getForeignKey();
442
443
            if ($field = $fields->dataFieldByName($key)) {
444
                $fields->makeFieldReadonly($field);
445
            }
446
        }
447
448
        $compatLayer = $this->tabulatorGrid->getCompatLayer($controller);
449
450
        $actions = $compatLayer->getFormActions($this);
451
        $this->extend('updateFormActions', $actions);
452
453
        $validator = null;
454
455
        $form = new Form(
456
            $this,
457
            'ItemEditForm',
458
            $fields,
459
            $actions,
460
            $validator
461
        );
462
463
        $form->loadDataFrom($record, $record->ID == 0 ? Form::MERGE_IGNORE_FALSEISH : Form::MERGE_DEFAULT);
464
465
        if ($record->ID && !$record->canEdit()) {
466
            // Restrict editing of existing records
467
            $form->makeReadonly();
468
            // Hack to re-enable delete button if user can delete
469
            if ($record->canDelete()) {
470
                $form->Actions()->fieldByName('action_doDelete')->setReadonly(false);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $form->Actions()->fieldByName('action_doDelete') targeting SilverStripe\Forms\FieldList::fieldByName() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
471
            }
472
        }
473
        $cannotCreate = !$record->ID && !$record->canCreate(null, $this->getCreateContext());
474
        if ($cannotCreate) {
475
            // Restrict creation of new records
476
            $form->makeReadonly();
477
        }
478
479
        // Load many_many extraData for record.
480
        // Fields with the correct 'ManyMany' namespace need to be added manually through getCMSFields().
481
        if ($list instanceof ManyManyList) {
482
            $extraData = $list->getExtraData('', $this->record->ID);
483
            $form->loadDataFrom(['ManyMany' => $extraData]);
484
        }
485
486
        // Coupling with CMS
487
        $compatLayer->adjustItemEditForm($this, $form);
488
489
        $this->extend("updateItemEditForm", $form);
490
491
        return $form;
492
    }
493
494
    /**
495
     * Build context for verifying canCreate
496
     *
497
     * @return array
498
     */
499
    protected function getCreateContext()
500
    {
501
        $grid = $this->tabulatorGrid;
502
        $context = [];
503
        if ($grid->getList() instanceof RelationList) {
504
            $record = $grid->getForm()->getRecord();
505
            if ($record && $record instanceof DataObject) {
0 ignored issues
show
introduced by
$record is always a sub-type of SilverStripe\ORM\DataObject.
Loading history...
506
                $context['Parent'] = $record;
507
            }
508
        }
509
        return $context;
510
    }
511
512
    /**
513
     * @return \SilverStripe\Control\Controller|\SilverStripe\Admin\LeftAndMain|TabulatorGrid_ItemRequest
0 ignored issues
show
Bug introduced by
The type SilverStripe\Admin\LeftAndMain was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
514
     */
515
    public function getToplevelController(): RequestHandler
516
    {
517
        $c = $this->popupController;
518
        // Maybe our field is included in a GridField or in a TabulatorGrid?
519
        while ($c && ($c instanceof GridFieldDetailForm_ItemRequest || $c instanceof TabulatorGrid_ItemRequest)) {
520
            $c = $c->getController();
521
        }
522
        return $c;
523
    }
524
525
    public function getDefaultBackLink(): string
526
    {
527
        $url = $this->getBackURL()
528
            ?: $this->getReturnReferer()
529
            ?: $this->AbsoluteLink();
530
        return $url;
531
    }
532
533
    public function getBackLink(): string
534
    {
535
        $backlink = '';
536
        $toplevelController = $this->getToplevelController();
537
        if ($this->popupController->hasMethod('Breadcrumbs')) {
538
            $parents = $this->popupController->Breadcrumbs(false);
539
            if ($parents && $parents = $parents->items) {
540
                $backlink = array_pop($parents)->Link;
541
            }
542
        }
543
        if ($toplevelController && $toplevelController->hasMethod('Backlink')) {
544
            $backlink = $toplevelController->Backlink();
545
        }
546
        if (!$backlink) {
547
            $backlink = $toplevelController->Link();
548
        }
549
        return $backlink;
550
    }
551
552
    /**
553
     * Get the list of extra data from the $record as saved into it by
554
     * {@see Form::saveInto()}
555
     *
556
     * Handles detection of falsey values explicitly saved into the
557
     * DataObject by formfields
558
     *
559
     * @param DataObject $record
560
     * @param SS_List $list
0 ignored issues
show
Bug introduced by
The type LeKoala\Tabulator\SS_List was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
561
     * @return array List of data to write to the relation
562
     */
563
    protected function getExtraSavedData($record, $list)
564
    {
565
        // Skip extra data if not ManyManyList
566
        if (!($list instanceof ManyManyList)) {
567
            return null;
568
        }
569
570
        $data = [];
571
        foreach ($list->getExtraFields() as $field => $dbSpec) {
572
            $savedField = "ManyMany[{$field}]";
573
            if ($record->hasField($savedField)) {
574
                $data[$field] = $record->getField($savedField);
575
            }
576
        }
577
        return $data;
578
    }
579
580
    public function doSave($data, $form)
581
    {
582
        $isNewRecord = $this->record->ID == 0;
583
584
        // Check permission
585
        if (!$this->record->canEdit()) {
586
            return $this->editFailure();
587
        }
588
589
        // _activetab is used in cms-action
590
        $this->hash = $data['_hash'] ?? $data['_activetab'] ?? '';
591
592
        // Save from form data
593
        $error = false;
594
        try {
595
            $this->saveFormIntoRecord($data, $form);
596
597
            $title = $this->record->Title ?? '';
598
            $link = '<a href="' . $this->Link('edit') . '">"'
599
                . htmlspecialchars($title, ENT_QUOTES)
600
                . '"</a>';
601
            $message = _t(
602
                'SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Saved',
603
                'Saved {name} {link}',
604
                [
605
                    'name' => $this->record->i18n_singular_name(),
606
                    'link' => $link
607
                ]
608
            );
609
        } catch (Exception $e) {
610
            $message = $e->getMessage();
611
            $error = true;
612
        }
613
614
        $this->sessionMessage($message, $error ? "error" : "good", 'html');
615
616
        // Redirect after save
617
        return $this->redirectAfterSave($isNewRecord);
618
    }
619
620
    /**
621
     * Gets the edit link for a record
622
     *
623
     * @param  int $id The ID of the record in the GridField
624
     * @return string
625
     */
626
    public function getEditLink($id)
627
    {
628
        $link = Controller::join_links(
629
            $this->tabulatorGrid->Link(),
630
            'item',
631
            $id
632
        );
633
634
        return $link;
635
    }
636
637
    /**
638
     * @param int $offset The offset from the current record
639
     * @return int|bool
640
     */
641
    private function getAdjacentRecordID($offset)
642
    {
643
        $list = $this->getManipulatedData();
644
        $map = array_column($list['data'], "ID");
645
        $index = array_search($this->record->ID, $map);
646
        return isset($map[$index + $offset]) ? $map[$index + $offset] : false;
647
    }
648
649
    /**
650
     * Gets the ID of the previous record in the list.
651
     */
652
    public function getPreviousRecordID(): int
653
    {
654
        return $this->getAdjacentRecordID(-1);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getAdjacentRecordID(-1) could return the type boolean which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
655
    }
656
657
    /**
658
     * Gets the ID of the next record in the list.
659
     */
660
    public function getNextRecordID(): int
661
    {
662
        return $this->getAdjacentRecordID(1);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getAdjacentRecordID(1) could return the type boolean which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
663
    }
664
665
    /**
666
     * This is expected in lekoala/silverstripe-cms-actions ActionsGridFieldItemRequest
667
     * @return HTTPResponse
668
     */
669
    public function getResponse()
670
    {
671
        return $this->getToplevelController()->getResponse();
672
    }
673
674
    /**
675
     * Response object for this request after a successful save
676
     *
677
     * @param bool $isNewRecord True if this record was just created
678
     * @return HTTPResponse|DBHTMLText
0 ignored issues
show
Bug introduced by
The type LeKoala\Tabulator\DBHTMLText was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
679
     */
680
    protected function redirectAfterSave($isNewRecord)
681
    {
682
        $controller = $this->getToplevelController();
683
        if ($isNewRecord) {
684
            return $this->redirect($this->Link());
685
        } elseif ($this->tabulatorGrid->hasByIDList() && $this->tabulatorGrid->getByIDList()->byID($this->record->ID)) {
686
            return $this->redirect($this->getDefaultBackLink());
687
        } else {
688
            // Changes to the record properties might've excluded the record from
689
            // a filtered list, so return back to the main view if it can't be found
690
            $url = $controller->getRequest()->getURL();
691
            $noActionURL = $controller->removeAction($url);
692
            if ($this->isSilverStripeAdmin($controller)) {
693
                $controller->getRequest()->addHeader('X-Pjax', 'Content');
694
            }
695
            return $controller->redirect($noActionURL, 302);
696
        }
697
    }
698
699
    protected function getHashValue()
700
    {
701
        if ($this->hash) {
702
            $hash = $this->hash;
703
        } else {
704
            $hash = Cookie::get('hash');
705
        }
706
        if ($hash) {
707
            $hash = '#' . ltrim($hash, '#');
708
        }
709
        return $hash;
710
    }
711
712
    /**
713
     * Redirect to the given URL.
714
     *
715
     * @param string $url
716
     * @param int $code
717
     * @return HTTPResponse
718
     */
719
    public function redirect($url, $code = 302): HTTPResponse
720
    {
721
        $hash = $this->getHashValue();
722
        if ($hash) {
723
            $url .= $hash;
724
        }
725
        $response = parent::redirect($url, $code);
726
727
        // if ($hash) {
728
        // We also pass it as a hash
729
        // @link https://github.com/whatwg/fetch/issues/1167
730
        // $response = $response->addHeader('X-Hash', $hash);
731
        // }
732
733
        return $response;
734
    }
735
736
    public function httpError($errorCode, $errorMessage = null)
737
    {
738
        $controller = $this->getToplevelController();
739
        return $controller->httpError($errorCode, $errorMessage);
740
    }
741
742
    /**
743
     * Loads the given form data into the underlying dataobject and relation
744
     *
745
     * @param array $data
746
     * @param Form $form
747
     * @throws ValidationException On error
748
     * @return DataObject Saved record
749
     */
750
    protected function saveFormIntoRecord($data, $form)
751
    {
752
        $list = $this->tabulatorGrid->getList();
753
754
        // Check object matches the correct classname
755
        if (isset($data['ClassName']) && $data['ClassName'] != $this->record->ClassName) {
756
            $newClassName = $data['ClassName'];
757
            // The records originally saved attribute was overwritten by $form->saveInto($record) before.
758
            // This is necessary for newClassInstance() to work as expected, and trigger change detection
759
            // on the ClassName attribute
760
            $this->record->setClassName($this->record->ClassName);
761
            // Replace $record with a new instance
762
            $this->record = $this->record->newClassInstance($newClassName);
763
        }
764
765
        // Save form and any extra saved data into this dataobject.
766
        // Set writeComponents = true to write has-one relations / join records
767
        $form->saveInto($this->record);
768
        // https://github.com/silverstripe/silverstripe-assets/issues/365
769
        $this->record->write();
770
        $this->extend('onAfterSave', $this->record);
771
772
        $extraData = $this->getExtraSavedData($this->record, $list);
773
        $list->add($this->record, $extraData);
0 ignored issues
show
Unused Code introduced by
The call to SilverStripe\ORM\SS_List::add() has too many arguments starting with $extraData. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

773
        $list->/** @scrutinizer ignore-call */ 
774
               add($this->record, $extraData);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
774
775
        return $this->record;
776
    }
777
778
    /**
779
     * @param array $data
780
     * @param Form $form
781
     * @return HTTPResponse
782
     * @throws ValidationException
783
     */
784
    public function doDelete($data, $form)
785
    {
786
        $title = $this->record->Title;
787
        if (!$this->record->canDelete()) {
788
            throw new ValidationException(
789
                _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.DeletePermissionsFailure', "No delete permissions")
790
            );
791
        }
792
793
        $this->record->delete();
794
795
        $message = _t(
796
            'SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Deleted',
797
            'Deleted {type} {name}',
798
            [
799
                'type' => $this->record->i18n_singular_name(),
800
                'name' => htmlspecialchars($title, ENT_QUOTES)
801
            ]
802
        );
803
804
805
        $backForm = $form;
0 ignored issues
show
Unused Code introduced by
The assignment to $backForm is dead and can be removed.
Loading history...
806
        $toplevelController = $this->getToplevelController();
807
        if ($this->isSilverStripeAdmin($toplevelController)) {
808
            $backForm = $toplevelController->getEditForm();
809
        }
810
        $this->sessionMessage($message, "good");
811
812
        //when an item is deleted, redirect to the parent controller
813
        $controller = $this->getToplevelController();
814
815
        if ($this->isSilverStripeAdmin($toplevelController)) {
816
            $controller->getRequest()->addHeader('X-Pjax', 'Content');
817
        }
818
        return $controller->redirect($this->getBackLink(), 302); //redirect back to admin section
819
    }
820
821
    public function isSilverStripeAdmin($controller)
822
    {
823
        if ($controller) {
824
            return is_subclass_of($controller, \SilverStripe\Admin\LeftAndMain::class);
825
        }
826
        return false;
827
    }
828
829
    /**
830
     * @param string $template
831
     * @return $this
832
     */
833
    public function setTemplate($template)
834
    {
835
        $this->template = $template;
836
        return $this;
837
    }
838
839
    /**
840
     * @return string
841
     */
842
    public function getTemplate()
843
    {
844
        return $this->template;
845
    }
846
847
    /**
848
     * Get list of templates to use
849
     *
850
     * @return array
851
     */
852
    public function getTemplates()
853
    {
854
        $templates = SSViewer::get_templates_by_class($this, '', __CLASS__);
855
        // Prefer any custom template
856
        if ($this->getTemplate()) {
857
            array_unshift($templates, $this->getTemplate());
858
        }
859
        return $templates;
860
    }
861
862
    /**
863
     * @return Controller
864
     */
865
    public function getController()
866
    {
867
        return $this->popupController;
868
    }
869
870
    /**
871
     * @return TabulatorGrid
872
     */
873
    public function getTabulatorGrid()
874
    {
875
        return $this->tabulatorGrid;
876
    }
877
878
    /**
879
     * @return DataObject
880
     */
881
    public function getRecord()
882
    {
883
        return $this->record;
884
    }
885
886
    /**
887
     * CMS-specific functionality: Passes through navigation breadcrumbs
888
     * to the template, and includes the currently edited record (if any).
889
     * see {@link LeftAndMain->Breadcrumbs()} for details.
890
     *
891
     * @param boolean $unlinked
892
     * @return ArrayList
893
     */
894
    public function Breadcrumbs($unlinked = false)
895
    {
896
        if (!$this->popupController->hasMethod('Breadcrumbs')) {
897
            return null;
898
        }
899
900
        /** @var ArrayList $items */
901
        $items = $this->popupController->Breadcrumbs($unlinked);
902
903
        if (!$items) {
0 ignored issues
show
introduced by
$items is of type SilverStripe\ORM\ArrayList, thus it always evaluated to true.
Loading history...
904
            $items = new ArrayList();
905
        }
906
907
        if ($this->record && $this->record->ID) {
908
            $title = ($this->record->Title) ? $this->record->Title : "#{$this->record->ID}";
909
            $items->push(new ArrayData([
910
                'Title' => $title,
911
                'Link' => $this->Link()
912
            ]));
913
        } else {
914
            $items->push(new ArrayData([
915
                'Title' => _t('SilverStripe\\Forms\\GridField\\GridField.NewRecord', 'New {type}', ['type' => $this->record->i18n_singular_name()]),
916
                'Link' => false
917
            ]));
918
        }
919
920
        $this->extend('updateBreadcrumbs', $items);
921
        return $items;
922
    }
923
}
924