Completed
Push — master ( 708319...e0d939 )
by Daniel
22:58
created

onAfterRevertToLive()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 2
1
<?php
2
3
/**
4
 * @package userforms
5
 */
6
class UserFormFieldEditorExtension extends DataExtension
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
7
{
8
9
    /**
10
     * @var array
11
     */
12
    private static $has_many = array(
0 ignored issues
show
Unused Code introduced by
The property $has_many is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
13
        'Fields' => 'EditableFormField'
14
    );
15
16
    /**
17
     * Adds the field editor to the page.
18
     *
19
     * @return FieldList
20
     */
21 2
    public function updateCMSFields(FieldList $fields)
22
    {
23 2
        $fieldEditor = $this->getFieldEditorGrid();
24
25 2
        $fields->insertAfter(new Tab('FormFields', _t('UserFormFieldEditorExtension.FORMFIELDS', 'Form Fields')), 'Main');
0 ignored issues
show
Documentation introduced by
'Main' is of type string, but the function expects a object<FormField>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
26 2
        $fields->addFieldToTab('Root.FormFields', $fieldEditor);
27
28 2
        return $fields;
29
    }
30
31
    /**
32
     * Gets the field editor, for adding and removing EditableFormFields.
33
     *
34
     * @return GridField
35
     */
36 2
    public function getFieldEditorGrid()
37 2
    {
38 2
        Requirements::javascript(USERFORMS_DIR . '/javascript/FieldEditor.js');
39
40 2
        $fields = $this->owner->Fields();
41
42 2
        $this->createInitialFormStep(true);
43
44 2
        $editableColumns = new GridFieldEditableColumns();
45 2
        $fieldClasses = singleton('EditableFormField')->getEditableFieldClasses();
46 2
        $editableColumns->setDisplayFields(array(
47
            'ClassName' => function ($record, $column, $grid) use ($fieldClasses) {
0 ignored issues
show
Unused Code introduced by
The parameter $grid 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...
48
                if ($record instanceof EditableFormField) {
49
                    return $record->getInlineClassnameField($column, $fieldClasses);
50
                }
51 2
            },
52 2
            'Title' => function ($record, $column, $grid) {
0 ignored issues
show
Unused Code introduced by
The parameter $grid 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...
53
                if ($record instanceof EditableFormField) {
54
                    return $record->getInlineTitleField($column);
55
                }
56
            }
57 2
        ));
58
59 2
        $config = GridFieldConfig::create()
60 2
            ->addComponents(
61 2
                $editableColumns,
62 2
                new GridFieldButtonRow(),
63 2
                GridFieldAddClassesButton::create('EditableTextField')
64 2
                    ->setButtonName(_t('UserFormFieldEditorExtension.ADD_FIELD', 'Add Field'))
65 2
                    ->setButtonClass('ss-ui-action-constructive'),
66 2
                GridFieldAddClassesButton::create('EditableFormStep')
67 2
                    ->setButtonName(_t('UserFormFieldEditorExtension.ADD_PAGE_BREAK', 'Add Page Break')),
68 2
                GridFieldAddClassesButton::create(array('EditableFieldGroup', 'EditableFieldGroupEnd'))
69 2
                    ->setButtonName(_t('UserFormFieldEditorExtension.ADD_FIELD_GROUP', 'Add Field Group')),
70 2
                new GridFieldEditButton(),
71 2
                new GridFieldDeleteAction(),
72 2
                new GridFieldToolbarHeader(),
73 2
                new GridFieldOrderableRows('Sort'),
74 2
                new GridFieldDetailForm()
75 2
            );
76
77 2
        $fieldEditor = GridField::create(
78 2
            'Fields',
79 2
            _t('UserDefinedForm.FIELDS', 'Fields'),
80 2
            $fields,
81
            $config
82 2
        )->addExtraClass('uf-field-editor');
83
84 2
        return $fieldEditor;
85
    }
86
87
    /**
88
     * A UserForm must have at least one step.
89
     * If no steps exist, create an initial step, and put all fields inside it.
90
     *
91
     * @param bool $force
92
     * @return void
93
     */
94 39
    public function createInitialFormStep($force = false)
95
    {
96
        // Only invoke once saved
97 39
        if (!$this->owner->exists()) {
98
            return;
99 1
        }
100
101
        // Check if first field is a step
102 39
        $fields = $this->owner->Fields();
103 39
        $firstField = $fields->first();
104 39
        if ($firstField instanceof EditableFormStep) {
105 9
            return;
106
        }
107
108
        // Don't create steps on write if there are no formfields, as this
109
        // can create duplicate first steps during publish of new records
110 39
        if (!$force && !$firstField) {
111 39
            return;
112
        }
113
114
        // Re-apply sort to each field starting at 2
115 2
        $next = 2;
116 2
        foreach ($fields as $field) {
117 2
            $field->Sort = $next++;
118 2
            $field->write();
119 2
        }
120
121
        // Add step
122 2
        $step = EditableFormStep::create();
123 2
        $step->Title = _t('EditableFormStep.TITLE_FIRST', 'First Page');
124 2
        $step->Sort = 1;
125 2
        $step->write();
126 2
        $fields->add($step);
127 2
    }
128
129
    /**
130
     * Ensure that at least one page exists at the start
131
     */
132 39
    public function onAfterWrite()
133
    {
134 39
        $this->createInitialFormStep();
135 39
    }
136
137
    /**
138
     * @see SiteTree::doPublish
139
     * @param Page $original
140
     *
141
     * @return void
142
     */
143 9
    public function onAfterPublish($original)
144
    {
145
        // store IDs of fields we've published
146 9
        $seenIDs = array();
147
148 9
        foreach ($this->owner->Fields() as $field) {
149
            // store any IDs of fields we publish so we don't unpublish them
150 9
            $seenIDs[] = $field->ID;
151 9
            $field->doPublish('Stage', 'Live');
152 9
            $field->destroy();
153 9
        }
154
155
        // fetch any orphaned live records
156 9
        $live = Versioned::get_by_stage("EditableFormField", "Live")
157 9
            ->filter(array(
158 9
                'ParentID' => $original->ID,
159 9
            ));
160
161 9
        if (!empty($seenIDs)) {
162 9
            $live = $live->exclude(array(
163 9
                'ID' => $seenIDs,
164 9
            ));
165 9
        }
166
167
        // delete orphaned records
168 9
        foreach ($live as $field) {
169
            $field->doDeleteFromStage('Live');
170
            $field->destroy();
171 9
        }
172 9
    }
173
174
    /**
175
     * @see SiteTree::doUnpublish
176
     * @param Page $page
177
     *
178
     * @return void
179
     */
180 1
    public function onAfterUnpublish($page)
181
    {
182 1
        foreach ($page->Fields() as $field) {
183 1
            $field->doDeleteFromStage('Live');
184 1
        }
185 1
    }
186
187
    /**
188
     * @see SiteTree::duplicate
189
     * @param DataObject $newPage
190
     *
191
     * @return DataObject
192
     */
193 1
    public function onAfterDuplicate($newPage)
194
    {
195
        // List of EditableFieldGroups, where the
196
        // key of the array is the ID of the old end group
197 1
        $fieldGroups = array();
198 1
        foreach ($this->owner->Fields() as $field) {
199 1
            $newField = $field->duplicate(false);
200 1
            $newField->ParentID = $newPage->ID;
201 1
            $newField->ParentClass = $newPage->ClassName;
202 1
            $newField->Version = 0;
203 1
            $newField->write();
204
205
            // If we encounter a group start, record it for later use
206 1
            if ($field instanceof EditableFieldGroup) {
207 1
                $fieldGroups[$field->EndID] = $newField;
0 ignored issues
show
Documentation introduced by
The property EndID does not exist on object<EditableFieldGroup>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
208 1
            }
209
210
            // If we encounter an end group, link it back to the group start
211 1
            if ($field instanceof EditableFieldGroupEnd && isset($fieldGroups[$field->ID])) {
212 1
                $groupStart = $fieldGroups[$field->ID];
213 1
                $groupStart->EndID = $newField->ID;
214 1
                $groupStart->write();
215 1
            }
216
217 1 View Code Duplication
            foreach ($field->DisplayRules() as $customRule) {
0 ignored issues
show
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...
218
                $newRule = $customRule->duplicate(false);
219
                $newRule->ParentID = $newField->ID;
220
                $newRule->Version = 0;
221
                $newRule->write();
222 1
            }
223 1
        }
224
225 1
        return $newPage;
226
    }
227
228
    /**
229
     * @see SiteTree::getIsModifiedOnStage
230
     * @param boolean $isModified
231
     *
232
     * @return boolean
233
     */
234
    public function getIsModifiedOnStage($isModified)
235
    {
236
        if (!$isModified) {
237
            foreach ($this->owner->Fields() as $field) {
238
                if ($field->getIsModifiedOnStage()) {
239
                    $isModified = true;
240
                    break;
241
                }
242
            }
243
        }
244
245
        return $isModified;
246
    }
247
248
    /**
249
     * @see SiteTree::doRevertToLive
250
     * @param Page $page
251
     *
252
     * @return void
253
     */
254 1
    public function onAfterRevertToLive($page)
255
    {
256 1
        foreach ($page->Fields() as $field) {
257 1
            $field->publish('Live', 'Stage', false);
258 1
            $field->writeWithoutVersion();
259 1
        }
260 1
    }
261
}
262