Passed
Push — phpstan ( c4fbd2...07dbe1 )
by Sam
08:10
created

GridFieldPrintButton::getPrintHasHeader()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\Forms\GridField;
4
5
use SilverStripe\Control\HTTPRequest;
6
use SilverStripe\Core\Convert;
7
use SilverStripe\Core\Extensible;
8
use SilverStripe\ORM\ArrayList;
9
use SilverStripe\ORM\DataObject;
10
use SilverStripe\ORM\FieldType\DBDatetime;
11
use SilverStripe\ORM\FieldType\DBHTMLText;
12
use SilverStripe\ORM\Limitable;
13
use SilverStripe\Security\Security;
14
use SilverStripe\View\ArrayData;
15
use SilverStripe\View\Requirements;
16
17
/**
18
 * Adds an "Print" button to the bottom or top of a GridField.
19
 */
20
class GridFieldPrintButton implements GridField_HTMLProvider, GridField_ActionProvider, GridField_URLHandler
21
{
22
    use Extensible;
23
24
    /**
25
     * @var array Map of a property name on the printed objects, with values
26
     * being the column title in the CSV file.
27
     *
28
     * Note that titles are only used when {@link $csvHasHeader} is set to TRUE
29
     */
30
    protected $printColumns;
31
32
    /**
33
     * @var boolean
34
     */
35
    protected $printHasHeader = true;
36
37
    /**
38
     * Fragment to write the button to.
39
     *
40
     * @var string
41
     */
42
    protected $targetFragment;
43
44
    /**
45
     * @param string $targetFragment The HTML fragment to write the button into
46
     * @param array $printColumns The columns to include in the print view
47
     */
48
    public function __construct($targetFragment = "after", $printColumns = null)
49
    {
50
        $this->targetFragment = $targetFragment;
51
        $this->printColumns = $printColumns;
52
    }
53
54
    /**
55
     * Place the print button in a <p> tag below the field
56
     *
57
     * @param GridField $gridField
58
     * @return array
59
     */
60
    public function getHTMLFragments($gridField)
61
    {
62
        $button = new GridField_FormAction(
63
            $gridField,
64
            'print',
65
            _t('SilverStripe\\Forms\\GridField\\GridField.Print', 'Print'),
66
            'print',
67
            null
68
        );
69
        $button->setForm($gridField->getForm());
70
71
        $button->addExtraClass('font-icon-print grid-print-button btn btn-secondary');
72
73
        return array(
74
            $this->targetFragment =>  $button->Field(),
75
        );
76
    }
77
78
    /**
79
     * Print is an action button.
80
     *
81
     * @param GridField $gridField
82
     * @return array
83
     */
84
    public function getActions($gridField)
85
    {
86
        return array('print');
87
    }
88
89
    /**
90
     * Handle the print action.
91
     *
92
     * @param GridField $gridField
93
     * @param string $actionName
94
     * @param array $arguments
95
     * @param array $data
96
     * @return DBHTMLText
97
     */
98
    public function handleAction(GridField $gridField, $actionName, $arguments, $data)
99
    {
100
        if ($actionName == 'print') {
101
            return $this->handlePrint($gridField);
102
        }
103
    }
104
105
    /**
106
     * Print is accessible via the url
107
     *
108
     * @param GridField $gridField
109
     * @return array
110
     */
111
    public function getURLHandlers($gridField)
112
    {
113
        return array(
114
            'print' => 'handlePrint',
115
        );
116
    }
117
118
    /**
119
     * Handle the print, for both the action button and the URL
120
     *
121
     * @param GridField $gridField
122
     * @param HTTPRequest $request
123
     * @return DBHTMLText
124
     */
125
    public function handlePrint($gridField, $request = null)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

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

125
    public function handlePrint($gridField, /** @scrutinizer ignore-unused */ $request = null)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
126
    {
127
        set_time_limit(60);
128
        Requirements::clear();
129
130
        $data = $this->generatePrintData($gridField);
131
132
        $this->extend('updatePrintData', $data);
133
134
        if ($data) {
135
            return $data->renderWith([
136
                get_class($gridField) . '_print',
137
                GridField::class . '_print',
138
            ]);
139
        }
140
141
        return null;
142
    }
143
144
    /**
145
     * Return the columns to print
146
     *
147
     * @param GridField $gridField
148
     * @return array
149
     */
150
    protected function getPrintColumnsForGridField(GridField $gridField)
151
    {
152
        if ($this->printColumns) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->printColumns 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...
153
            return $this->printColumns;
154
        }
155
156
        /** @var GridFieldDataColumns $dataCols */
157
        $dataCols = $gridField->getConfig()->getComponentByType('SilverStripe\\Forms\\GridField\\GridFieldDataColumns');
158
        if ($dataCols) {
0 ignored issues
show
introduced by
$dataCols is of type SilverStripe\Forms\GridField\GridFieldDataColumns, thus it always evaluated to true.
Loading history...
159
            return $dataCols->getDisplayFields($gridField);
160
        }
161
162
        return DataObject::singleton($gridField->getModelClass())->summaryFields();
163
    }
164
165
    /**
166
     * Return the title of the printed page
167
     *
168
     * @param GridField $gridField
169
     * @return array
170
     */
171
    public function getTitle(GridField $gridField)
172
    {
173
        $form = $gridField->getForm();
174
        $currentController = $gridField->getForm()->getController();
175
        $title = '';
176
177
        if (method_exists($currentController, 'Title')) {
178
            $title = $currentController->Title();
0 ignored issues
show
Bug introduced by
The method Title() does not exist on SilverStripe\Control\RequestHandler. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

178
            /** @scrutinizer ignore-call */ 
179
            $title = $currentController->Title();
Loading history...
179
        } else {
180
            if (isset($currentController->Title) && $currentController->Title) {
0 ignored issues
show
Bug Best Practice introduced by
The property Title does not exist on SilverStripe\Control\RequestHandler. Since you implemented __get, consider adding a @property annotation.
Loading history...
181
                $title = $currentController->Title;
182
            } elseif ($form->getName()) {
183
                $title = $form->getName();
184
            }
185
        }
186
187
        if ($fieldTitle = $gridField->Title()) {
188
            if ($title) {
189
                $title .= " - ";
190
            }
191
192
            $title .= $fieldTitle;
193
        }
194
195
        return $title;
196
    }
197
198
    /**
199
     * Export core.
200
     *
201
     * @param GridField $gridField
202
     * @return ArrayData
203
     */
204
    public function generatePrintData(GridField $gridField)
205
    {
206
        $printColumns = $this->getPrintColumnsForGridField($gridField);
207
208
        $header = null;
209
210
        if ($this->printHasHeader) {
211
            $header = new ArrayList();
212
213
            foreach ($printColumns as $field => $label) {
214
                $header->push(new ArrayData(array(
215
                    "CellString" => $label,
216
                )));
217
            }
218
        }
219
220
        /** @var Limitable */
221
        $items = $gridField->getManipulatedList();
222
        $itemRows = new ArrayList();
223
224
        /** @var DataObject $item */
225
        foreach ($items->limit(null) as $item) {
0 ignored issues
show
Bug introduced by
The method limit() does not exist on SilverStripe\ORM\SS_List. It seems like you code against a sub-type of said class. However, the method does not exist in SilverStripe\ORM\Sortable or SilverStripe\ORM\Filterable. Are you sure you never get one of those? ( Ignorable by Annotation )

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

225
        foreach ($items->/** @scrutinizer ignore-call */ limit(null) as $item) {
Loading history...
226
            $itemRow = new ArrayList();
227
228
            foreach ($printColumns as $field => $label) {
229
                $value = $gridField->getDataFieldValue($item, $field);
230
231
                $itemRow->push(new ArrayData(array(
232
                    "CellString" => $value,
233
                )));
234
            }
235
236
            $itemRows->push(new ArrayData(array(
237
                "ItemRow" => $itemRow
238
            )));
239
            if ($item->hasMethod('destroy')) {
240
                $item->destroy();
241
            }
242
        }
243
244
        $ret = new ArrayData(array(
245
            "Title" => $this->getTitle($gridField),
246
            "Header" => $header,
247
            "ItemRows" => $itemRows,
248
            "Datetime" => DBDatetime::now(),
249
            "Member" => Security::getCurrentUser(),
250
        ));
251
252
        return $ret;
253
    }
254
255
    /**
256
     * @return array
257
     */
258
    public function getPrintColumns()
259
    {
260
        return $this->printColumns;
261
    }
262
263
    /**
264
     * @param array $cols
265
     * @return $this
266
     */
267
    public function setPrintColumns($cols)
268
    {
269
        $this->printColumns = $cols;
270
271
        return $this;
272
    }
273
274
    /**
275
     * @return boolean
276
     */
277
    public function getPrintHasHeader()
278
    {
279
        return $this->printHasHeader;
280
    }
281
282
    /**
283
     * @param bool $bool
284
     * @return $this
285
     */
286
    public function setPrintHasHeader($bool)
287
    {
288
        $this->printHasHeader = $bool;
289
290
        return $this;
291
    }
292
}
293