Passed
Pull Request — master (#28)
by
unknown
03:15
created

SitewideContentReport::columns()   B

Complexity

Conditions 5
Paths 2

Size

Total Lines 66
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 37
nc 2
nop 1
dl 0
loc 66
rs 8.6045
c 0
b 0
f 0

How to fix   Long Method   

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\SiteWideContentReport;
4
5
use SilverStripe\Forms\FieldList;
6
use SilverStripe\Forms\GridField\GridField;
7
use SilverStripe\Subsites\Model\Subsite;
0 ignored issues
show
Bug introduced by
The type SilverStripe\Subsites\Model\Subsite 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...
8
use Page;
0 ignored issues
show
Bug introduced by
The type Page 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...
9
use SilverStripe\Versioned\Versioned;
10
use SilverStripe\CMS\Model\SiteTree;
11
use SilverStripe\Assets\File;
12
use SilverStripe\Assets\Folder;
13
use SilverStripe\View\Requirements;
14
use SilverStripe\Forms\HeaderField;
15
use SilverStripe\Forms\DropdownField;
16
use SilverStripe\SiteWideContentReport\Form\GridFieldBasicContentReport;
17
use SilverStripe\Forms\GridField\GridFieldConfig;
18
use SilverStripe\Forms\GridField\GridFieldToolbarHeader;
19
use SilverStripe\Forms\GridField\GridFieldSortableHeader;
20
use SilverStripe\Forms\GridField\GridFieldDataColumns;
21
use SilverStripe\Forms\GridField\GridFieldPaginator;
22
use SilverStripe\Forms\GridField\GridFieldButtonRow;
23
use SilverStripe\Forms\GridField\GridFieldPrintButton;
24
use SilverStripe\Forms\GridField\GridFieldExportButton;
25
use SilverStripe\CMS\Controllers\CMSPageEditController;
26
use SilverStripe\Control\Controller;
27
use SilverStripe\AssetAdmin\Controller\AssetAdmin;
28
use SilverStripe\Reports\Report;
29
30
/**
31
 * Content side-report listing all pages and files from all sub sites.
32
 *
33
 * Class SitewideContentReport
34
 * @package SilverStripe\SiteWideContentReport
35
 */
36
class SitewideContentReport extends Report
37
{
38
    /**
39
     * @return string
40
     */
41
    public function title()
42
    {
43
        return _t('SitewideContentReport.Title', 'Site-wide content report');
44
    }
45
46
    /**
47
     * @return string
48
     */
49
    public function description()
50
    {
51
        return _t('SitewideContentReport.Description', 'All pages and files across all Subsites');
52
    }
53
54
    /**
55
     * Returns an array with 2 elements, one with a list of Page on the site (and all subsites if
56
     * applicable) and another with files.
57
     *
58
     * @return array
59
     */
60
    public function sourceRecords()
61
    {
62
        if (class_exists('Subsite') && Subsite::get()->count() > 0) {
63
            $origMode = Versioned::get_reading_mode();
64
            Versioned::set_reading_mode('Stage.Stage');
65
            $items = [
66
                'Pages' => Subsite::get_from_all_subsites(SiteTree::class),
67
                'Files' => Subsite::get_from_all_subsites(File::class),
68
            ];
69
            Versioned::set_reading_mode($origMode);
70
71
            return $items;
72
        } else {
73
            return [
74
                'Pages' => Versioned::get_by_stage(SiteTree::class, 'Stage'),
75
                'Files' => File::get(),
76
            ];
77
        }
78
    }
79
80
    /**
81
     * Returns columns for the grid fields on this report.
82
     *
83
     * @param string $itemType (i.e 'Pages' or 'Files')
84
     *
85
     * @return array
86
     */
87
    public function columns($itemType = 'Pages')
88
    {
89
        $columns = [
90
            'Title' => [
91
                'title' => _t('SitewideContentReport.Name', 'Name'),
92
                'link' => true,
93
            ],
94
            'Created' => [
95
                'title' => _t('SitewideContentReport.Created', 'Date created'),
96
                'formatting' => function ($value, $item) {
97
                    return $item->dbObject('Created')->Nice();
98
                },
99
            ],
100
            'LastEdited' => [
101
                'title' => _t('SitewideContentReport.LastEdited', 'Date last edited'),
102
                'formatting' => function ($value, $item) {
103
                    return $item->dbObject('LastEdited')->Nice();
104
                },
105
            ],
106
        ];
107
108
        if ($itemType == 'Pages') {
109
            // Page specific fields
110
            $columns['i18n_singular_name'] = _t('SitewideContentReport.PageType', 'Page type');
111
            $columns['StageState'] = [
112
                'title' => _t('SitewideContentReport.Stage', 'Stage'),
113
                'formatting' => function ($value, $item) {
114
                    // Stage only
115
                    if (!$item->getExistsOnLive()) {
116
                        return _t('SitewideContentReport.Draft', 'Draft');
117
                    }
118
119
                    // Pending changes
120
                    if ($item->getIsModifiedOnStage()) {
121
                        return _t('SitewideContentReport.PublishedWithChanges', 'Published (with changes)');
122
                    }
123
124
                    // If on live and unmodified
125
                    return _t('SitewideContentReport.Published', 'Published');
126
                },
127
            ];
128
            $columns['RelativeLink'] = _t('SitewideContentReport.Link', 'Link');
129
            $columns['MetaDescription'] = [
130
                'title' => _t('SitewideContentReport.MetaDescription', 'Description'),
131
                'printonly' => true,
132
            ];
133
        } else {
134
            // File specific fields
135
            $columns['FileType'] = [
136
                'title' => _t('SitewideContentReport.FileType', 'File type'),
137
                'datasource' => function ($record) {
138
                    // Handle folders separately
139
                    if ($record instanceof Folder) {
140
                        return $record->i18n_singular_name();
141
                    }
142
143
                    return $record->getFileType();
144
                }
145
            ];
146
            $columns['Size'] = _t('SitewideContentReport.Size', 'Size');
147
            $columns['Filename'] = _t('SitewideContentReport.Directory', 'Directory');
148
        }
149
150
        $this->extend('updateColumns', $itemType, $columns);
151
152
        return $columns;
153
    }
154
155
    /**
156
     * @return FieldList
157
     */
158
    public function getCMSFields()
159
    {
160
        Requirements::javascript('silverstripe/sitewidecontent-report: javascript/sitewidecontentreport.js');
161
        $fields = parent::getCMSFields();
162
163
        if (class_exists('Subsite')) {
164
            $subsites = Subsite::all_sites()->map();
165
            $fields->insertBefore(HeaderField::create('PagesTitle', _t('SitewideContentReport.Pages', 'Pages'), 3), 'Report-Pages');
0 ignored issues
show
Bug introduced by
'Report-Pages' of type string is incompatible with the type SilverStripe\Forms\FormField expected by parameter $item of SilverStripe\Forms\FieldList::insertBefore(). ( Ignorable by Annotation )

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

165
            $fields->insertBefore(HeaderField::create('PagesTitle', _t('SitewideContentReport.Pages', 'Pages'), 3), /** @scrutinizer ignore-type */ 'Report-Pages');
Loading history...
Bug introduced by
'PagesTitle' of type string is incompatible with the type array expected by parameter $args of SilverStripe\View\ViewableData::create(). ( Ignorable by Annotation )

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

165
            $fields->insertBefore(HeaderField::create(/** @scrutinizer ignore-type */ 'PagesTitle', _t('SitewideContentReport.Pages', 'Pages'), 3), 'Report-Pages');
Loading history...
Bug introduced by
3 of type integer is incompatible with the type array expected by parameter $args of SilverStripe\View\ViewableData::create(). ( Ignorable by Annotation )

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

165
            $fields->insertBefore(HeaderField::create('PagesTitle', _t('SitewideContentReport.Pages', 'Pages'), /** @scrutinizer ignore-type */ 3), 'Report-Pages');
Loading history...
166
            $fields->insertBefore(DropdownField::create('AllSubsites', _t('SitewideContentReport.FilterBy', 'Filter by:'), $subsites)
167
                ->addExtraClass('subsite-filter no-change-track')
168
                ->setEmptyString('All Subsites'), 'Report-Pages');
169
        }
170
171
        $fields->push(HeaderField::create('FilesTitle', _t('SitewideContentReport.Files', 'Files'), 3));
172
        $fields->push($this->getReportField('Files'));
173
174
        return $fields;
175
    }
176
177
    /**
178
     * Creates a GridField for pages and another one for files with different columns.
179
     * Grid fields have an export and a print button.
180
     *
181
     * @param string $itemType (i.e 'Pages' or 'Files')
182
     *
183
     * @return GridField
184
     */
185
    public function getReportField($itemType = 'Pages')
186
    {
187
        $params = isset($_REQUEST['filters']) ? $_REQUEST['filters'] : array();
188
        $items = $this->sourceRecords($params, null, null);
0 ignored issues
show
Unused Code introduced by
The call to SilverStripe\SiteWideCon...Report::sourceRecords() has too many arguments starting with $params. ( Ignorable by Annotation )

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

188
        /** @scrutinizer ignore-call */ 
189
        $items = $this->sourceRecords($params, null, null);

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...
189
190
        $gridField = new GridFieldBasicContentReport('Report-'.$itemType, false, $items[$itemType]);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type string expected by parameter $title of SilverStripe\SiteWideCon...ntReport::__construct(). ( Ignorable by Annotation )

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

190
        $gridField = new GridFieldBasicContentReport('Report-'.$itemType, /** @scrutinizer ignore-type */ false, $items[$itemType]);
Loading history...
191
192
        $gridFieldConfig = GridFieldConfig::create()->addComponents(
193
            new GridFieldToolbarHeader(),
194
            new GridFieldSortableHeader(),
195
            new GridFieldDataColumns(),
196
            new GridFieldPaginator(),
197
            new GridFieldButtonRow('after'),
198
            $printButton = new GridFieldPrintButton('buttons-after-left'),
199
            $exportButton = new GridFieldExportButton('buttons-after-left')
200
        );
201
202
        $gridField->setConfig($gridFieldConfig);
203
204
        /* @var $columns GridFieldDataColumns */
205
        $columns = $gridField->getConfig()->getComponentByType(GridFieldDataColumns::class);
206
207
        $exportFields = [];
208
        $displayFields = [];
209
        $fieldCasting = [];
210
        $fieldFormatting = [];
211
        $dataFields = [];
212
213
        // Parse the column information
214
        foreach ($this->columns($itemType) as $source => $info) {
215
            if (is_string($info)) {
216
                $info = ['title' => $info];
217
            }
218
219
            if (isset($info['formatting'])) {
220
                $fieldFormatting[$source] = $info['formatting'];
221
            }
222
            if (isset($info['casting'])) {
223
                $fieldCasting[$source] = $info['casting'];
224
            }
225
226
            if (isset($info['link']) && $info['link']) {
227
                $fieldFormatting[$source] = function ($value, &$item) {
228
                    if ($item instanceof Page) {
229
                        return sprintf(
230
                            "<a href='%s'>%s</a>",
231
                            Controller::join_links(singleton(CMSPageEditController::class)->Link('show'), $item->ID),
232
                            $value
233
                        );
234
                    }
235
236
                    return sprintf(
237
                        "<a href='%s'>%s</a>",
238
                        Controller::join_links(
239
                            singleton(AssetAdmin::class)->Link('EditForm'), 'field/File/item', $item->ID, 'edit'
240
                        ),
241
                        $value
242
                    );
243
                };
244
            }
245
246
            // Set custom datasource
247
            if (isset($info['datasource'])) {
248
                $dataFields[$source] = $info['datasource'];
249
            }
250
251
            // Set field name for export
252
            $fieldTitle = isset($info['title']) ? $info['title'] : $source;
253
254
            // If not print-only, then add to display list
255
            if (empty($info['printonly'])) {
256
                $displayFields[$source] = $fieldTitle;
257
            }
258
259
            // Assume that all displayed fields are printed also
260
            $exportFields[$source] = $fieldTitle;
261
        }
262
263
        // Set custom evaluated columns
264
        $gridField->addDataFields($dataFields);
265
266
        // Set visible fields
267
        $columns->setDisplayFields($displayFields);
268
        $columns->setFieldCasting($fieldCasting);
269
        $columns->setFieldFormatting($fieldFormatting);
270
271
        // Get print columns, and merge with print-only columns
272
        $printExportColumns = $this->getPrintExportColumns($gridField, $itemType, $exportFields);
273
274
        $printButton->setPrintColumns($printExportColumns);
275
        $exportButton->setExportColumns($printExportColumns);
276
277
        return $gridField;
278
    }
279
280
    /**
281
     * Returns the columns for the export and print functionality.
282
     *
283
     * @param GridField $gridField
284
     * @param string    $itemType      (i.e 'Pages' or 'Files')
285
     * @param array     $exportColumns
286
     *
287
     * @return array
288
     */
289
    public function getPrintExportColumns($gridField, $itemType, $exportColumns)
290
    {
291
        // Swap RelativeLink for AbsoluteLink for export
292
        $exportColumns['AbsoluteLink'] = _t('SitewideContentReport.Link', 'Link');
293
        unset($exportColumns['RelativeLink']);
294
295
        $this->extend('updatePrintExportColumns', $gridField, $itemType, $exportColumns);
296
297
        return $exportColumns;
298
    }
299
}
300