Completed
Pull Request — master (#415)
by
unknown
02:13
created

AssetFormFactory::getForm()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 24
rs 8.6845
cc 4
eloc 12
nc 5
nop 3
1
<?php
2
3
namespace SilverStripe\AssetAdmin\Forms;
4
5
use InvalidArgumentException;
6
use SilverStripe\Assets\File;
7
use SilverStripe\Control\Controller;
8
use SilverStripe\Core\Config\Configurable;
9
use SilverStripe\Core\Extensible;
10
use SilverStripe\Core\Injector\Injectable;
11
use SilverStripe\Forms\FieldList;
12
use SilverStripe\Forms\Form;
13
use SilverStripe\Forms\FormAction;
14
use SilverStripe\Forms\FormFactory;
15
use SilverStripe\Forms\HeaderField;
16
use SilverStripe\Forms\HiddenField;
17
use SilverStripe\Forms\PopoverField;
18
use SilverStripe\Forms\RequiredFields;
19
use SilverStripe\Forms\Tab;
20
use SilverStripe\Forms\TabSet;
21
use SilverStripe\Forms\TextField;
22
23
abstract class AssetFormFactory implements FormFactory
24
{
25
    use Extensible;
26
    use Injectable;
27
    use Configurable;
28
29
    /**
30
     * Insert into HTML content area
31
     */
32
    const TYPE_INSERT = 'insert';
33
34
    /**
35
     * Select file by ID only
36
     */
37
    const TYPE_SELECT = 'select';
38
39
    /**
40
     * Edit form: Default
41
     */
42
    const TYPE_ADMIN = 'admin';
43
44
    public function __construct()
45
    {
46
        $this->constructExtensions();
47
    }
48
49
    public function getForm(Controller $controller, $name = FormFactory::DEFAULT_NAME, $context = [])
50
    {
51
        // Validate context
52
        foreach ($this->getRequiredContext() as $required) {
53
            if (!isset($context[$required])) {
54
                throw new InvalidArgumentException("Missing required context $required");
55
            }
56
        }
57
58
        $fields = $this->getFormFields($controller, $name, $context);
59
        $actions = $this->getFormActions($controller, $name, $context);
60
        $validator = $this->getValidator($controller, $name, $context);
61
        $form = Form::create($controller, $name, $fields, $actions, $validator);
62
63
        // Extend form
64
        $this->invokeWithExtensions('updateForm', $form, $controller, $name, $context);
65
66
        // Populate form from record
67
        if (isset($context['Record'])) {
68
            $form->loadDataFrom($context['Record']);
69
        }
70
71
        return $form;
72
    }
73
    
74
    /**
75
     * Get the validator for the form to be built
76
     *
77
     * @param $controller
78
     * @param $name
79
     * @param $context
80
     * @return RequiredFields
81
     */
82
    protected function getValidator(Controller $controller, $name, $context = []) {
0 ignored issues
show
Unused Code introduced by
The parameter $controller 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 $name 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 $context 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...
83
        $validator = new RequiredFields('Name');
84
        
85
        return $validator;
86
    }
87
88
    /**
89
     * Get form type from 'type' context
90
     *
91
     * @param array $context
92
     * @return string
93
     */
94
    protected function getFormType($context)
95
    {
96
        return empty($context['Type']) ? static::TYPE_ADMIN : $context['Type'];
97
    }
98
99
    /**
100
     * Gets the main tabs for the file edit form
101
     *
102
     * @param File $record
103
     * @return TabSet
104
     */
105
    protected function getFormFieldTabs($record, $context = [])
106
    {
107
        $tabs = TabSet::create('Editor', $this->getFormFieldDetailsTab($record));
108
109
        return $tabs;
110
    }
111
112
    /**
113
     * @param File $record
114
     * @return FormAction
115
     */
116 View Code Duplication
    protected function getSaveAction($record)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
117
    {
118
        if ($record && $record->isInDB() && $record->canEdit()) {
119
            return FormAction::create('save', _t('CMSMain.SAVE', 'Save'))
120
                ->setIcon('save');
121
        }
122
        return null;
123
    }
124
125
    /**
126
     * Get delete action, if this record is deletable
127
     *
128
     * @param File $record
129
     * @return FormAction
130
     */
131 View Code Duplication
    protected function getDeleteAction($record)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
132
    {
133
        // Delete action
134
        if ($record && $record->isInDB() && $record->canDelete()) {
135
            $deleteText = _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.DELETE_BUTTON', 'Delete');
136
            return FormAction::create('delete', $deleteText)
137
                ->setIcon('trash-bin');
138
        }
139
        return null;
140
    }
141
142
    protected function getFormActions(Controller $controller, $name, $context = [])
143
    {
144
        $record = isset($context['Record']) ? $context['Record'] : null;
145
146
        $actions = new FieldList();
147
        if ($saveAction = $this->getSaveAction($record)) {
148
            $actions->push($saveAction);
149
        }
150
        $menu = $this->getPopoverMenu($record);
151
        if ($menu && $menu->FieldList()->count()) {
152
            $actions->push($menu);
153
        }
154
155
        $this->invokeWithExtensions('updateFormActions', $actions, $controller, $name, $context);
156
        return $actions;
157
    }
158
159
    /**
160
     * Get fields for this form
161
     *
162
     * @param Controller $controller
163
     * @param string $name
164
     * @param array $context
165
     * @return FieldList
166
     */
167
    protected function getFormFields(Controller $controller, $name, $context = [])
168
    {
169
        $record = isset($context['Record']) ? $context['Record'] : null;
170
171
        // Build standard fields for all folders / files
172
        /** @var File $record */
173
        $fields = new FieldList(
174
            HeaderField::create('TitleHeader', $record ? $record->Title : null, 1)
175
                ->addExtraClass('editor__heading'),
176
            $this->getFormFieldTabs($record, $context)
177
        );
178
        if ($record) {
179
            $fields->push(HiddenField::create('ID', $record->ID));
180
            $fields->insertAfter(
181
                'TitleHeader',
182
                PreviewImageField::create('PreviewImage')
183
                    ->setRecordID($record->ID)
184
                    ->addExtraClass('editor__file-preview')
185
            );
186
        }
187
188
        $this->invokeWithExtensions('updateFormFields', $fields, $controller, $name, $context);
189
        return $fields;
190
    }
191
    
192
    /**
193
     * Build popup menu
194
     *
195
     * @param File $record
196
     * @return PopoverField
197
     */
198
    protected function getPopoverMenu($record)
199
    {
200
        // Build popover actions
201
        $popoverActions = $this->getPopoverActions($record);
202
        if ($popoverActions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $popoverActions 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...
203
            return PopoverField::create($popoverActions)
204
                ->setPlacement('top')
205
                ->setButtonTooltip(_t(
206
                    'SilverStripe\\AssetAdmin\\Forms\\FileFormFactory.OTHER_ACTIONS',
207
                    'Other actions'
208
                ));
209
        }
210
        return null;
211
    }
212
    
213
    /**
214
     * Get actions that go into the Popover menu
215
     *
216
     * @param $record
217
     * @return array
218
     */
219
    protected function getPopoverActions($record)
220
    {
221
        return array_filter([
222
            $this->getDeleteAction($record)
223
        ]);
224
    }
225
    
226
    /**
227
     * Build "details" formfield tab
228
     *
229
     * @param File $record
230
     * @param array $context
231
     * @return Tab
232
     */
233
    protected function getFormFieldDetailsTab($record, $context = [])
234
    {
235
        return Tab::create(
236
            'Details',
237
            TextField::create('Name', File::singleton()->fieldLabel('Filename'))
238
        );
239
    }
240
241
    public function getRequiredContext()
242
    {
243
        return ['Record'];
244
    }
245
}
246