Completed
Push — master ( 9f244d...a6cc2e )
by Robbie
02:20
created

SiteSummary::getCMSFields()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 0
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
namespace BringYourOwnIdeas\Maintenance\Reports;
4
5
use BringYourOwnIdeas\Maintenance\Forms\GridFieldDropdownFilter;
6
use BringYourOwnIdeas\Maintenance\Forms\GridFieldHtmlFragment;
7
use BringYourOwnIdeas\Maintenance\Forms\GridFieldLinkButton;
8
use BringYourOwnIdeas\Maintenance\Forms\GridFieldRefreshButton;
9
use BringYourOwnIdeas\Maintenance\Model\Package;
10
use BringYourOwnIdeas\Maintenance\Tasks\UpdatePackageInfoTask;
11
use SilverStripe\Core\Config\Config;
12
use SilverStripe\Core\Injector\Injector;
13
use SilverStripe\Forms\GridField\GridField;
14
use SilverStripe\Forms\GridField\GridFieldConfig;
15
use SilverStripe\Forms\GridField\GridFieldExportButton;
16
use SilverStripe\Forms\GridField\GridFieldPaginator;
17
use SilverStripe\Forms\GridField\GridFieldPrintButton;
18
use SilverStripe\Forms\LiteralField;
19
use SilverStripe\ORM\FieldType\DBDatetime;
20
use SilverStripe\ORM\FieldType\DBField;
21
use SilverStripe\Reports\Report;
22
use SilverStripe\View\ArrayData;
23
use SilverStripe\View\Requirements;
24
25
/**
26
 * A report listing all installed modules used in this site (from a cache).
27
 */
28
class SiteSummary extends Report
29
{
30
    public function title()
31
    {
32
        return _t(__CLASS__ . '.TITLE', 'Installed modules');
33
    }
34
35
    public function sourceRecords()
36
    {
37
        $packageList = Package::get();
38
        $typeFilters = Config::inst()->get(UpdatePackageInfoTask::class, 'allowed_types');
39
40
        if (!empty($typeFilters)) {
41
            $packageList = $packageList->filter('Type', $typeFilters);
42
        }
43
44
        $this->extend('updateSourceRecords', $packageList);
45
46
        return $packageList;
47
    }
48
49
    /**
50
     * Provide column selection and formatting rules for the CMS report. You can extend data columns by extending
51
     * {@link Package::summary_fields}, or you can extend this method to adjust the formatting rules, or to provide
52
     * composite fields (such as Summary below) for the CMS report but not the CSV export.
53
     *
54
     * {@inheritDoc}
55
     */
56
    public function columns()
57
    {
58
        $columns = Package::create()->summaryFields();
59
60
        // Remove the default Title and Description and create Summary as a composite of both for the CMS report only
61
        unset($columns['Title'], $columns['Description']);
62
        $columns = ['Summary' => 'Summary'] + $columns;
63
64
        $this->extend('updateColumns', $columns);
65
66
        return $columns;
67
    }
68
69
    /**
70
     * Add a button row, including link out to the SilverStripe addons repository, and export button
71
     *
72
     * {@inheritdoc}
73
     */
74
    public function getReportField()
75
    {
76
        Requirements::css('bringyourownideas/silverstripe-maintenance: client/dist/styles/bundle.css');
77
78
        /** @var GridField $grid */
79
        $grid = parent::getReportField();
80
81
        /** @var GridFieldConfig $config */
82
        $config = $grid->getConfig();
83
84
        $grid->addExtraClass('site-summary');
85
86
        /** @var GridFieldExportButton $exportButton */
87
        $exportButton = $config->getComponentByType(GridFieldExportButton::class);
88
        $exportButton->setExportColumns(Package::create()->summaryFields());
89
90
        $versionHtml = ArrayData::create([
91
            'Title' => _t(__CLASS__ . '.VERSION', 'Version'),
92
            'Version' => $this->resolveCmsVersion(),
93
            'LastUpdated' => $this->getLastUpdated(),
94
        ])->renderWith('SiteSummary_VersionHeader');
95
96
        $config->addComponents(
97
            Injector::inst()->create(GridFieldRefreshButton::class, 'buttons-before-left'),
98
            Injector::inst()->create(
99
                GridFieldLinkButton::class,
100
                'https://addons.silverstripe.org',
101
                _t(__CLASS__ . '.LINK_TO_ADDONS', 'Explore Addons'),
102
                'buttons-before-left'
103
            ),
104
            $this->getDropdownFilter(),
105
            $this->getInfoLink(),
106
            Injector::inst()->create(GridFieldHtmlFragment::class, 'header', $versionHtml)
107
        );
108
109
        // Re-order the paginator to ensure it counts correctly, and reorder the buttons
110
        $paginator = $config->getComponentByType(GridFieldPaginator::class);
111
        $config->removeComponent($paginator)->addComponent($paginator);
112
113
        $exportButton = $config->getComponentByType(GridFieldExportButton::class);
114
        $config->removeComponent($exportButton)->addComponent($exportButton);
115
116
        $printButton = $config->getComponentByType(GridFieldPrintButton::class);
117
        $config->removeComponentsByType($printButton)->addComponent($printButton);
0 ignored issues
show
Bug introduced by
$printButton of type SilverStripe\Forms\GridField\GridFieldComponent is incompatible with the type string|string[] expected by parameter $types of SilverStripe\Forms\GridF...emoveComponentsByType(). ( Ignorable by Annotation )

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

117
        $config->removeComponentsByType(/** @scrutinizer ignore-type */ $printButton)->addComponent($printButton);
Loading history...
118
119
        return $grid;
120
    }
121
122
    /**
123
     * Returns a dropdown filter with user configurable options in it
124
     *
125
     * @return GridFieldDropdownFilter
126
     */
127
    protected function getDropdownFilter()
128
    {
129
        /** @var GridFieldDropdownFilter $dropdownFilter */
130
        $dropdownFilter = Injector::inst()->create(
131
            GridFieldDropdownFilter::class,
132
            'addonFilter',
133
            'buttons-before-right',
134
            _t(__CLASS__ . '.ShowAllModules', 'Show all modules')
135
        );
136
137
        $dropdownFilter->addFilterOption(
138
            'supported',
139
            _t(__CLASS__ . '.FilterSupported', 'Supported modules'),
140
            ['Supported' => true]
141
        );
142
        $dropdownFilter->addFilterOption(
143
            'unsupported',
144
            _t(__CLASS__ . '.FilterUnsupported', 'Unsupported modules'),
145
            ['Supported' => false]
146
        );
147
148
        $this->extend('updateDropdownFilterOptions', $dropdownFilter);
149
150
        return $dropdownFilter;
151
    }
152
153
    /**
154
     * Returns a link to more information on this module on the addons site
155
     *
156
     * @return GridFieldHtmlFragment
157
     */
158
    protected function getInfoLink()
159
    {
160
        return Injector::inst()->create(
161
            GridFieldHtmlFragment::class,
162
            'buttons-before-right',
163
            DBField::create_field('HTMLFragment', ArrayData::create([
164
                'Link' => 'https://addons.silverstripe.org/add-ons/bringyourownideas/silverstripe-maintenance',
165
                'Label' => _t(__CLASS__ . '.MORE_INFORMATION', 'More information'),
166
            ])->renderWith(__CLASS__ . '/MoreInformationLink'))
167
        );
168
    }
169
170
    public function getCMSFields()
171
    {
172
        $fields = parent::getCMSFields();
173
        $alerts = $this->getAlerts();
174
        if ($alerts) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $alerts 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...
175
            $summaryInfo = '<div class="site-summary message warning">' . implode("\n", $alerts) . '</div>';
176
            $fields->unshift(LiteralField::create('AlertSummary', $summaryInfo));
177
        }
178
        return $fields;
179
    }
180
181
    /**
182
     * Return a list of alerts to display in a message box above the report
183
     * A combination of free text fields - combined alerts as opposed to a message box per alert.
184
     *
185
     * @return array
186
     */
187
    protected function getAlerts()
188
    {
189
        $alerts = [];
190
        $this->extend('updateAlerts', $alerts);
191
        return $alerts;
192
    }
193
194
    /**
195
     * Extract CMS and Framework version details from the records in the report
196
     *
197
     * @return string
198
     */
199
    protected function resolveCmsVersion()
200
    {
201
        $versionModules = [
202
            'silverstripe/framework' => 'Framework',
203
            'silverstripe/cms' => 'CMS',
204
        ];
205
        $this->extend('updateVersionModules', $versionModules);
206
207
        $records = $this->sourceRecords()->filter('Name', array_keys($versionModules));
208
        $versionParts = [];
209
210
        foreach ($versionModules as $name => $label) {
211
            $record = $records->find('Name', $name);
212
            if (!$record) {
213
                $version = _t(__CLASS__.'.VersionUnknown', 'Unknown');
214
            } else {
215
                $version = $record->Version;
216
            }
217
218
            $versionParts[] = "$label $version";
219
        }
220
221
        return implode(', ', $versionParts);
222
    }
223
224
    /**
225
     * Get the "last updated" date for the report. This is based on the modified date of any of the records, since
226
     * they are regenerated when the report is generated.
227
     *
228
     * @return string
229
     */
230
    public function getLastUpdated()
231
    {
232
        $packages = Package::get()->limit(1);
233
        if (!$packages->count()) {
234
            return '';
235
        }
236
        /** @var DBDatetime $datetime */
237
        $datetime = $packages->first()->dbObject('LastEdited');
238
        return $datetime->Date() . ' ' . $datetime->Time12();
239
    }
240
}
241