Passed
Push — master ( dfd767...3d7f15 )
by Thomas
03:11
created

TabulatorGrid_ItemRequest::Breadcrumbs()   A

Complexity

Conditions 6
Paths 7

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 28
rs 9.1111
cc 6
nc 7
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
        'delete',
40
        'customAction',
41
        'ItemEditForm',
42
    ];
43
44
    protected TabulatorGrid $tabulatorGrid;
45
46
    /**
47
     * @var DataObject
48
     */
49
    protected $record;
50
51
    /**
52
     * @var array
53
     */
54
    protected $manipulatedData = null;
55
56
    /**
57
     * This represents the current parent RequestHandler (which does not necessarily need to be a Controller).
58
     * It allows us to traverse the RequestHandler chain upwards to reach the Controller stack.
59
     *
60
     * @var RequestHandler
61
     */
62
    protected $popupController;
63
64
    protected string $hash = '';
65
66
    protected string $template = '';
67
68
    private static $url_handlers = [
69
        'customAction/$CustomAction' => 'customAction',
70
        '$Action!' => '$Action',
71
        '' => 'edit',
72
    ];
73
74
    /**
75
     *
76
     * @param TabulatorGrid $tabulatorGrid
77
     * @param DataObject $record
78
     * @param RequestHandler $requestHandler
79
     */
80
    public function __construct($tabulatorGrid, $record, $requestHandler)
81
    {
82
        $this->tabulatorGrid = $tabulatorGrid;
83
        $this->record = $record;
84
        $this->popupController = $requestHandler;
85
        parent::__construct();
86
    }
87
88
    public function Link($action = null)
89
    {
90
        return Controller::join_links(
91
            $this->tabulatorGrid->Link('item'),
92
            $this->record->ID ? $this->record->ID : 'new',
93
            $action
94
        );
95
    }
96
97
    public function AbsoluteLink($action = null)
98
    {
99
        return Director::absoluteURL($this->Link($action));
100
    }
101
102
    protected function getManipulatedData(): array
103
    {
104
        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...
105
            return $this->manipulatedData;
106
        }
107
        $grid = $this->getTabulatorGrid();
108
109
        $state = $grid->getState($this->popupController->getRequest());
110
111
        $currentPage = $state['page'];
112
        $itemsPerPage = $state['limit'];
113
114
        $limit = $itemsPerPage + 2;
115
        $offset = max(0, $itemsPerPage * ($currentPage - 1) - 1);
116
117
        $list = $grid->getManipulatedData($limit, $offset, $state['sort'], $state['filter']);
118
119
        $this->manipulatedData = $list;
120
        return $list;
121
    }
122
123
    public function index(HTTPRequest $request)
124
    {
125
        $controller = $this->getToplevelController();
126
        return $controller->redirect($this->Link('edit'));
127
    }
128
129
    protected function returnWithinContext(HTTPRequest $request, RequestHandler $controller, Form $form)
130
    {
131
        $data = $this->customise([
132
            'Backlink' => $controller->hasMethod('Backlink') ? $controller->Backlink() : $controller->Link(),
133
            'ItemEditForm' => $form,
134
        ]);
135
136
        $return = $data->renderWith('LeKoala\\Tabulator\\TabulatorGrid_ItemEditForm');
137
        if ($request->isAjax()) {
138
            return $return;
139
        }
140
        // If not requested by ajax, we need to render it within the controller context+template
141
        return $controller->customise([
142
            'Content' => $return,
143
        ]);
144
    }
145
146
    protected function editFailure(): HTTPResponse
147
    {
148
        return $this->httpError(403, _t(
149
            __CLASS__ . '.EditPermissionsFailure',
150
            'It seems you don\'t have the necessary permissions to edit "{ObjectTitle}"',
151
            ['ObjectTitle' => $this->record->singular_name()]
152
        ));
153
    }
154
155
    /**
156
     * This is responsible to display an edit form, like GridFieldDetailForm, but much simpler
157
     *
158
     * @return mixed
159
     */
160
    public function edit(HTTPRequest $request)
161
    {
162
        if (!$this->record->canEdit()) {
163
            return $this->editFailure();
164
        }
165
        $controller = $this->getToplevelController();
166
167
        $form = $this->ItemEditForm();
168
169
        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

169
        return $this->returnWithinContext($request, $controller, /** @scrutinizer ignore-type */ $form);
Loading history...
170
    }
171
172
    public function ajaxEdit(HTTPRequest $request)
173
    {
174
        $SecurityID = $request->postVar('SecurityID');
175
        if (!SecurityToken::inst()->check($SecurityID)) {
176
            return $this->httpError(404, "Invalid SecurityID");
177
        }
178
        if (!$this->record->canEdit()) {
179
            return $this->editFailure();
180
        }
181
182
        $preventEmpty = [];
183
        if ($this->record->hasMethod('tabulatorPreventEmpty')) {
184
            $preventEmpty = $this->record->tabulatorPreventEmpty();
185
        }
186
187
        $Data = $request->postVar("Data");
0 ignored issues
show
Unused Code introduced by
The assignment to $Data is dead and can be removed.
Loading history...
188
        $Column = $request->postVar("Column");
189
        $Value = $request->postVar("Value");
190
191
        if (!$Value && in_array($Column, $preventEmpty)) {
192
            return $this->httpError(400, _t(__CLASS__ . '.ValueCannotBeEmpty', 'Value cannot be empty'));
193
        }
194
195
        try {
196
            $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

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

249
            $Data = json_decode($Data, /** @scrutinizer ignore-type */ JSON_OBJECT_AS_ARRAY);
Loading history...
250
        }
251
        $Sort = $request->postVar("Sort");
252
253
        try {
254
            $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

254
            $updatedSort = $this->executeSort($Data, /** @scrutinizer ignore-type */ $Sort);
Loading history...
255
        } catch (Exception $e) {
256
            return $this->httpError(400, $e->getMessage());
257
        }
258
259
        $response = new HTTPResponse(json_encode([
260
            'success' => true,
261
            'message' => _t(__CLASS__ . '.RecordMove', 'Record moved'),
262
            'value' => $updatedSort,
263
        ]));
264
        $response->addHeader('Content-Type', 'application/json');
265
        return $response;
266
    }
267
268
    public function executeSort(array $Data, int $Sort, string $sortField = 'Sort'): int
269
    {
270
        $table = DataObject::getSchema()->baseDataTable(get_class($this->record));
271
272
        if (!isset($Data[$sortField])) {
273
            return $this->httpError(403, _t(
274
                __CLASS__ . '.UnableToResolveSort',
275
                'Unable to resolve previous sort order'
276
            ));
277
        }
278
279
        $prevSort = $Data[$sortField];
280
281
        // Just make sure you don't have 0 (except first record) or equal sorts
282
        if ($prevSort < $Sort) {
283
            $set = "$sortField = $sortField - 1";
284
            $where = "$sortField > $prevSort and $sortField <= $Sort";
285
        } else {
286
            $set = "$sortField = $sortField + 1";
287
            $where = "$sortField < $prevSort and $sortField >= $Sort";
288
        }
289
        DB::query("UPDATE `$table` SET $set WHERE $where");
290
        $this->record->$sortField = $Sort;
291
        $this->record->write();
292
293
        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...
294
    }
295
296
297
    /**
298
     * Delete from the row level
299
     *
300
     * @param HTTPRequest $request
301
     * @return void
302
     */
303
    public function delete(HTTPRequest $request)
304
    {
305
        if (!$this->record->canDelete()) {
306
            return $this->httpError(403, _t(
307
                __CLASS__ . '.DeletePermissionsFailure',
308
                'It seems you don\'t have the necessary permissions to delete "{ObjectTitle}"',
309
                ['ObjectTitle' => $this->record->singular_name()]
310
            ));
311
        }
312
313
        $title = $this->record->getTitle();
314
        $this->record->delete();
315
316
        $message = _t(
317
            'SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Deleted',
318
            'Deleted {type} {name}',
319
            [
320
                'type' => $this->record->i18n_singular_name(),
321
                'name' => htmlspecialchars($title, ENT_QUOTES)
322
            ]
323
        );
324
325
        $this->sessionMessage($message, "good");
326
327
        //when an item is deleted, redirect to the parent controller
328
        $controller = $this->getToplevelController();
329
330
        if ($this->isSilverStripeAdmin($controller)) {
331
            $controller->getRequest()->addHeader('X-Pjax', 'Content');
332
        }
333
        return $controller->redirect($this->getBackLink(), 302); //redirect back to admin section
0 ignored issues
show
Bug Best Practice introduced by
The expression return $controller->redi...is->getBackLink(), 302) returns the type SilverStripe\Control\HTTPResponse which is incompatible with the documented return type void.
Loading history...
334
    }
335
336
    /**
337
     * @return mixed
338
     */
339
    public function view(HTTPRequest $request)
340
    {
341
        if (!$this->record->canView()) {
342
            return $this->httpError(403, _t(
343
                __CLASS__ . '.ViewPermissionsFailure',
344
                'It seems you don\'t have the necessary permissions to view "{ObjectTitle}"',
345
                ['ObjectTitle' => $this->record->singular_name()]
346
            ));
347
        }
348
349
        $controller = $this->getToplevelController();
350
351
        $form = $this->ItemEditForm();
352
        $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

352
        $form->/** @scrutinizer ignore-call */ 
353
               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...
353
354
        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

354
        return $this->returnWithinContext($request, $controller, /** @scrutinizer ignore-type */ $form);
Loading history...
355
    }
356
357
    /**
358
     * This is responsible to forward actions to the model if necessary
359
     * @param HTTPRequest $request
360
     * @return HTTPResponse
361
     */
362
    public function customAction(HTTPRequest $request)
363
    {
364
        // This gets populated thanks to our updated URL handler
365
        $params = $request->params();
366
        $customAction = $params['CustomAction'] ?? null;
367
        $ID = $params['ID'] ?? 0;
368
369
        $dataClass = $this->tabulatorGrid->getModelClass();
370
        $record = DataObject::get_by_id($dataClass, $ID);
371
        $rowActions = $record->tabulatorRowActions();
372
        $validActions = array_keys($rowActions);
373
        if (!$customAction || !in_array($customAction, $validActions)) {
374
            return $this->httpError(403, _t(
375
                __CLASS__ . '.CustomActionPermissionsFailure',
376
                'It seems you don\'t have the necessary permissions to {ActionName} "{ObjectTitle}"',
377
                ['ActionName' => $customAction, 'ObjectTitle' => $this->record->singular_name()]
378
            ));
379
        }
380
381
        $clickedAction = $rowActions[$customAction];
382
383
        $error = false;
384
        try {
385
            $result = $record->$customAction();
386
        } catch (Exception $e) {
387
            $error = true;
388
            $result = $e->getMessage();
389
        }
390
391
        // Maybe it's a custom redirect or a file ?
392
        if ($result && $result instanceof HTTPResponse) {
393
            return $result;
394
        }
395
396
        // Show message on controller or in form
397
        $controller = $this->getToplevelController();
398
        $response = $controller->getResponse();
399
        if (Director::is_ajax()) {
400
            $responseData = [
401
                'message' => $result,
402
                'status' => $error ? 'error' : 'success',
403
            ];
404
            if (!empty($clickedAction['reload'])) {
405
                $responseData['reload'] = true;
406
            }
407
            if (!empty($clickedAction['refresh'])) {
408
                $responseData['refresh'] = true;
409
            }
410
            $response->setBody(json_encode($responseData));
411
            // 4xx status makes a red box
412
            if ($error) {
413
                $response->setStatusCode(400);
414
            }
415
            return $response;
416
        }
417
418
        $this->sessionMessage($result, $error ? "error" : "good", "html");
419
420
        $url = $this->getDefaultBackLink();
421
        return $this->redirect($url);
422
    }
423
424
    public function sessionMessage($message, $type = ValidationResult::TYPE_ERROR, $cast = ValidationResult::CAST_TEXT)
425
    {
426
        $controller = $this->getToplevelController();
427
        if ($controller->hasMethod('sessionMessage')) {
428
            $controller->sessionMessage($message, $type, $cast);
429
        } else {
430
            $form = $this->ItemEditForm();
431
            if ($form) {
0 ignored issues
show
introduced by
$form is of type SilverStripe\Control\HTTPResponse, thus it always evaluated to true.
Loading history...
432
                $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

432
                $form->/** @scrutinizer ignore-call */ 
433
                       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...
433
            }
434
        }
435
    }
436
437
    /**
438
     * Builds an item edit form
439
     *
440
     * @return Form|HTTPResponse
441
     */
442
    public function ItemEditForm()
443
    {
444
        $list = $this->tabulatorGrid->getList();
445
        $controller = $this->getToplevelController();
446
447
        try {
448
            $record = $this->getRecord();
449
        } catch (Exception $e) {
450
            $url = $controller->getRequest()->getURL();
451
            $noActionURL = $controller->removeAction($url);
452
            //clear the existing redirect
453
            $controller->getResponse()->removeHeader('Location');
454
            return $controller->redirect($noActionURL, 302);
455
        }
456
457
        // If we are creating a new record in a has-many list, then
458
        // pre-populate the record's foreign key.
459
        if ($list instanceof HasManyList && !$this->record->isInDB()) {
460
            $key = $list->getForeignKey();
461
            $id = $list->getForeignID();
462
            $record->$key = $id;
463
        }
464
465
        if (!$record->canView()) {
466
            return $controller->httpError(403, _t(
467
                __CLASS__ . '.ViewPermissionsFailure',
468
                'It seems you don\'t have the necessary permissions to view "{ObjectTitle}"',
469
                ['ObjectTitle' => $this->record->singular_name()]
470
            ));
471
        }
472
473
        if ($record->hasMethod("tabulatorCMSFields")) {
474
            $fields = $record->tabulatorCMSFields();
475
        } else {
476
            $fields = $record->getCMSFields();
477
        }
478
479
        // If we are creating a new record in a has-many list, then
480
        // Disable the form field as it has no effect.
481
        if ($list instanceof HasManyList && !$this->record->isInDB()) {
482
            $key = $list->getForeignKey();
483
484
            if ($field = $fields->dataFieldByName($key)) {
485
                $fields->makeFieldReadonly($field);
486
            }
487
        }
488
489
        $compatLayer = $this->tabulatorGrid->getCompatLayer($controller);
490
491
        $actions = $compatLayer->getFormActions($this);
492
        $this->extend('updateFormActions', $actions);
493
494
        $validator = null;
495
496
        $form = new Form(
497
            $this,
498
            'ItemEditForm',
499
            $fields,
500
            $actions,
501
            $validator
502
        );
503
504
        $form->loadDataFrom($record, $record->ID == 0 ? Form::MERGE_IGNORE_FALSEISH : Form::MERGE_DEFAULT);
505
506
        if ($record->ID && !$record->canEdit()) {
507
            // Restrict editing of existing records
508
            $form->makeReadonly();
509
            // Hack to re-enable delete button if user can delete
510
            if ($record->canDelete()) {
511
                $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...
512
            }
513
        }
514
        $cannotCreate = !$record->ID && !$record->canCreate(null, $this->getCreateContext());
515
        if ($cannotCreate || $this->tabulatorGrid->isViewOnly()) {
516
            // Restrict creation of new records
517
            $form->makeReadonly();
518
        }
519
520
        // Load many_many extraData for record.
521
        // Fields with the correct 'ManyMany' namespace need to be added manually through getCMSFields().
522
        if ($list instanceof ManyManyList) {
523
            $extraData = $list->getExtraData('', $this->record->ID);
524
            $form->loadDataFrom(['ManyMany' => $extraData]);
525
        }
526
527
        // Coupling with CMS
528
        $compatLayer->adjustItemEditForm($this, $form);
529
530
        $this->extend("updateItemEditForm", $form);
531
532
        return $form;
533
    }
534
535
    /**
536
     * Build context for verifying canCreate
537
     *
538
     * @return array
539
     */
540
    protected function getCreateContext()
541
    {
542
        $grid = $this->tabulatorGrid;
543
        $context = [];
544
        if ($grid->getList() instanceof RelationList) {
545
            $record = $grid->getForm()->getRecord();
546
            if ($record && $record instanceof DataObject) {
0 ignored issues
show
introduced by
$record is always a sub-type of SilverStripe\ORM\DataObject.
Loading history...
547
                $context['Parent'] = $record;
548
            }
549
        }
550
        return $context;
551
    }
552
553
    /**
554
     * @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...
555
     */
556
    public function getToplevelController(): RequestHandler
557
    {
558
        $c = $this->popupController;
559
        // Maybe our field is included in a GridField or in a TabulatorGrid?
560
        while ($c && ($c instanceof GridFieldDetailForm_ItemRequest || $c instanceof TabulatorGrid_ItemRequest)) {
561
            $c = $c->getController();
562
        }
563
        return $c;
564
    }
565
566
    public function getDefaultBackLink(): string
567
    {
568
        $url = $this->getBackURL()
569
            ?: $this->getReturnReferer()
570
            ?: $this->AbsoluteLink();
571
        return $url;
572
    }
573
574
    public function getBackLink(): string
575
    {
576
        $backlink = '';
577
        $toplevelController = $this->getToplevelController();
578
        if ($this->popupController->hasMethod('Breadcrumbs')) {
579
            $parents = $this->popupController->Breadcrumbs(false);
580
            if ($parents && $parents = $parents->items) {
581
                $backlink = array_pop($parents)->Link;
582
            }
583
        }
584
        if ($toplevelController && $toplevelController->hasMethod('Backlink')) {
585
            $backlink = $toplevelController->Backlink();
586
        }
587
        if (!$backlink) {
588
            $backlink = $toplevelController->Link();
589
        }
590
        return $backlink;
591
    }
592
593
    /**
594
     * Get the list of extra data from the $record as saved into it by
595
     * {@see Form::saveInto()}
596
     *
597
     * Handles detection of falsey values explicitly saved into the
598
     * DataObject by formfields
599
     *
600
     * @param DataObject $record
601
     * @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...
602
     * @return array List of data to write to the relation
603
     */
604
    protected function getExtraSavedData($record, $list)
605
    {
606
        // Skip extra data if not ManyManyList
607
        if (!($list instanceof ManyManyList)) {
608
            return null;
609
        }
610
611
        $data = [];
612
        foreach ($list->getExtraFields() as $field => $dbSpec) {
613
            $savedField = "ManyMany[{$field}]";
614
            if ($record->hasField($savedField)) {
615
                $data[$field] = $record->getField($savedField);
616
            }
617
        }
618
        return $data;
619
    }
620
621
    public function doSave($data, $form)
622
    {
623
        $isNewRecord = $this->record->ID == 0;
624
625
        // Check permission
626
        if (!$this->record->canEdit()) {
627
            return $this->editFailure();
628
        }
629
630
        // _activetab is used in cms-action
631
        $this->hash = $data['_hash'] ?? $data['_activetab'] ?? '';
632
633
        // Save from form data
634
        $error = false;
635
        try {
636
            $this->saveFormIntoRecord($data, $form);
637
638
            $title = $this->record->Title ?? '';
639
            $link = '<a href="' . $this->Link('edit') . '">"'
640
                . htmlspecialchars($title, ENT_QUOTES)
641
                . '"</a>';
642
            $message = _t(
643
                'SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Saved',
644
                'Saved {name} {link}',
645
                [
646
                    'name' => $this->record->i18n_singular_name(),
647
                    'link' => $link
648
                ]
649
            );
650
        } catch (Exception $e) {
651
            $message = $e->getMessage();
652
            $error = true;
653
        }
654
655
        $this->sessionMessage($message, $error ? "error" : "good", 'html');
656
657
        // Redirect after save
658
        return $this->redirectAfterSave($isNewRecord);
659
    }
660
661
    /**
662
     * Gets the edit link for a record
663
     *
664
     * @param  int $id The ID of the record in the GridField
665
     * @return string
666
     */
667
    public function getEditLink($id)
668
    {
669
        $link = Controller::join_links(
670
            $this->tabulatorGrid->Link(),
671
            'item',
672
            $id
673
        );
674
675
        return $link;
676
    }
677
678
    /**
679
     * @param int $offset The offset from the current record
680
     * @return int|bool
681
     */
682
    private function getAdjacentRecordID($offset)
683
    {
684
        $list = $this->getManipulatedData();
685
        $map = array_column($list['data'], "ID");
686
        $index = array_search($this->record->ID, $map);
687
        return isset($map[$index + $offset]) ? $map[$index + $offset] : false;
688
    }
689
690
    /**
691
     * Gets the ID of the previous record in the list.
692
     */
693
    public function getPreviousRecordID(): int
694
    {
695
        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...
696
    }
697
698
    /**
699
     * Gets the ID of the next record in the list.
700
     */
701
    public function getNextRecordID(): int
702
    {
703
        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...
704
    }
705
706
    /**
707
     * This is expected in lekoala/silverstripe-cms-actions ActionsGridFieldItemRequest
708
     * @return HTTPResponse
709
     */
710
    public function getResponse()
711
    {
712
        return $this->getToplevelController()->getResponse();
713
    }
714
715
    /**
716
     * Response object for this request after a successful save
717
     *
718
     * @param bool $isNewRecord True if this record was just created
719
     * @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...
720
     */
721
    protected function redirectAfterSave($isNewRecord)
722
    {
723
        $controller = $this->getToplevelController();
724
        if ($isNewRecord) {
725
            return $this->redirect($this->Link());
726
        } elseif ($this->tabulatorGrid->hasByIDList() && $this->tabulatorGrid->getByIDList()->byID($this->record->ID)) {
727
            return $this->redirect($this->getDefaultBackLink());
728
        } else {
729
            // Changes to the record properties might've excluded the record from
730
            // a filtered list, so return back to the main view if it can't be found
731
            $url = $controller->getRequest()->getURL();
732
            $noActionURL = $controller->removeAction($url);
733
            if ($this->isSilverStripeAdmin($controller)) {
734
                $controller->getRequest()->addHeader('X-Pjax', 'Content');
735
            }
736
            return $controller->redirect($noActionURL, 302);
737
        }
738
    }
739
740
    protected function getHashValue()
741
    {
742
        if ($this->hash) {
743
            $hash = $this->hash;
744
        } else {
745
            $hash = Cookie::get('hash');
746
        }
747
        if ($hash) {
748
            $hash = '#' . ltrim($hash, '#');
749
        }
750
        return $hash;
751
    }
752
753
    /**
754
     * Redirect to the given URL.
755
     *
756
     * @param string $url
757
     * @param int $code
758
     * @return HTTPResponse
759
     */
760
    public function redirect($url, $code = 302): HTTPResponse
761
    {
762
        $hash = $this->getHashValue();
763
        if ($hash) {
764
            $url .= $hash;
765
        }
766
        $response = parent::redirect($url, $code);
767
768
        // if ($hash) {
769
        // We also pass it as a hash
770
        // @link https://github.com/whatwg/fetch/issues/1167
771
        // $response = $response->addHeader('X-Hash', $hash);
772
        // }
773
774
        return $response;
775
    }
776
777
    public function httpError($errorCode, $errorMessage = null)
778
    {
779
        $controller = $this->getToplevelController();
780
        return $controller->httpError($errorCode, $errorMessage);
781
    }
782
783
    /**
784
     * Loads the given form data into the underlying dataobject and relation
785
     *
786
     * @param array $data
787
     * @param Form $form
788
     * @throws ValidationException On error
789
     * @return DataObject Saved record
790
     */
791
    protected function saveFormIntoRecord($data, $form)
792
    {
793
        $list = $this->tabulatorGrid->getList();
794
795
        // Check object matches the correct classname
796
        if (isset($data['ClassName']) && $data['ClassName'] != $this->record->ClassName) {
797
            $newClassName = $data['ClassName'];
798
            // The records originally saved attribute was overwritten by $form->saveInto($record) before.
799
            // This is necessary for newClassInstance() to work as expected, and trigger change detection
800
            // on the ClassName attribute
801
            $this->record->setClassName($this->record->ClassName);
802
            // Replace $record with a new instance
803
            $this->record = $this->record->newClassInstance($newClassName);
804
        }
805
806
        // Save form and any extra saved data into this dataobject.
807
        // Set writeComponents = true to write has-one relations / join records
808
        $form->saveInto($this->record);
809
        // https://github.com/silverstripe/silverstripe-assets/issues/365
810
        $this->record->write();
811
        $this->extend('onAfterSave', $this->record);
812
813
        $extraData = $this->getExtraSavedData($this->record, $list);
814
        $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

814
        $list->/** @scrutinizer ignore-call */ 
815
               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...
815
816
        return $this->record;
817
    }
818
819
    /**
820
     * Delete from ItemRequest action
821
     *
822
     * @param array $data
823
     * @param Form $form
824
     * @return HTTPResponse
825
     * @throws ValidationException
826
     */
827
    public function doDelete($data, $form)
828
    {
829
        $title = $this->record->Title;
830
        if (!$this->record->canDelete()) {
831
            throw new ValidationException(
832
                _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.DeletePermissionsFailure', "No delete permissions")
833
            );
834
        }
835
836
        $this->record->delete();
837
838
        $message = _t(
839
            'SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Deleted',
840
            'Deleted {type} {name}',
841
            [
842
                'type' => $this->record->i18n_singular_name(),
843
                'name' => htmlspecialchars($title, ENT_QUOTES)
844
            ]
845
        );
846
847
848
        $backForm = $form;
0 ignored issues
show
Unused Code introduced by
The assignment to $backForm is dead and can be removed.
Loading history...
849
        $toplevelController = $this->getToplevelController();
850
        if ($this->isSilverStripeAdmin($toplevelController)) {
851
            $backForm = $toplevelController->getEditForm();
852
        }
853
        $this->sessionMessage($message, "good");
854
855
        //when an item is deleted, redirect to the parent controller
856
        $controller = $this->getToplevelController();
857
858
        if ($this->isSilverStripeAdmin($toplevelController)) {
859
            $controller->getRequest()->addHeader('X-Pjax', 'Content');
860
        }
861
        return $controller->redirect($this->getBackLink(), 302); //redirect back to admin section
862
    }
863
864
    public function isSilverStripeAdmin($controller)
865
    {
866
        if ($controller) {
867
            return is_subclass_of($controller, \SilverStripe\Admin\LeftAndMain::class);
868
        }
869
        return false;
870
    }
871
872
    /**
873
     * @param string $template
874
     * @return $this
875
     */
876
    public function setTemplate($template)
877
    {
878
        $this->template = $template;
879
        return $this;
880
    }
881
882
    /**
883
     * @return string
884
     */
885
    public function getTemplate()
886
    {
887
        return $this->template;
888
    }
889
890
    /**
891
     * Get list of templates to use
892
     *
893
     * @return array
894
     */
895
    public function getTemplates()
896
    {
897
        $templates = SSViewer::get_templates_by_class($this, '', __CLASS__);
898
        // Prefer any custom template
899
        if ($this->getTemplate()) {
900
            array_unshift($templates, $this->getTemplate());
901
        }
902
        return $templates;
903
    }
904
905
    /**
906
     * @return Controller
907
     */
908
    public function getController()
909
    {
910
        return $this->popupController;
911
    }
912
913
    /**
914
     * @return TabulatorGrid
915
     */
916
    public function getTabulatorGrid()
917
    {
918
        return $this->tabulatorGrid;
919
    }
920
921
    /**
922
     * @return DataObject
923
     */
924
    public function getRecord()
925
    {
926
        return $this->record;
927
    }
928
929
    /**
930
     * CMS-specific functionality: Passes through navigation breadcrumbs
931
     * to the template, and includes the currently edited record (if any).
932
     * see {@link LeftAndMain->Breadcrumbs()} for details.
933
     *
934
     * @param boolean $unlinked
935
     * @return ArrayList
936
     */
937
    public function Breadcrumbs($unlinked = false)
938
    {
939
        if (!$this->popupController->hasMethod('Breadcrumbs')) {
940
            return null;
941
        }
942
943
        /** @var ArrayList $items */
944
        $items = $this->popupController->Breadcrumbs($unlinked);
945
946
        if (!$items) {
0 ignored issues
show
introduced by
$items is of type SilverStripe\ORM\ArrayList, thus it always evaluated to true.
Loading history...
947
            $items = new ArrayList();
948
        }
949
950
        if ($this->record && $this->record->ID) {
951
            $title = ($this->record->Title) ? $this->record->Title : "#{$this->record->ID}";
952
            $items->push(new ArrayData([
953
                'Title' => $title,
954
                'Link' => $this->Link()
955
            ]));
956
        } else {
957
            $items->push(new ArrayData([
958
                'Title' => _t('SilverStripe\\Forms\\GridField\\GridField.NewRecord', 'New {type}', ['type' => $this->record->i18n_singular_name()]),
959
                'Link' => false
960
            ]));
961
        }
962
963
        $this->extend('updateBreadcrumbs', $items);
964
        return $items;
965
    }
966
}
967