Completed
Pull Request — master (#201)
by
unknown
02:10
created

ExcelDispatchJobService::initialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Nayjest\Grids\Components;
4
5
use Event;
6
use Illuminate\Pagination\Paginator;
7
use Illuminate\Foundation\Application;
8
use Maatwebsite\Excel\Classes\LaravelExcelWorksheet;
9
use Maatwebsite\Excel\Excel;
10
use Maatwebsite\Excel\Writers\LaravelExcelWriter;
11
use Nayjest\Grids\Components\Base\RenderableComponent;
12
use Nayjest\Grids\Components\Base\RenderableRegistry;
13
use Nayjest\Grids\DataProvider;
14
use Nayjest\Grids\DataRow;
15
use Nayjest\Grids\FieldConfig;
16
use Nayjest\Grids\Grid;
17
use Illuminate\Support\Facades\Storage;
18
19
20
/**
21
 * Class ExcelExport
22
 *
23
 * The component provides control for exporting data to excel.
24
 *
25
 * @author: Alexander Hofmeister
26
 * @package Nayjest\Grids\Components
27
 */
28
class ExcelDispatchJobService extends RenderableComponent
29
{
30
    const NAME = 'excel_export';
31
    const INPUT_PARAM = 'xlsx';
32
    const DEFAULT_ROWS_LIMIT = 50000;
33
34
    protected $template = '*.components.excel_export';
35
    protected $name = ExcelDispatchJobService::NAME;
36
    protected $render_section = RenderableRegistry::SECTION_END;
37
    protected $rows_limit = self::DEFAULT_ROWS_LIMIT;
38
    protected $extension = 'xlsx';
39
40
    /**
41
     * @var string
42
     */
43
    protected $output;
44
45
    protected $data;
46
47
    protected $config;
48
49
    /**
50
     * @var string
51
     */
52
    protected $fileName;
53
54
    /**
55
     * @var string
56
     */
57
    protected $sheetName;
58
59
    protected $ignored_columns = [];
60
61
    protected $is_hidden_columns_exported = false;
62
63
    protected $on_file_create;
64
65
    protected $on_sheet_create;
66
67
    /**
68
     * @return mixed
69
     */
70
    public function getConfig()
71
    {
72
        return $this->config;
73
    }
74
75
    /**
76
     * @param mixed $config
77
     */
78
    public function setConfig($config)
79
    {
80
        $this->config = $config;
81
        return $this;
82
    }
83
84
    public function __construct()
85
    {
86
        $this->renderExcel();
87
    }
88
89
    /**
90
     * @param Grid $grid
91
     * @return null|void
92
     */
93
    public function initialize(Grid $grid)
94
    {
95
        $this->renderExcel();
96
    }
97
98
    /**
99
     * Sets name of exported file.
100
     *
101
     * @param string $name
102
     * @return $this
103
     */
104
    public function setFileName($name)
105
    {
106
        $this->fileName = $name;
107
        return $this;
108
    }
109
110
    /**
111
     * Returns name of exported file.
112
     *
113
     * @return string
114
     */
115
    public function getFileName()
116
    {
117
        return $this->fileName ?: $this->getConfig()->getName();
118
    }
119
120
    /**
121
     * @param string $name
122
     * @return $this
123
     */
124
    public function setSheetName($name)
125
    {
126
        $this->sheetName = $name;
127
        return $this;
128
    }
129
130
    /**
131
     * @return string
132
     */
133
    public function getSheetName()
134
    {
135
        return $this->sheetName;
136
    }
137
138
    /**
139
     * @param string $name
140
     * @return $this
141
     */
142
    public function setExtension($name)
143
    {
144
        $this->extension = $name;
145
        return $this;
146
    }
147
148
    /**
149
     * @return string
150
     */
151
    public function getExtension()
152
    {
153
        return $this->extension;
154
    }
155
156
    /**
157
     * @return int
158
     */
159
    public function getRowsLimit()
160
    {
161
        return $this->rows_limit;
162
    }
163
164
    /**
165
     * @param int $limit
166
     *
167
     * @return $this
168
     */
169
    public function setRowsLimit($limit = 50000)
170
    {
171
        $this->rows_limit = $limit;
172
        return $this;
173
    }
174
175 View Code Duplication
    protected function resetPagination(DataProvider $provider)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
176
    {
177
        if (version_compare(Application::VERSION, '5.0.0', '<')) {
178
            $provider->getPaginationFactory()->setPageName('page_unused');
179
        } else {
180
            Paginator::currentPageResolver(function () {
181
                return 1;
182
            });
183
        }
184
        $provider->setPageSize($this->getRowsLimit());
185
        $provider->setCurrentPage(1);
186
    }
187
188
    /**
189
     * @param FieldConfig $column
190
     * @return bool
191
     */
192
    protected function isColumnExported(FieldConfig $column)
193
    {
194
        return !in_array($column->getName(), $this->getIgnoredColumns())
195
            && ($this->isHiddenColumnsExported() || !$column->isHidden());
196
    }
197
198
    /**
199
     * @internal
200
     * @return array
201
     */
202
    public function getData()
203
    {
204
        // Build array
205
        $exportData = [];
206
        /** @var $provider DataProvider */
207
        $provider = $this->getConfig()->getDataProvider();
208
209
        $exportData[] = $this->getHeaderRow();
210
211
        $this->resetPagination($provider);
212
        $provider->reset();
213
214
        /** @var DataRow $row */
215
        while ($row = $provider->getRow()) {
216
            $output = [];
217 View Code Duplication
            foreach ($this->getConfig()->getColumns() as $column) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
218
                if ($this->isColumnExported($column)) {
219
                    $output[] = $this->escapeString($column->getValue($row));
220
                }
221
            }
222
            $exportData[] = $output;
223
        }
224
        return $exportData;
225
    }
226
227
    protected function renderExcel()
228
    {
229
        /** @var Excel $excel */
230
        $excel = app('excel');
231
        $excel
232
            ->create($this->getFileName(), $this->getOnFileCreate())
233
            ->save('xlsx',Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix() . 'public/excels/');
0 ignored issues
show
Bug introduced by
The method getDriver() does not seem to exist on object<Illuminate\Contra...\Filesystem\Filesystem>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
234
    }
235
236
    protected function escapeString($str)
237
    {
238
        return str_replace('"', '\'', strip_tags(html_entity_decode($str)));
239
    }
240
241
    protected function getHeaderRow()
242
    {
243
        $output = [];
244 View Code Duplication
        foreach ($this->getConfig()->getColumns() as $column) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
245
            if ($this->isColumnExported($column)) {
246
                $output[] = $this->escapeString($column->getLabel());
247
            }
248
        }
249
        return $output;
250
    }
251
252
    /**
253
     * @return string[]
254
     */
255
    public function getIgnoredColumns()
256
    {
257
        return $this->ignored_columns;
258
    }
259
260
    /**
261
     * @param string[] $ignoredColumns
262
     * @return $this
263
     */
264
    public function setIgnoredColumns(array $ignoredColumns)
265
    {
266
        $this->ignored_columns = $ignoredColumns;
267
        return $this;
268
    }
269
270
    /**
271
     * @return boolean
272
     */
273
    public function isHiddenColumnsExported()
274
    {
275
        return $this->is_hidden_columns_exported;
276
    }
277
278
    /**
279
     * @param bool $isHiddenColumnsExported
280
     * @return $this
281
     */
282
    public function setHiddenColumnsExported($isHiddenColumnsExported)
283
    {
284
        $this->is_hidden_columns_exported = $isHiddenColumnsExported;
285
        return $this;
286
    }
287
288
    /**
289
     * @return mixed
290
     */
291
    public function getOnFileCreate()
292
    {
293
        if ($this->on_file_create === null) {
294
            $this->on_file_create = function (LaravelExcelWriter $excel) {
295
                $excel->sheet($this->getSheetName(), $this->getOnSheetCreate());
296
297
            };
298
        }
299
        return $this->on_file_create;
300
    }
301
302
    /**
303
     * @param callable $onFileCreate
304
     *
305
     * @return $this
306
     */
307
    public function setOnFileCreate($onFileCreate)
308
    {
309
        $this->on_file_create = $onFileCreate;
310
        return $this;
311
    }
312
313
    /**
314
     * @return callable
315
     */
316
    public function getOnSheetCreate()
317
    {
318
        if ($this->on_sheet_create === null) {
319
            $this->on_sheet_create = function (LaravelExcelWorksheet $sheet) {
320
//                for($i = 0; $i < count($data); $i++) {
321
//                    for ($j = 0; $j < count($data[$i]); $j++) {
322
//                        $sheet->appendRow(($i * 1000) + $j + 1, $data[$i][$j]);
323
//                    }
324
                //$sheet->fromArray($data, null, 'A1', false, false);
325
//                $data = $this->getData();
326
//                $data->chunk(100, function($rows) use ($sheet)
327
//                {
328
329
                $sheet->fromArray($this->getData(), null, 'A1', false, false);
330
//                });
331
            };
332
        }
333
334
        return $this->on_sheet_create;
335
    }
336
337
    /**
338
     * @param callable $onSheetCreate
339
     *
340
     * @return $this
341
     */
342
    public function setOnSheetCreate($onSheetCreate)
343
    {
344
        $this->on_sheet_create = $onSheetCreate;
345
        return $this;
346
    }
347
}