Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Export.php
Go to the documentation of this file.
1 <?php
8 
10 
17 class Export extends \Magento\Backend\Block\Widget implements \Magento\Backend\Block\Widget\Grid\ExportInterface
18 {
24  protected $_exportTypes = [];
25 
31  protected $_exportPageSize = 1000;
32 
38  protected $_template = "Magento_Backend::widget/grid/export.phtml";
39 
44 
48  protected $_directory;
49 
55  protected $_path = 'export';
56 
62  public function __construct(
63  \Magento\Backend\Block\Template\Context $context,
64  \Magento\Framework\Data\CollectionFactory $collectionFactory,
65  array $data = []
66  ) {
67  $this->_collectionFactory = $collectionFactory;
68  parent::__construct($context, $data);
69  }
70 
75  protected function _construct()
76  {
77  parent::_construct();
78  if ($this->hasData('exportTypes')) {
79  foreach ($this->getData('exportTypes') as $type) {
80  if (!isset($type['urlPath']) || !isset($type['label'])) {
81  throw new \Magento\Framework\Exception\LocalizedException(
82  __('Invalid export type supplied for grid export block')
83  );
84  }
85  $this->addExportType($type['urlPath'], $type['label']);
86  }
87  }
88  $this->_directory = $this->_filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
89  }
90 
96  protected function _getColumns()
97  {
98  return $this->getParentBlock()->getColumns();
99  }
100 
106  protected function _getTotals()
107  {
108  return $this->getParentBlock()->getColumnSet()->getTotals();
109  }
110 
117  public function getCountTotals()
118  {
119  return $this->getParentBlock()->getColumnSet()->shouldRenderTotal();
120  }
121 
127  protected function _getCollection()
128  {
129  return $this->getParentBlock()->getCollection();
130  }
131 
137  public function getExportTypes()
138  {
139  return empty($this->_exportTypes) ? false : $this->_exportTypes;
140  }
141 
147  public function getId()
148  {
149  return $this->getParentBlock()->getId();
150  }
151 
157  protected function _prepareLayout()
158  {
159  $this->setChild(
160  'export_button',
161  $this->getLayout()->createBlock(
162  \Magento\Backend\Block\Widget\Button::class
163  )->setData(
164  [
165  'label' => __('Export'),
166  'onclick' => $this->getParentBlock()->getJsObjectName() . '.doExport()',
167  'class' => 'task',
168  ]
169  )
170  );
171  return parent::_prepareLayout();
172  }
173 
179  public function getExportButtonHtml()
180  {
181  return $this->getChildHtml('export_button');
182  }
183 
191  public function addExportType($url, $label)
192  {
193  $this->_exportTypes[] = new \Magento\Framework\DataObject(
194  ['url' => $this->getUrl($url, ['_current' => true]), 'label' => $label]
195  );
196  return $this;
197  }
198 
205  protected function _getFileContainerContent(array $fileData)
206  {
207  return $this->_directory->readFile('export/' . $fileData['value']);
208  }
209 
215  protected function _getExportHeaders()
216  {
217  $row = [];
218  foreach ($this->_getColumns() as $column) {
219  if (!$column->getIsSystem()) {
220  $row[] = $column->getExportHeader();
221  }
222  }
223  return $row;
224  }
225 
231  protected function _getExportTotals()
232  {
233  $totals = $this->_getTotals();
234  $row = [];
235  foreach ($this->_getColumns() as $column) {
236  if (!$column->getIsSystem()) {
237  $row[] = $column->hasTotalsLabel() ? $column->getTotalsLabel() : $column->getRowFieldExport($totals);
238  }
239  }
240  return $row;
241  }
242 
251  public function _exportIterateCollection($callback, array $args)
252  {
254  $originalCollection = $this->getParentBlock()->getPreparedCollection();
255  $count = null;
256  $page = 1;
257  $lPage = null;
258  $break = false;
259 
260  while ($break !== true) {
261  $originalCollection->clear();
262  $originalCollection->setPageSize($this->getExportPageSize());
263  $originalCollection->setCurPage($page);
264  $originalCollection->load();
265  if ($count === null) {
266  $count = $originalCollection->getSize();
267  $lPage = $originalCollection->getLastPageNumber();
268  }
269  if ($lPage == $page) {
270  $break = true;
271  }
272  $page++;
273 
274  $collection = $this->_getRowCollection($originalCollection);
275  foreach ($collection as $item) {
276  call_user_func_array([$this, $callback], array_merge([$item], $args));
277  }
278  }
279  }
280 
288  protected function _exportCsvItem(
289  \Magento\Framework\DataObject $item,
290  \Magento\Framework\Filesystem\File\WriteInterface $stream
291  ) {
292  $row = [];
293  foreach ($this->_getColumns() as $column) {
294  if (!$column->getIsSystem()) {
295  $row[] = $column->getRowFieldExport($item);
296  }
297  }
298  $stream->writeCsv($row);
299  }
300 
308  public function getCsvFile()
309  {
310  $name = md5(microtime());
311  $file = $this->_path . '/' . $name . '.csv';
312 
313  $this->_directory->create($this->_path);
314  $stream = $this->_directory->openFile($file, 'w+');
315 
316  $stream->writeCsv($this->_getExportHeaders());
317  $stream->lock();
318  $this->_exportIterateCollection('_exportCsvItem', [$stream]);
319  if ($this->getCountTotals()) {
320  $stream->writeCsv($this->_getExportTotals());
321  }
322  $stream->unlock();
323  $stream->close();
324 
325  return [
326  'type' => 'filename',
327  'value' => $file,
328  'rm' => true // can delete file after use
329  ];
330  }
331 
337  public function getCsv()
338  {
339  $csv = '';
340  $collection = $this->_getPreparedCollection();
341 
342  $data = [];
343  foreach ($this->_getColumns() as $column) {
344  if (!$column->getIsSystem()) {
345  $data[] = '"' . $column->getExportHeader() . '"';
346  }
347  }
348  $csv .= implode(',', $data) . "\n";
349 
350  foreach ($collection as $item) {
351  $data = [];
352  foreach ($this->_getColumns() as $column) {
353  if (!$column->getIsSystem()) {
354  $data[] = '"' . str_replace(
355  ['"', '\\'],
356  ['""', '\\\\'],
357  $column->getRowFieldExport($item)
358  ) . '"';
359  }
360  }
361  $csv .= implode(',', $data) . "\n";
362  }
363 
364  if ($this->getCountTotals()) {
365  $data = [];
366  foreach ($this->_getColumns() as $column) {
367  if (!$column->getIsSystem()) {
368  $data[] = '"' . str_replace(
369  ['"', '\\'],
370  ['""', '\\\\'],
371  $column->getRowFieldExport($this->_getTotals())
372  ) . '"';
373  }
374  }
375  $csv .= implode(',', $data) . "\n";
376  }
377 
378  return $csv;
379  }
380 
386  public function getXml()
387  {
388  $collection = $this->_getPreparedCollection();
389 
390  $indexes = [];
391  foreach ($this->_getColumns() as $column) {
392  if (!$column->getIsSystem()) {
393  $indexes[] = $column->getIndex();
394  }
395  }
396  $xml = '<?xml version="1.0" encoding="UTF-8"?>';
397  $xml .= '<items>';
398  foreach ($collection as $item) {
399  $xml .= $item->toXml($indexes);
400  }
401  if ($this->getCountTotals()) {
402  $xml .= $this->_getTotals()->toXml($indexes);
403  }
404  $xml .= '</items>';
405  return $xml;
406  }
407 
414  public function getRowRecord(\Magento\Framework\DataObject $data)
415  {
416  $row = [];
417  foreach ($this->_getColumns() as $column) {
418  if (!$column->getIsSystem()) {
419  $row[] = $column->getRowFieldExport($data);
420  }
421  }
422  return $row;
423  }
424 
433  public function getExcelFile($sheetName = '')
434  {
435  $collection = $this->_getRowCollection();
436 
437  $convert = new \Magento\Framework\Convert\Excel($collection->getIterator(), [$this, 'getRowRecord']);
438 
439  $name = md5(microtime());
440  $file = $this->_path . '/' . $name . '.xml';
441 
442  $this->_directory->create($this->_path);
443  $stream = $this->_directory->openFile($file, 'w+');
444  $stream->lock();
445 
446  $convert->setDataHeader($this->_getExportHeaders());
447  if ($this->getCountTotals()) {
448  $convert->setDataFooter($this->_getExportTotals());
449  }
450 
451  $convert->write($stream, $sheetName);
452  $stream->unlock();
453  $stream->close();
454 
455  return [
456  'type' => 'filename',
457  'value' => $file,
458  'rm' => true // can delete file after use
459  ];
460  }
461 
467  public function getExcel()
468  {
469  $collection = $this->_getPreparedCollection();
470 
471  $headers = [];
472  $data = [];
473  foreach ($this->_getColumns() as $column) {
474  if (!$column->getIsSystem()) {
475  $headers[] = $column->getHeader();
476  }
477  }
478  $data[] = $headers;
479 
480  foreach ($collection as $item) {
481  $row = [];
482  foreach ($this->_getColumns() as $column) {
483  if (!$column->getIsSystem()) {
484  $row[] = $column->getRowField($item);
485  }
486  }
487  $data[] = $row;
488  }
489 
490  if ($this->getCountTotals()) {
491  $row = [];
492  foreach ($this->_getColumns() as $column) {
493  if (!$column->getIsSystem()) {
494  $row[] = $column->getRowField($this->_getTotals());
495  }
496  }
497  $data[] = $row;
498  }
499 
500  $convert = new \Magento\Framework\Convert\Excel(new \ArrayIterator($data));
501  return $convert->convert('single_sheet');
502  }
503 
510  protected function _getRowCollection(\Magento\Framework\Data\Collection $baseCollection = null)
511  {
512  if (null === $baseCollection) {
513  $baseCollection = $this->getParentBlock()->getPreparedCollection();
514  }
515  $collection = $this->_collectionFactory->create();
516 
518  foreach ($baseCollection as $item) {
519  if ($item->getIsEmpty()) {
520  continue;
521  }
522  if ($item->hasChildren() && count($item->getChildren()) > 0) {
524  foreach ($item->getChildren() as $subItem) {
525  $tmpItem = clone $item;
526  $tmpItem->unsChildren();
527  $tmpItem->addData($subItem->getData());
528  $collection->addItem($tmpItem);
529  }
530  } else {
531  $collection->addItem($item);
532  }
533  }
534 
535  return $collection;
536  }
537 
543  public function _getPreparedCollection()
544  {
546  $collection = $this->getParentBlock()->getPreparedCollection();
547  $collection->setPageSize(0);
548  $collection->load();
549 
550  return $this->_getRowCollection($collection);
551  }
552 
556  public function getExportPageSize()
557  {
558  return $this->_exportPageSize;
559  }
560 }
getData($key='', $index=null)
Definition: DataObject.php:119
return false
Definition: gallery.phtml:36
$count
Definition: recent.phtml:13
__()
Definition: __.php:13
$type
Definition: item.phtml:13
_getFileContainerContent(array $fileData)
Definition: Export.php:205
getRowRecord(\Magento\Framework\DataObject $data)
Definition: Export.php:414
$label
Definition: details.phtml:21
$totals
Definition: totalbar.phtml:10
$page
Definition: pages.php:8
_exportCsvItem(\Magento\Framework\DataObject $item, \Magento\Framework\Filesystem\File\WriteInterface $stream)
Definition: Export.php:288
__construct(\Magento\Backend\Block\Template\Context $context, \Magento\Framework\Data\CollectionFactory $collectionFactory, array $data=[])
Definition: Export.php:62
setData($key, $value=null)
Definition: DataObject.php:72
if(!isset($_GET['name'])) $name
Definition: log.php:14