Completed
Pull Request — 3.5 (#6973)
by Daniel
17:22
created

GridFieldExportButton::generateExportFileData()   D

Complexity

Conditions 22
Paths 60

Size

Total Lines 82
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 22
eloc 44
nc 60
nop 1
dl 0
loc 82
rs 4.9058
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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
/**
4
 * Adds an "Export list" button to the bottom of a {@link GridField}.
5
 *
6
 * @package forms
7
 * @subpackage fields-gridfield
8
 */
9
10
class GridFieldExportButton implements GridField_HTMLProvider, GridField_ActionProvider, GridField_URLHandler {
11
12
	/**
13
	 * @var array Map of a property name on the exported objects, with values being the column title in the CSV file.
14
	 * Note that titles are only used when {@link $csvHasHeader} is set to TRUE.
15
	 */
16
	protected $exportColumns;
17
18
	/**
19
	 * @var string
20
	 */
21
	protected $csvSeparator = ",";
22
23
	/**
24
	 * @var boolean
25
	 */
26
	protected $csvHasHeader = true;
27
28
	/**
29
	 * Fragment to write the button to
30
	 */
31
	protected $targetFragment;
32
33
	/**
34
	 * Set to true to disable XLS sanitisation
35
	 * [SS-2017-007] Ensure all cells with leading [@=+] have a leading tab
36
	 *
37
	 * @config
38
	 * @var bool
39
	 */
40
	private static $xls_export_disabled = false;
41
42
	/**
43
	 * @param string $targetFragment The HTML fragment to write the button into
44
	 * @param array $exportColumns The columns to include in the export
45
	 */
46
	public function __construct($targetFragment = "after", $exportColumns = null) {
47
		$this->targetFragment = $targetFragment;
48
		$this->exportColumns = $exportColumns;
0 ignored issues
show
Documentation Bug introduced by
It seems like $exportColumns can be null. However, the property $exportColumns is declared as array. Maybe change the type of the property to array|null or add a type check?

Our type inference engine has found an assignment of a scalar value (like a string, an integer or null) to a property which is an array.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property.

To type hint that a parameter can be either an array or null, you can set a type hint of array and a default value of null. The PHP interpreter will then accept both an array or null for that parameter.

function aContainsB(array $needle = null, array  $haystack) {
    if (!$needle) {
        return false;
    }

    return array_intersect($haystack, $needle) == $haystack;
}

The function can be called with either null or an array for the parameter $needle but will only accept an array as $haystack.

Loading history...
49
	}
50
51
	/**
52
	 * Place the export button in a <p> tag below the field
53
	 */
54
	public function getHTMLFragments($gridField) {
55
		$button = new GridField_FormAction(
56
			$gridField,
57
			'export',
58
			_t('TableListField.CSVEXPORT', 'Export to CSV'),
59
			'export',
60
			null
61
		);
62
		$button->setAttribute('data-icon', 'download-csv');
63
		$button->addExtraClass('no-ajax action_export');
64
		$button->setForm($gridField->getForm());
65
		return array(
66
			$this->targetFragment => '<p class="grid-csv-button">' . $button->Field() . '</p>',
67
		);
68
	}
69
70
	/**
71
	 * export is an action button
72
	 */
73
	public function getActions($gridField) {
74
		return array('export');
75
	}
76
77
	public function handleAction(GridField $gridField, $actionName, $arguments, $data) {
78
		if($actionName == 'export') {
79
			return $this->handleExport($gridField);
80
		}
81
	}
82
83
	/**
84
	 * it is also a URL
85
	 */
86
	public function getURLHandlers($gridField) {
87
		return array(
88
			'export' => 'handleExport',
89
		);
90
	}
91
92
	/**
93
	 * Handle the export, for both the action button and the URL
94
 	 */
95
	public function handleExport($gridField, $request = null) {
0 ignored issues
show
Unused Code introduced by
The parameter $request 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...
96
		$now = Date("d-m-Y-H-i");
97
		$fileName = "export-$now.csv";
98
99
		if($fileData = $this->generateExportFileData($gridField)){
100
			return SS_HTTPRequest::send_file($fileData, $fileName, 'text/csv');
101
		}
102
	}
103
104
	/**
105
	 * Return the columns to export
106
	 *
107
	 * @param GridField $gridField
108
	 *
109
	 * @return array
110
	 */
111
	protected function getExportColumnsForGridField(GridField $gridField) {
112
		if($this->exportColumns) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->exportColumns 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...
113
			$exportColumns = $this->exportColumns;
114
		} else if($dataCols = $gridField->getConfig()->getComponentByType('GridFieldDataColumns')) {
115
			$exportColumns = $dataCols->getDisplayFields($gridField);
116
		} else {
117
			$exportColumns = singleton($gridField->getModelClass())->summaryFields();
118
		}
119
120
		return $exportColumns;
121
	}
122
123
	/**
124
	 * Generate export fields for CSV.
125
	 *
126
	 * @param GridField $gridField
127
	 * @return string
128
	 */
129
	public function generateExportFileData($gridField) {
130
		$separator = $this->getCsvSeparator();
131
		$csvColumns = $this->getExportColumnsForGridField($gridField);
132
		$fileData = array();
133
134
		if($this->csvHasHeader) {
135
			$headers = array();
136
137
			// determine the CSV headers. If a field is callable (e.g. anonymous function) then use the
138
			// source name as the header instead
139
140
			foreach($csvColumns as $columnSource => $columnHeader) {
141
				if (is_array($columnHeader) && array_key_exists('title', $columnHeader)) {
142
					$headers[] = $columnHeader['title'];
143
				} else {
144
					$headers[] = (!is_string($columnHeader) && is_callable($columnHeader)) ? $columnSource : $columnHeader;
145
				}
146
			}
147
148
			$fileData[] = $headers;
149
		}
150
151
		//Remove GridFieldPaginator as we're going to export the entire list.
152
		$gridField->getConfig()->removeComponentsByType('GridFieldPaginator');
153
154
		$items = $gridField->getManipulatedList();
155
156
		// @todo should GridFieldComponents change behaviour based on whether others are available in the config?
157
		foreach($gridField->getConfig()->getComponents() as $component){
158
			if($component instanceof GridFieldFilterHeader || $component instanceof GridFieldSortableHeader) {
159
				$items = $component->getManipulatedData($gridField, $items);
160
			}
161
		}
162
163
		foreach($items->limit(null) as $item) {
164
			if(!$item->hasMethod('canView') || $item->canView()) {
165
				$columnData = array();
166
167
				foreach($csvColumns as $columnSource => $columnHeader) {
168
					if(!is_string($columnHeader) && is_callable($columnHeader)) {
169
						if($item->hasMethod($columnSource)) {
170
							$relObj = $item->{$columnSource}();
171
						} else {
172
							$relObj = $item->relObject($columnSource);
173
						}
174
175
						$value = $columnHeader($relObj);
176
					} else {
177
						$value = $gridField->getDataFieldValue($item, $columnSource);
178
179
						if($value === null) {
180
							$value = $gridField->getDataFieldValue($item, $columnHeader);
181
						}
182
					}
183
184
					$value = str_replace(array("\r", "\n"), "\n", $value);
185
186
					// [SS-2017-007] Sanitise XLS executable column values with a leading tab
187
					if (!Config::inst()->get(get_class($this), 'xls_export_disabled')
188
						&& preg_match('/^[-@=+].*/', $value)
189
					) {
190
						$value = "\t" . $value;
191
					}
192
					$columnData[] = $value;
193
				}
194
195
				$fileData[] = $columnData;
196
			}
197
198
			if($item->hasMethod('destroy')) {
199
				$item->destroy();
200
			}
201
		}
202
203
		// Convert the $fileData array into csv by capturing fputcsv's output
204
		$csv = fopen('php://temp', 'r+');
205
		foreach($fileData as $line) {
206
			fputcsv($csv, $line, $separator);
207
		}
208
		rewind($csv);
209
		return stream_get_contents($csv);
210
	}
211
212
	/**
213
	 * @return array
214
	 */
215
	public function getExportColumns() {
216
		return $this->exportColumns;
217
	}
218
219
	/**
220
	 * @param array
221
	 */
222
	public function setExportColumns($cols) {
223
		$this->exportColumns = $cols;
224
		return $this;
225
	}
226
227
	/**
228
	 * @return string
229
	 */
230
	public function getCsvSeparator() {
231
		return $this->csvSeparator;
232
	}
233
234
	/**
235
	 * @param string
236
	 */
237
	public function setCsvSeparator($separator) {
238
		$this->csvSeparator = $separator;
239
		return $this;
240
	}
241
242
	/**
243
	 * @return boolean
244
	 */
245
	public function getCsvHasHeader() {
246
		return $this->csvHasHeader;
247
	}
248
249
	/**
250
	 * @param boolean
251
	 */
252
	public function setCsvHasHeader($bool) {
253
		$this->csvHasHeader = $bool;
254
		return $this;
255
	}
256
257
258
}
259