Completed
Pull Request — master (#306)
by Damian
02:01
created

FileFormFactory::getFormFieldUsageTab()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 7
nc 1
nop 2
1
<?php
2
3
namespace SilverStripe\AssetAdmin\Forms;
4
5
use SilverStripe\Assets\File;
6
use SilverStripe\Control\Controller;
7
use SilverStripe\Forms\DatetimeField;
8
use SilverStripe\Forms\FieldList;
9
use SilverStripe\Forms\FormAction;
10
use SilverStripe\Forms\LiteralField;
11
use SilverStripe\Forms\PopoverField;
12
use SilverStripe\Forms\ReadonlyField;
13
use SilverStripe\Forms\Tab;
14
use SilverStripe\Forms\TabSet;
15
use SilverStripe\Forms\TextField;
16
17
class FileFormFactory extends AssetFormFactory
18
{
19
    protected function getFormFieldTabs($record, $context = [])
20
    {
21
        // Add extra tab
22
        $tabs = TabSet::create(
23
            'Editor',
24
            $this->getFormFieldDetailsTab($record, $context),
25
            $this->getFormFieldUsageTab($record, $context),
26
            $this->getFormFieldHistoryTab($record, $context)
27
        );
28
29
        if (isset($context['Type']) && $context['Type'] === 'insert') {
30
            $tabs->setReadonly(true);
31
32
            $tabs->unshift($this->getFormFieldAttributesTab($record, $context));
33
        }
34
35
        return $tabs;
36
    }
37
38
    /**
39
     * Build "Usage" tab
40
     *
41
     * @param File $record
42
     * @param array $context
43
     * @return Tab
44
     */
45
    protected function getFormFieldUsageTab($record, $context = [])
0 ignored issues
show
Unused Code introduced by
The parameter $record 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...
46
    {
47
        // Add new tab for usage
48
        return Tab::create(
49
            'Usage',
50
            DatetimeField::create("Created", _t('AssetTableField.CREATED', 'First uploaded'))
51
                ->setReadonly(true),
52
            DatetimeField::create("LastEdited", _t('AssetTableField.LASTEDIT', 'Last changed'))
53
                ->setReadonly(true)
54
        );
55
    }
56
57
    protected function getFormFieldDetailsTab($record, $context = [])
58
    {
59
        // Update details tab
60
        $tab = Tab::create(
61
            'Details',
62
            TextField::create("Title", File::singleton()->fieldLabel('Title')),
63
            TextField::create('Name', File::singleton()->fieldLabel('Filename')),
64
            ReadonlyField::create("Path", _t('AssetTableField.PATH', 'Path'), $this->getPath($record))
65
        );
66
67
        if (isset($context['Type']) && $context['Type'] === 'insert') {
68
            $tab->push(LiteralField::create('EditLink',
69
                sprintf('<a href="%s" class="%s" target="_blank"><i class="%s" />%s</a>',
70
                    $record->CMSEditLink(),
71
                    'btn btn-secondary-outline font-icon-edit editor__edit-link',
72
                    '',
73
                    _t('AssetAdmin.EditLink', 'Edit original file')
74
                )
75
            ));
76
        }
77
        return $tab;
78
    }
79
80
    /**
81
     * Create tab for file attributes
82
     *
83
     * @param File $record
84
     * @param array $context
85
     * @return Tab
86
     */
87
    protected function getFormFieldAttributesTab($record, $context = [])
0 ignored issues
show
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...
88
    {
89
        return Tab::create(
90
            'Placement',
91
            LiteralField::create('AttributesDescription',
92
                '<p>'. _t(
93
                    'AssetAdmin.AttributesDescription',
94
                    'These changes will only affect this particular placement of the file.'
95
                ) .'</p>'
96
            ),
97
            TextField::create('Caption', _t('AssetAdmin.Caption', 'Caption'))
98
        );
99
    }
100
101
    protected function getFormFieldHistoryTab($record, $context = [])
0 ignored issues
show
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...
102
    {
103
        return Tab::create(
104
            'History',
105
            LiteralField::create('HistoryList','')
106
             ->setSchemaComponent('HistoryList')
107
             ->setSchemaData(array(
108
                'data' => array(
109
                    'fileId' => $record->ID,
110
                    'latestVersionId' => $record->Version
111
                )
112
            ))
113
        );
114
    }
115
116
    protected function getFormFields(Controller $controller, $name, $context = [])
117
    {
118
        $record = $context['Record'];
119
120
        // Add status flag before extensions are triggered
121
        $this->beforeExtending('updateFormFields', function (FieldList $fields) use ($record) {
122
            $fields->insertAfter(
123
                'TitleHeader',
124
                LiteralField::create('FileSpecs', $this->getSpecsMarkup($record))
125
            );
126
        });
127
128
        return parent::getFormFields($controller, $name, $context);
129
    }
130
131
    /**
132
     * Get publish action
133
     *
134
     * @param File $record
135
     * @return FormAction
136
     */
137
    protected function getPublishAction($record)
138
    {
139
        if (!$record || !$record->canPublish()) {
140
            return null;
141
        }
142
143
        // Build action
144
        $publishText = _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.PUBLISH_BUTTON', 'Publish');
145
        return FormAction::create('publish', $publishText)
146
            ->setIcon('rocket')
147
            ->setSchemaData(['data' => ['buttonStyle' => 'primary']]);
148
    }
149
150
    protected function getFormActions(Controller $controller, $name, $context = [])
151
    {
152
        $record = $context['Record'];
153
154
        if (isset($context['Type']) && $context['Type'] === 'insert') {
155
            $actions = new FieldList(array_filter([
156
                $this->getInsertAction($record),
157
            ]));
158
        } else {
159
            // Build top level bar
160
            $actions = new FieldList(array_filter([
161
                $this->getSaveAction($record),
162
                $this->getPublishAction($record),
163
                $this->getPopoverMenu($record),
164
            ]));
165
        }
166
167
        // Update
168
        $this->invokeWithExtensions('updateFormActions', $actions, $controller, $name, $context);
169
        return $actions;
170
    }
171
172
    /**
173
     * Get raw HTML for image markup
174
     *
175
     * @param File $file
176
     * @return string
177
     */
178
    protected function getIconMarkup($file)
179
    {
180
        $markup = parent::getIconMarkup($file);
181
        if (!$markup) {
182
            return null;
183
        }
184
        if (!$file->exists()) {
185
            return sprintf('<div class="%s">%s</div>',
186
                'editor__file-preview-message--file-missing',
187
                _t('AssetAdmin.FILE_MISSING', 'File cannot be found')
188
            );
189
        }
190
        $link = $file->Link();
191
        $linkedImage = sprintf(
192
            '<a class="%s" href="%s" target="_blank">%s</a>',
193
            'editor__file-preview-link',
194
            $link,
195
            $markup
196
        );
197
        return $linkedImage;
198
    }
199
200
    /**
201
     * get HTML for status icon
202
     *
203
     * @param File $record
204
     * @return null|string
205
     */
206
    protected function getSpecsMarkup($record)
207
    {
208
        if (!$record || !$record->exists()) {
209
            return null;
210
        }
211
        /**
212
         * Can remove .label and .label-info when Bootstrap has been updated to BS4 Beta
213
         * .label is being replaced with .tag
214
         */
215
        return sprintf(
216
            '<div class="editor__specs">
217
                <span class="label label-info tag tag-info">v.%s</span> %s %s, %s %s
218
            </div>',
219
            $record->Version,
220
            ($record->WasPublished) ? _t('File.PUBLISHED', 'Published') : _t('File.SAVED', 'Saved'),
221
            $record->dbObject('LastEdited')->Ago(),
222
            $record->getSize(),
223
            $this->getStatusFlagMarkup($record)
224
        );
225
    }
226
227
    /**
228
     * Get published status flag
229
     *
230
     * @param File $record
231
     * @return null|string
232
     */
233
    protected function getStatusFlagMarkup($record)
234
    {
235
        if ($record && ($statusTitle = $record->getStatusTitle())) {
236
            return "<span class=\"editor__status-flag\">{$statusTitle}</span>";
237
        }
238
        return null;
239
    }
240
241
    /**
242
     * Get user-visible "Path" for this record
243
     *
244
     * @param File $record
245
     * @return string
246
     */
247
    protected function getPath($record)
248
    {
249
        if ($record && $record->isInDB()) {
250
            if ($record->ParentID) {
251
                return $record->Parent()->getFilename();
252
            } else {
253
                return '/';
254
            }
255
        }
256
        return null;
257
    }
258
259
    /**
260
     * Get action for adding to campaign
261
     *
262
     * @param File $record
263
     * @return FormAction|null
264
     */
265
    protected function getAddToCampaignAction($record)
266
    {
267
        if ($record && $record->canPublish()) {
268
            return FormAction::create(
269
                'addtocampaign',
270
                _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.ADDTOCAMPAIGN', 'Add to campaign')
271
            );
272
        }
273
        return null;
274
    }
275
276
    /**
277
     * Get action for publishing
278
     *
279
     * @param File $record
280
     * @return FormAction
281
     */
282
    protected function getUnpublishAction($record)
283
    {
284
        // Check if record is unpublishable
285
        if (!$record || !$record->isPublished() || !$record->canUnpublish()) {
286
            return null;
287
        }
288
289
        // Build action
290
        $unpublishText = _t(
291
            'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.UNPUBLISH_BUTTON',
292
            'Unpublish'
293
        );
294
        return FormAction::create('unpublish', $unpublishText)
295
            ->setIcon('cancel-circled');
296
    }
297
298
    /**
299
     * Build popup menu
300
     *
301
     * @param File $record
302
     * @return PopoverField
303
     */
304
    protected function getPopoverMenu($record)
305
    {
306
        // Build popover actions
307
        $popoverActions = array_filter([
308
            $this->getAddToCampaignAction($record),
309
            $this->getUnpublishAction($record),
310
            $this->getDeleteAction($record)
311
        ]);
312
        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...
313
            return PopoverField::create($popoverActions)
314
                ->setPlacement('top');
315
        }
316
        return null;
317
    }
318
319
    /**
320
     * @param File $record
321
     * @return FormAction
322
     */
323
    protected function getInsertAction($record)
324
    {
325
        if ($record && $record->isInDB() && $record->canEdit()) {
326
            return FormAction::create('insert', _t('CMSMain.INSERT', 'Insert file'))
327
                ->setSchemaData(['data' => ['buttonStyle' => 'primary']]);
328
        }
329
        return null;
330
    }
331
332
}
333