Completed
Push — master ( 0c6a92...001811 )
by Damian
14:34
created

CMSPageAddController   C

Complexity

Total Complexity 18

Size/Duplication

Total Lines 204
Duplicated Lines 5.88 %

Coupling/Cohesion

Components 1
Dependencies 19

Importance

Changes 0
Metric Value
wmc 18
lcom 1
cbo 19
dl 12
loc 204
rs 6.875
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
B AddForm() 12 131 6
A doCancel() 0 4 1
C doAdd() 0 43 11

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace SilverStripe\CMS\Controllers;
4
5
use SilverStripe\CMS\Model\SiteTree;
6
use SilverStripe\Control\Controller;
7
use SilverStripe\Control\Session;
8
use SilverStripe\Control\HTTPResponse;
9
use SilverStripe\Forms\FieldList;
10
use SilverStripe\Forms\Form;
11
use SilverStripe\Forms\FormAction;
12
use SilverStripe\Forms\LiteralField;
13
use SilverStripe\Forms\OptionsetField;
14
use SilverStripe\Forms\SelectionGroup;
15
use SilverStripe\Forms\SelectionGroup_Item;
16
use SilverStripe\Forms\TreeDropdownField;
17
use SilverStripe\ORM\DataObject;
18
use SilverStripe\ORM\FieldType\DBField;
19
use SilverStripe\ORM\ValidationResult;
20
use SilverStripe\Security\Member;
21
use SilverStripe\Security\Security;
22
23
class CMSPageAddController extends CMSPageEditController
24
{
25
26
    private static $url_segment = 'pages/add';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
27
    private static $url_rule = '/$Action/$ID/$OtherID';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
28
    private static $url_priority = 42;
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
29
    private static $menu_title = 'Add page';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
30
    private static $required_permission_codes = 'CMS_ACCESS_CMSMain';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
31
32
    private static $allowed_actions = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
33
        'AddForm',
34
        'doAdd',
35
        'doCancel'
36
    );
37
38
    /**
39
     * @return Form
40
     */
41
    public function AddForm()
42
    {
43
        $pageTypes = array();
44
        foreach ($this->PageTypes() as $type) {
45
            $html = sprintf(
46
                '<span class="page-icon class-%s"></span><span class="title">%s</span><span class="form__field-description">%s</span>',
47
                $type->getField('ClassName'),
48
                $type->getField('AddAction'),
49
                $type->getField('Description')
50
            );
51
            $pageTypes[$type->getField('ClassName')] = DBField::create_field('HTMLFragment', $html);
52
        }
53
        // Ensure generic page type shows on top
54
        if (isset($pageTypes['Page'])) {
55
            $pageTitle = $pageTypes['Page'];
56
            $pageTypes = array_merge(array('Page' => $pageTitle), $pageTypes);
57
        }
58
59
        $numericLabelTmpl = '<span class="step-label"><span class="flyout">Step %d. </span><span class="title">%s</span></span>';
60
61
        $topTitle = _t('SilverStripe\\CMS\\Controllers\\CMSPageAddController.ParentMode_top', 'Top level');
62
        $childTitle = _t('SilverStripe\\CMS\\Controllers\\CMSPageAddController.ParentMode_child', 'Under another page');
63
64
        $fields = new FieldList(
65
            $parentModeField = new SelectionGroup(
66
                "ParentModeField",
67
                array(
68
                    new SelectionGroup_Item(
69
                        "top",
70
                        null,
71
                        $topTitle
72
                    ),
73
                    new SelectionGroup_Item(
74
                        'child',
75
                        $parentField = new TreeDropdownField(
76
                            "ParentID",
77
                            "",
78
                            'SilverStripe\\CMS\\Model\\SiteTree',
79
                            'ID',
80
                            'TreeTitle'
81
                        ),
82
                        $childTitle
83
                    )
84
                )
85
            ),
86
            new LiteralField(
87
                'RestrictedNote',
88
                sprintf(
89
                    '<p class="message notice message-restricted">%s</p>',
90
                    _t(
91
                        'SilverStripe\\CMS\\Controllers\\CMSMain.AddPageRestriction',
92
                        'Note: Some page types are not allowed for this selection'
93
                    )
94
                )
95
            ),
96
            $typeField = new OptionsetField(
97
                "PageType",
98
                DBField::create_field(
99
                    'HTMLFragment',
100
                    sprintf($numericLabelTmpl, 2, _t('SilverStripe\\CMS\\Controllers\\CMSMain.ChoosePageType', 'Choose page type'))
101
                ),
102
                $pageTypes,
103
                'Page'
104
            )
105
        );
106
107
        $parentModeField->setTitle(DBField::create_field(
108
            'HTMLFragment',
109
            sprintf($numericLabelTmpl, 1, _t('SilverStripe\\CMS\\Controllers\\CMSMain.ChoosePageParentMode', 'Choose where to create this page'))
110
        ));
111
112
        $parentField->setSearchFunction(function ($sourceObject, $labelField, $search) {
113
            return DataObject::get($sourceObject)
114
                ->filterAny([
115
                    'MenuTitle:PartialMatch' => $search,
116
                    'Title:PartialMatch' => $search,
117
                ]);
118
        });
119
120
        // TODO Re-enable search once it allows for HTML title display,
121
        // see http://open.silverstripe.org/ticket/7455
122
        // $parentField->setShowSearch(true);
123
124
        $parentModeField->addExtraClass('parent-mode');
125
126
        // CMSMain->currentPageID() automatically sets the homepage,
127
        // which we need to counteract in the default selection (which should default to root, ID=0)
128
        if ($parentID = $this->getRequest()->getVar('ParentID')) {
129
            $parentModeField->setValue('child');
130
            $parentField->setValue((int)$parentID);
131
        } else {
132
            $parentModeField->setValue('top');
133
        }
134
135
        $actions = new FieldList(
136
            FormAction::create("doAdd", _t('SilverStripe\\CMS\\Controllers\\CMSMain.Create', "Create"))
137
                ->addExtraClass('btn-primary font-icon-plus-circled')
138
                ->setUseButtonTag(true),
139
            FormAction::create("doCancel", _t('SilverStripe\\CMS\\Controllers\\CMSMain.Cancel', "Cancel"))
140
                ->addExtraClass('btn-secondary')
141
                ->setUseButtonTag(true)
142
        );
143
144
        $this->extend('updatePageOptions', $fields);
145
146
        $negotiator = $this->getResponseNegotiator();
147
        $form = Form::create(
148
            $this,
149
            "AddForm",
150
            $fields,
151
            $actions
152
        )->setHTMLID('Form_AddForm')->setStrictFormMethodCheck(false);
153
        $form->setAttribute('data-hints', $this->SiteTreeHints());
154
        $form->setAttribute('data-childfilter', $this->Link('childfilter'));
155 View Code Duplication
        $form->setValidationResponseCallback(function (ValidationResult $errors) use ($negotiator, $form) {
0 ignored issues
show
Unused Code introduced by
The parameter $errors is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
156
            $request = $this->getRequest();
157
            if ($request->isAjax() && $negotiator) {
158
                $result = $form->forTemplate();
159
                return $negotiator->respond($request, array(
160
                    'CurrentForm' => function () use ($result) {
161
                        return $result;
162
                    }
163
                ));
164
            }
165
            return null;
166
        });
167
        $form->addExtraClass('flexbox-area-grow fill-height cms-add-form cms-content cms-edit-form ' . $this->BaseCSSClasses());
168
        $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
0 ignored issues
show
Bug introduced by
It seems like $this->getTemplatesWithSuffix('_EditForm') targeting SilverStripe\Admin\LeftA...etTemplatesWithSuffix() can also be of type array; however, SilverStripe\Forms\Form::setTemplate() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
169
170
        return $form;
171
    }
172
173
    /**
174
     * @param array $data
175
     * @param Form $form
176
     * @return HTTPResponse
177
     */
178
    public function doAdd($data, $form)
179
    {
180
        $className = isset($data['PageType']) ? $data['PageType'] : "Page";
181
        $parentID = isset($data['ParentID']) ? (int)$data['ParentID'] : 0;
182
183
        if (!$parentID && isset($data['Parent'])) {
184
            $page = SiteTree::get_by_link($data['Parent']);
185
            if ($page) {
186
                $parentID = $page->ID;
187
            }
188
        }
189
190
        if (is_numeric($parentID) && $parentID > 0) {
191
            $parentObj = SiteTree::get()->byID($parentID);
192
        } else {
193
            $parentObj = null;
194
        }
195
196
        if (!$parentObj || !$parentObj->ID) {
197
            $parentID = 0;
198
        }
199
200
        if (!singleton($className)->canCreate(Security::getCurrentUser(), array('Parent' => $parentObj))) {
201
            return Security::permissionFailure($this);
202
        }
203
204
        $record = $this->getNewItem("new-$className-$parentID", false);
205
        $this->extend('updateDoAdd', $record, $form);
206
        $record->write();
207
208
        $editController = CMSPageEditController::singleton();
209
        $editController->setRequest($this->getRequest());
210
        $editController->setCurrentPageID($record->ID);
211
212
        $session = $this->getRequest()->getSession();
213
        $session->set(
214
            "FormInfo.Form_EditForm.formError.message",
215
            _t('SilverStripe\\CMS\\Controllers\\CMSMain.PageAdded', 'Successfully created page')
216
        );
217
        $session->set("FormInfo.Form_EditForm.formError.type", 'good');
218
219
        return $this->redirect(Controller::join_links($editController->Link('show'), $record->ID));
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->redirect(\SilverS...'show'), $record->ID)); of type string|SilverStripe\Control\HTTPResponse adds the type string to the return on line 219 which is incompatible with the return type documented by SilverStripe\CMS\Control...ageAddController::doAdd of type SilverStripe\Control\HTTPResponse.
Loading history...
220
    }
221
222
    public function doCancel($data, $form)
0 ignored issues
show
Unused Code introduced by
The parameter $data is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $form is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
223
    {
224
        return $this->redirect(CMSMain::singleton()->Link());
225
    }
226
}
227