Passed
Push — fix-6460 ( 379c3e...254990 )
by Sam
09:57
created

getRightGroupField()   C

Complexity

Conditions 12
Paths 4

Size

Total Lines 65
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 44
nc 4
nop 0
dl 0
loc 65
rs 6.9666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace SilverStripe\Forms\GridField;
4
5
use SilverStripe\Admin\LeftAndMain;
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...
6
use SilverStripe\Control\Controller;
7
use SilverStripe\Control\HTTPRequest;
8
use SilverStripe\Control\HTTPResponse;
9
use SilverStripe\Control\RequestHandler;
10
use SilverStripe\Forms\CompositeField;
11
use SilverStripe\Forms\FieldList;
12
use SilverStripe\Forms\Form;
13
use SilverStripe\Forms\FormAction;
14
use SilverStripe\Forms\HiddenField;
15
use SilverStripe\Forms\LiteralField;
16
use SilverStripe\ORM\ArrayList;
17
use SilverStripe\ORM\DataObject;
18
use SilverStripe\ORM\FieldType\DBHTMLText;
19
use SilverStripe\ORM\HasManyList;
20
use SilverStripe\ORM\ManyManyList;
21
use SilverStripe\ORM\SS_List;
22
use SilverStripe\ORM\ValidationException;
23
use SilverStripe\ORM\ValidationResult;
24
use SilverStripe\View\ArrayData;
25
use SilverStripe\View\HTML;
26
use SilverStripe\View\SSViewer;
27
28
class GridFieldDetailForm_ItemRequest extends RequestHandler
29
{
30
31
    private static $allowed_actions = array(
32
        'edit',
33
        'view',
34
        'ItemEditForm'
35
    );
36
37
    /**
38
     *
39
     * @var GridField
40
     */
41
    protected $gridField;
42
43
    /**
44
     *
45
     * @var GridFieldDetailForm
46
     */
47
    protected $component;
48
49
    /**
50
     * @var DataObject
51
     */
52
    protected $record;
53
54
    /**
55
     * This represents the current parent RequestHandler (which does not necessarily need to be a Controller).
56
     * It allows us to traverse the RequestHandler chain upwards to reach the Controller stack.
57
     *
58
     * @var RequestHandler
59
     */
60
    protected $popupController;
61
62
    /**
63
     *
64
     * @var string
65
     */
66
    protected $popupFormName;
67
68
    /**
69
     * @var String
70
     */
71
    protected $template = null;
72
73
    private static $url_handlers = array(
74
        '$Action!' => '$Action',
75
        '' => 'edit',
76
    );
77
78
    /**
79
     *
80
     * @param GridField $gridField
81
     * @param GridFieldDetailForm $component
82
     * @param DataObject $record
83
     * @param RequestHandler $requestHandler
84
     * @param string $popupFormName
85
     */
86
    public function __construct($gridField, $component, $record, $requestHandler, $popupFormName)
87
    {
88
        $this->gridField = $gridField;
89
        $this->component = $component;
90
        $this->record = $record;
91
        $this->popupController = $requestHandler;
92
        $this->popupFormName = $popupFormName;
93
        parent::__construct();
94
    }
95
96
    public function Link($action = null)
97
    {
98
        return Controller::join_links(
99
            $this->gridField->Link('item'),
100
            $this->record->ID ? $this->record->ID : 'new',
101
            $action
102
        );
103
    }
104
105
    /**
106
     * @param HTTPRequest $request
107
     * @return mixed
108
     */
109
    public function view($request)
110
    {
111
        if (!$this->record->canView()) {
112
            $this->httpError(403);
113
        }
114
115
        $controller = $this->getToplevelController();
116
117
        $form = $this->ItemEditForm();
118
        $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

118
        $form->/** @scrutinizer ignore-call */ 
119
               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...
119
120
        $data = new ArrayData(array(
121
            'Backlink'     => $controller->Link(),
122
            'ItemEditForm' => $form
123
        ));
124
        $return = $data->renderWith($this->getTemplates());
125
126
        if ($request->isAjax()) {
127
            return $return;
128
        } else {
129
            return $controller->customise(array('Content' => $return));
130
        }
131
    }
132
133
    /**
134
     * @param HTTPRequest $request
135
     * @return mixed
136
     */
137
    public function edit($request)
138
    {
139
        $controller = $this->getToplevelController();
140
        $form = $this->ItemEditForm();
141
142
        $return = $this->customise(array(
143
            'Backlink' => $controller->hasMethod('Backlink') ? $controller->Backlink() : $controller->Link(),
0 ignored issues
show
Bug introduced by
The method Backlink() does not exist on SilverStripe\Control\Controller. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

143
            'Backlink' => $controller->hasMethod('Backlink') ? $controller->/** @scrutinizer ignore-call */ Backlink() : $controller->Link(),
Loading history...
144
            'ItemEditForm' => $form,
145
        ))->renderWith($this->getTemplates());
146
147
        if ($request->isAjax()) {
148
            return $return;
149
        } else {
150
            // If not requested by ajax, we need to render it within the controller context+template
151
            return $controller->customise(array(
152
                // TODO CMS coupling
153
                'Content' => $return,
154
            ));
155
        }
156
    }
157
158
    /**
159
     * Builds an item edit form.  The arguments to getCMSFields() are the popupController and
160
     * popupFormName, however this is an experimental API and may change.
161
     *
162
     * @todo In the future, we will probably need to come up with a tigher object representing a partially
163
     * complete controller with gaps for extra functionality.  This, for example, would be a better way
164
     * of letting Security/login put its log-in form inside a UI specified elsewhere.
165
     *
166
     * @return Form|HTTPResponse
167
     */
168
    public function ItemEditForm()
169
    {
170
        $list = $this->gridField->getList();
171
172
        if (empty($this->record)) {
173
            $controller = $this->getToplevelController();
174
            $url = $controller->getRequest()->getURL();
175
            $noActionURL = $controller->removeAction($url);
176
            $controller->getResponse()->removeHeader('Location');   //clear the existing redirect
177
            return $controller->redirect($noActionURL, 302);
178
        }
179
180
        $canView = $this->record->canView();
181
        $canEdit = $this->record->canEdit();
182
        $canDelete = $this->record->canDelete();
183
        $canCreate = $this->record->canCreate();
184
185
        if (!$canView) {
186
            $controller = $this->getToplevelController();
187
            // TODO More friendly error
188
            return $controller->httpError(403);
189
        }
190
191
        // Build actions
192
        $actions = $this->getFormActions();
193
194
        // If we are creating a new record in a has-many list, then
195
        // pre-populate the record's foreign key.
196
        if ($list instanceof HasManyList && !$this->record->isInDB()) {
197
            $key = $list->getForeignKey();
198
            $id = $list->getForeignID();
199
            $this->record->$key = $id;
200
        }
201
202
        $fields = $this->component->getFields();
203
        if (!$fields) {
0 ignored issues
show
introduced by
$fields is of type SilverStripe\Forms\FieldList, thus it always evaluated to true.
Loading history...
204
            $fields = $this->record->getCMSFields();
205
        }
206
207
        // If we are creating a new record in a has-many list, then
208
        // Disable the form field as it has no effect.
209
        if ($list instanceof HasManyList) {
210
            $key = $list->getForeignKey();
211
212
            if ($field = $fields->dataFieldByName($key)) {
213
                $fields->makeFieldReadonly($field);
214
            }
215
        }
216
217
        $form = new Form(
218
            $this,
219
            'ItemEditForm',
220
            $fields,
221
            $actions,
222
            $this->component->getValidator()
223
        );
224
225
        $form->loadDataFrom($this->record, $this->record->ID == 0 ? Form::MERGE_IGNORE_FALSEISH : Form::MERGE_DEFAULT);
226
227
        if ($this->record->ID && !$canEdit) {
228
            // Restrict editing of existing records
229
            $form->makeReadonly();
230
            // Hack to re-enable delete button if user can delete
231
            if ($canDelete) {
232
                $form->Actions()->fieldByName('action_doDelete')->setReadonly(false);
233
            }
234
        } elseif (!$this->record->ID && !$canCreate) {
235
            // Restrict creation of new records
236
            $form->makeReadonly();
237
        }
238
239
        // Load many_many extraData for record.
240
        // Fields with the correct 'ManyMany' namespace need to be added manually through getCMSFields().
241
        if ($list instanceof ManyManyList) {
242
            $extraData = $list->getExtraData('', $this->record->ID);
243
            $form->loadDataFrom(array('ManyMany' => $extraData));
244
        }
245
246
        // TODO Coupling with CMS
247
        $toplevelController = $this->getToplevelController();
248
        if ($toplevelController && $toplevelController instanceof LeftAndMain) {
249
            // Always show with base template (full width, no other panels),
250
            // regardless of overloaded CMS controller templates.
251
            // TODO Allow customization, e.g. to display an edit form alongside a search form from the CMS controller
252
            $form->setTemplate([
253
                'type' => 'Includes',
254
                'SilverStripe\\Admin\\LeftAndMain_EditForm',
255
            ]);
256
            $form->addExtraClass('cms-content cms-edit-form center fill-height flexbox-area-grow');
257
            $form->setAttribute('data-pjax-fragment', 'CurrentForm Content');
258
            if ($form->Fields()->hasTabSet()) {
259
                $form->Fields()->findOrMakeTab('Root')->setTemplate('SilverStripe\\Forms\\CMSTabSet');
260
                $form->addExtraClass('cms-tabset');
261
            }
262
263
            $form->Backlink = $this->getBackLink();
0 ignored issues
show
Bug Best Practice introduced by
The property Backlink does not exist on SilverStripe\Forms\Form. Since you implemented __set, consider adding a @property annotation.
Loading history...
264
        }
265
266
        $cb = $this->component->getItemEditFormCallback();
267
        if ($cb) {
0 ignored issues
show
introduced by
$cb is of type Closure, thus it always evaluated to true.
Loading history...
268
            $cb($form, $this);
269
        }
270
        $this->extend("updateItemEditForm", $form);
271
        return $form;
272
    }
273
274
    /**
275
     * @return CompositeField Returns the right aligned toolbar group field along with its FormAction's
276
     */
277
    protected function getRightGroupField()
278
    {
279
        $rightGroup = CompositeField::create()->setName('RightGroup');
280
        $rightGroup->addExtraClass('ml-auto');
281
        $rightGroup->setFieldHolderTemplate(get_class($rightGroup) . '_holder_buttongroup');
282
283
        $previousAndNextGroup = CompositeField::create()->setName('PreviousAndNextGroup');
284
        $previousAndNextGroup->addExtraClass('btn-group--circular mr-2');
285
        $previousAndNextGroup->setFieldHolderTemplate(CompositeField::class . '_holder_buttongroup');
286
287
        /** @var GridFieldDetailForm $component */
288
        $component = $this->gridField->getConfig()->getComponentByType(GridFieldDetailForm::class);
289
        $paginator = $this->getGridField()->getConfig()->getComponentByType(GridFieldPaginator::class);
290
        $gridState = $this->getRequest()->requestVar('gridState');
291
        if ($component && $paginator && $component->getShowPagination()) {
0 ignored issues
show
introduced by
$paginator is of type SilverStripe\Forms\GridField\GridFieldComponent, thus it always evaluated to true.
Loading history...
292
            $previousIsDisabled = !$this->getPreviousRecordID();
293
            $nextIsDisabled = !$this->getNextRecordID();
294
295
            $previousAndNextGroup->push(
296
                LiteralField::create(
297
                    'previous-record',
298
                    HTML::createTag($previousIsDisabled ? 'span' : 'a', [
299
                        'href' => $previousIsDisabled ? '#' : $this->getEditLink($this->getPreviousRecordID()),
300
                        'data-grid-state' => $gridState,
301
                        'title' => _t(__CLASS__ . '.PREVIOUS', 'Go to previous record'),
302
                        'aria-label' => _t(__CLASS__ . '.PREVIOUS', 'Go to previous record'),
303
                        'class' => 'btn btn-secondary font-icon-left-open action--previous discard-confirmation'
304
                            . ($previousIsDisabled ? ' disabled' : ''),
305
                    ])
306
                )
307
            );
308
309
            $previousAndNextGroup->push(
310
                LiteralField::create(
311
                    'next-record',
312
                    HTML::createTag($nextIsDisabled ? 'span' : 'a', [
313
                        'href' => $nextIsDisabled ? '#' : $this->getEditLink($this->getNextRecordID()),
314
                        'data-grid-state' => $gridState,
315
                        'title' => _t(__CLASS__ . '.NEXT', 'Go to next record'),
316
                        'aria-label' => _t(__CLASS__ . '.NEXT', 'Go to next record'),
317
                        'class' => 'btn btn-secondary font-icon-right-open action--next discard-confirmation'
318
                            . ($nextIsDisabled ? ' disabled' : ''),
319
                    ])
320
                )
321
            );
322
        }
323
324
        $rightGroup->push($previousAndNextGroup);
325
326
        if ($component && $component->getShowAdd()) {
327
            $rightGroup->push(
328
                LiteralField::create(
329
                    'new-record',
330
                    HTML::createTag('a', [
331
                        'href' => Controller::join_links($this->gridField->Link('item'), 'new'),
332
                        'data-grid-state' => $gridState,
333
                        'title' => _t(__CLASS__ . '.NEW', 'Add new record'),
334
                        'aria-label' => _t(__CLASS__ . '.NEW', 'Add new record'),
335
                        'class' => 'btn btn-primary font-icon-plus-thin btn--circular action--new discard-confirmation',
336
                    ])
337
                )
338
            );
339
        }
340
341
        return $rightGroup;
342
    }
343
344
    /**
345
     * Build the set of form field actions for this DataObject
346
     *
347
     * @return FieldList
348
     */
349
    protected function getFormActions()
350
    {
351
        $actions = FieldList::create();
352
353
        if ($this->record->ID !== 0) { // existing record
354
            if ($this->record->canEdit()) {
355
                $actions->push(FormAction::create('doSave', _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Save', 'Save'))
356
                    ->setUseButtonTag(true)
357
                    ->addExtraClass('btn-primary font-icon-save'));
358
            }
359
360
            if ($this->record->canDelete()) {
361
                $actions->push(FormAction::create('doDelete', _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Delete', 'Delete'))
362
                    ->setUseButtonTag(true)
363
                    ->addExtraClass('btn-outline-danger btn-hide-outline font-icon-trash-bin action--delete'));
364
            }
365
366
            $gridState = $this->getRequest()->requestVar('gridState');
367
            $this->gridField->getState(false)->setValue($gridState);
368
            $actions->push(HiddenField::create('gridState', null, $gridState));
369
370
            $actions->push($this->getRightGroupField());
371
        } else { // adding new record
372
            //Change the Save label to 'Create'
373
            $actions->push(FormAction::create('doSave', _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Create', 'Create'))
374
                ->setUseButtonTag(true)
375
                ->addExtraClass('btn-primary font-icon-plus-thin'));
376
377
            // Add a Cancel link which is a button-like link and link back to one level up.
378
            $crumbs = $this->Breadcrumbs();
379
            if ($crumbs && $crumbs->count() >= 2) {
380
                $oneLevelUp = $crumbs->offsetGet($crumbs->count() - 2);
381
                $text = sprintf(
382
                    "<a class=\"%s\" href=\"%s\">%s</a>",
383
                    "crumb btn btn-secondary cms-panel-link", // CSS classes
384
                    $oneLevelUp->Link, // url
0 ignored issues
show
Bug Best Practice introduced by
The property Link does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
385
                    _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.CancelBtn', 'Cancel') // label
386
                );
387
                $actions->push(new LiteralField('cancelbutton', $text));
388
            }
389
        }
390
391
        $this->extend('updateFormActions', $actions);
392
393
        return $actions;
394
    }
395
396
    /**
397
     * Traverse the nested RequestHandlers until we reach something that's not GridFieldDetailForm_ItemRequest.
398
     * This allows us to access the Controller responsible for invoking the top-level GridField.
399
     * This should be equivalent to getting the controller off the top of the controller stack via Controller::curr(),
400
     * but allows us to avoid accessing the global state.
401
     *
402
     * GridFieldDetailForm_ItemRequests are RequestHandlers, and as such they are not part of the controller stack.
403
     *
404
     * @return Controller
405
     */
406
    protected function getToplevelController()
407
    {
408
        $c = $this->popupController;
409
        while ($c && $c instanceof GridFieldDetailForm_ItemRequest) {
410
            $c = $c->getController();
411
        }
412
        return $c;
413
    }
414
415
    protected function getBackLink()
416
    {
417
        // TODO Coupling with CMS
418
        $backlink = '';
419
        $toplevelController = $this->getToplevelController();
420
        if ($toplevelController && $toplevelController instanceof LeftAndMain) {
421
            if ($toplevelController->hasMethod('Backlink')) {
422
                $backlink = $toplevelController->Backlink();
423
            } elseif ($this->popupController->hasMethod('Breadcrumbs')) {
424
                $parents = $this->popupController->Breadcrumbs(false)->items;
0 ignored issues
show
Bug introduced by
The method Breadcrumbs() does not exist on SilverStripe\Control\RequestHandler. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

424
                $parents = $this->popupController->/** @scrutinizer ignore-call */ Breadcrumbs(false)->items;
Loading history...
425
                $backlink = array_pop($parents)->Link;
426
            }
427
        }
428
        if (!$backlink) {
429
            $backlink = $toplevelController->Link();
430
        }
431
432
        return $backlink;
433
    }
434
435
    /**
436
     * Get the list of extra data from the $record as saved into it by
437
     * {@see Form::saveInto()}
438
     *
439
     * Handles detection of falsey values explicitly saved into the
440
     * DataObject by formfields
441
     *
442
     * @param DataObject $record
443
     * @param SS_List $list
444
     * @return array List of data to write to the relation
445
     */
446
    protected function getExtraSavedData($record, $list)
447
    {
448
        // Skip extra data if not ManyManyList
449
        if (!($list instanceof ManyManyList)) {
450
            return null;
451
        }
452
453
        $data = array();
454
        foreach ($list->getExtraFields() as $field => $dbSpec) {
455
            $savedField = "ManyMany[{$field}]";
456
            if ($record->hasField($savedField)) {
457
                $data[$field] = $record->getField($savedField);
458
            }
459
        }
460
        return $data;
461
    }
462
463
    public function doSave($data, $form)
464
    {
465
        $isNewRecord = $this->record->ID == 0;
466
467
        // Check permission
468
        if (!$this->record->canEdit()) {
469
            return $this->httpError(403);
470
        }
471
472
        // Save from form data
473
        $this->saveFormIntoRecord($data, $form);
474
475
        $link = '<a href="' . $this->Link('edit') . '">"'
476
            . htmlspecialchars($this->record->Title, ENT_QUOTES)
477
            . '"</a>';
478
        $message = _t(
479
            'SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Saved',
480
            'Saved {name} {link}',
481
            array(
482
                'name' => $this->record->i18n_singular_name(),
483
                'link' => $link
484
            )
485
        );
486
487
        $form->sessionMessage($message, 'good', ValidationResult::CAST_HTML);
488
489
        // Redirect after save
490
        return $this->redirectAfterSave($isNewRecord);
491
    }
492
493
    /**
494
     * Gets the edit link for a record
495
     *
496
     * @param  int $id The ID of the record in the GridField
497
     * @return string
498
     */
499
    public function getEditLink($id)
500
    {
501
        return Controller::join_links(
502
            $this->gridField->Link(),
503
            'item',
504
            $id,
505
            '?gridState=' . urlencode($this->gridField->getState(false)->Value())
506
        );
507
    }
508
509
    /**
510
     * @param int $offset The offset from the current record
511
     * @return int|bool
512
     */
513
    private function getAdjacentRecordID($offset)
514
    {
515
        $gridField = $this->getGridField();
516
        $list = $gridField->getManipulatedList();
517
        $state = $gridField->getState(false);
518
        $gridStateStr = $this->getRequest()->requestVar('gridState');
519
        if (!empty($gridStateStr)) {
520
            $state->setValue($gridStateStr);
521
        }
522
        $data = $state->getData();
523
        $paginator = $data->getData('GridFieldPaginator');
524
        if (!$paginator) {
525
            return false;
526
        }
527
528
        $currentPage = $paginator->getData('currentPage');
529
        $itemsPerPage = $paginator->getData('itemsPerPage');
530
531
        $limit = $itemsPerPage + 2;
532
        $limitOffset = max(0, $itemsPerPage * ($currentPage-1) -1);
533
534
        $map = $list->limit($limit, $limitOffset)->column('ID');
0 ignored issues
show
Bug introduced by
The method limit() does not exist on SilverStripe\ORM\SS_List. It seems like you code against a sub-type of said class. However, the method does not exist in SilverStripe\ORM\Sortable or SilverStripe\ORM\Filterable. Are you sure you never get one of those? ( Ignorable by Annotation )

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

534
        $map = $list->/** @scrutinizer ignore-call */ limit($limit, $limitOffset)->column('ID');
Loading history...
535
        $index = array_search($this->record->ID, $map);
536
        return isset($map[$index+$offset]) ? $map[$index+$offset] : false;
537
    }
538
539
    /**
540
     * Gets the ID of the previous record in the list.
541
     *
542
     * @return int
543
     */
544
    public function getPreviousRecordID()
545
    {
546
        return $this->getAdjacentRecordID(-1);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getAdjacentRecordID(-1) also could return the type boolean which is incompatible with the documented return type integer.
Loading history...
547
    }
548
549
    /**
550
     * Gets the ID of the next record in the list.
551
     *
552
     * @return int
553
     */
554
    public function getNextRecordID()
555
    {
556
        return $this->getAdjacentRecordID(1);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getAdjacentRecordID(1) also could return the type boolean which is incompatible with the documented return type integer.
Loading history...
557
    }
558
559
    /**
560
     * Response object for this request after a successful save
561
     *
562
     * @param bool $isNewRecord True if this record was just created
563
     * @return HTTPResponse|DBHTMLText
564
     */
565
    protected function redirectAfterSave($isNewRecord)
566
    {
567
        $controller = $this->getToplevelController();
568
        if ($isNewRecord) {
569
            return $controller->redirect($this->Link());
570
        } elseif ($this->gridField->getList()->byID($this->record->ID)) {
0 ignored issues
show
Bug introduced by
The method byID() does not exist on SilverStripe\ORM\SS_List. It seems like you code against a sub-type of said class. However, the method does not exist in SilverStripe\ORM\Sortable or SilverStripe\ORM\Limitable. Are you sure you never get one of those? ( Ignorable by Annotation )

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

570
        } elseif ($this->gridField->getList()->/** @scrutinizer ignore-call */ byID($this->record->ID)) {
Loading history...
571
            // Return new view, as we can't do a "virtual redirect" via the CMS Ajax
572
            // to the same URL (it assumes that its content is already current, and doesn't reload)
573
            return $this->edit($controller->getRequest());
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->edit($controller->getRequest()) also could return the type SilverStripe\View\ViewableData_Customised which is incompatible with the documented return type SilverStripe\Control\HTT...RM\FieldType\DBHTMLText.
Loading history...
574
        } else {
575
            // Changes to the record properties might've excluded the record from
576
            // a filtered list, so return back to the main view if it can't be found
577
            $url = $controller->getRequest()->getURL();
578
            $noActionURL = $controller->removeAction($url);
579
            $controller->getRequest()->addHeader('X-Pjax', 'Content');
580
            return $controller->redirect($noActionURL, 302);
581
        }
582
    }
583
584
    public function httpError($errorCode, $errorMessage = null)
585
    {
586
        $controller = $this->getToplevelController();
587
        return $controller->httpError($errorCode, $errorMessage);
588
    }
589
590
    /**
591
     * Loads the given form data into the underlying dataobject and relation
592
     *
593
     * @param array $data
594
     * @param Form $form
595
     * @throws ValidationException On error
596
     * @return DataObject Saved record
597
     */
598
    protected function saveFormIntoRecord($data, $form)
599
    {
600
        $list = $this->gridField->getList();
601
602
        // Check object matches the correct classname
603
        if (isset($data['ClassName']) && $data['ClassName'] != $this->record->ClassName) {
604
            $newClassName = $data['ClassName'];
605
            // The records originally saved attribute was overwritten by $form->saveInto($record) before.
606
            // This is necessary for newClassInstance() to work as expected, and trigger change detection
607
            // on the ClassName attribute
608
            $this->record->setClassName($this->record->ClassName);
609
            // Replace $record with a new instance
610
            $this->record = $this->record->newClassInstance($newClassName);
611
        }
612
613
        // Save form and any extra saved data into this dataobject
614
        $form->saveInto($this->record);
615
        $this->record->write();
616
        $this->extend('onAfterSave', $this->record);
617
618
        $extraData = $this->getExtraSavedData($this->record, $list);
619
        $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

619
        $list->/** @scrutinizer ignore-call */ 
620
               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...
620
621
        return $this->record;
622
    }
623
624
    /**
625
     * @param array $data
626
     * @param Form $form
627
     * @return HTTPResponse
628
     * @throws ValidationException
629
     */
630
    public function doDelete($data, $form)
631
    {
632
        $title = $this->record->Title;
633
        if (!$this->record->canDelete()) {
634
            throw new ValidationException(
635
                _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.DeletePermissionsFailure', "No delete permissions")
636
            );
637
        }
638
        $this->record->delete();
639
640
        $message = _t(
641
            'SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Deleted',
642
            'Deleted {type} {name}',
643
            [
644
                'type' => $this->record->i18n_singular_name(),
645
                'name' => htmlspecialchars($title, ENT_QUOTES)
646
            ]
647
        );
648
649
        $toplevelController = $this->getToplevelController();
650
        if ($toplevelController && $toplevelController instanceof LeftAndMain) {
651
            $backForm = $toplevelController->getEditForm();
0 ignored issues
show
Bug introduced by
The method getEditForm() does not exist on SilverStripe\Control\Controller. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

651
            /** @scrutinizer ignore-call */ 
652
            $backForm = $toplevelController->getEditForm();
Loading history...
652
            $backForm->sessionMessage($message, 'good', ValidationResult::CAST_HTML);
653
        } else {
654
            $form->sessionMessage($message, 'good', ValidationResult::CAST_HTML);
655
        }
656
657
        //when an item is deleted, redirect to the parent controller
658
        $controller = $this->getToplevelController();
659
        $controller->getRequest()->addHeader('X-Pjax', 'Content'); // Force a content refresh
660
661
        return $controller->redirect($this->getBackLink(), 302); //redirect back to admin section
662
    }
663
664
    /**
665
     * @param string $template
666
     * @return $this
667
     */
668
    public function setTemplate($template)
669
    {
670
        $this->template = $template;
671
        return $this;
672
    }
673
674
    /**
675
     * @return string
676
     */
677
    public function getTemplate()
678
    {
679
        return $this->template;
680
    }
681
682
    /**
683
     * Get list of templates to use
684
     *
685
     * @return array
686
     */
687
    public function getTemplates()
688
    {
689
        $templates = SSViewer::get_templates_by_class($this, '', __CLASS__);
690
        // Prefer any custom template
691
        if ($this->getTemplate()) {
692
            array_unshift($templates, $this->getTemplate());
693
        }
694
        return $templates;
695
    }
696
697
    /**
698
     * @return Controller
699
     */
700
    public function getController()
701
    {
702
        return $this->popupController;
703
    }
704
705
    /**
706
     * @return GridField
707
     */
708
    public function getGridField()
709
    {
710
        return $this->gridField;
711
    }
712
713
    /**
714
     * @return DataObject
715
     */
716
    public function getRecord()
717
    {
718
        return $this->record;
719
    }
720
721
    /**
722
     * CMS-specific functionality: Passes through navigation breadcrumbs
723
     * to the template, and includes the currently edited record (if any).
724
     * see {@link LeftAndMain->Breadcrumbs()} for details.
725
     *
726
     * @param boolean $unlinked
727
     * @return ArrayList
728
     */
729
    public function Breadcrumbs($unlinked = false)
730
    {
731
        if (!$this->popupController->hasMethod('Breadcrumbs')) {
732
            return null;
733
        }
734
735
        /** @var ArrayList $items */
736
        $items = $this->popupController->Breadcrumbs($unlinked);
737
738
        if ($this->record && $this->record->ID) {
739
            $title = ($this->record->Title) ? $this->record->Title : "#{$this->record->ID}";
740
            $items->push(new ArrayData(array(
741
                'Title' => $title,
742
                'Link' => $this->Link()
743
            )));
744
        } else {
745
            $items->push(new ArrayData(array(
746
                'Title' => _t('SilverStripe\\Forms\\GridField\\GridField.NewRecord', 'New {type}', ['type' => $this->record->i18n_singular_name()]),
747
                'Link' => false
748
            )));
749
        }
750
751
        $this->extend('updateBreadcrumbs', $items);
752
        return $items;
753
    }
754
}
755