Completed
Push — master ( 155d74...73c1de )
by Vitaliy
8s
created

ExcelExport   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 291
Duplicated Lines 11.68 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 9
Bugs 3 Features 1
Metric Value
wmc 36
c 9
b 3
f 1
lcom 1
cbo 6
dl 34
loc 291
rs 8.8

23 Methods

Rating   Name   Duplication   Size   Complexity  
A initialize() 12 12 3
A setFileName() 0 5 1
A getFileName() 0 4 2
A setSheetName() 0 5 1
A getSheetName() 0 4 1
A setExtension() 0 5 1
A getExtension() 0 4 1
A getRowsLimit() 0 4 1
A setRowsLimit() 0 5 1
A resetPagination() 12 12 2
A isColumnExported() 0 5 3
B getData() 5 25 4
A renderExcel() 0 8 1
A escapeString() 0 4 1
A getHeaderRow() 5 10 3
A getIgnoredColumns() 0 4 1
A setIgnoredColumns() 0 5 1
A isHiddenColumnsExported() 0 4 1
A setHiddenColumnsExported() 0 5 1
A getOnFileCreate() 0 9 2
A setOnFileCreate() 0 5 1
A getOnSheetCreate() 0 9 2
A setOnSheetCreate() 0 5 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Nayjest\Grids\Components;
4
5
use Event;
6
use 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
18
/**
19
 * Class ExcelExport
20
 *
21
 * The component provides control for exporting data to excel.
22
 *
23
 * @author: Alexander Hofmeister
24
 * @package Nayjest\Grids\Components
25
 */
26
class ExcelExport extends RenderableComponent
27
{
28
    const NAME = 'excel_export';
29
    const INPUT_PARAM = 'xls';
30
    const DEFAULT_ROWS_LIMIT = 5000;
31
32
    protected $template = '*.components.excel_export';
33
    protected $name = ExcelExport::NAME;
34
    protected $render_section = RenderableRegistry::SECTION_END;
35
    protected $rows_limit = self::DEFAULT_ROWS_LIMIT;
36
    protected $extension = 'xls';
37
38
    /**
39
     * @var string
40
     */
41
    protected $output;
42
43
    /**
44
     * @var string
45
     */
46
    protected $fileName;
47
48
    /**
49
     * @var string
50
     */
51
    protected $sheetName;
52
53
    protected $ignored_columns = [];
54
55
    protected $is_hidden_columns_exported = false;
56
57
    protected $on_file_create;
58
59
    protected $on_sheet_create;
60
61
    /**
62
     * @param Grid $grid
63
     * @return null|void
64
     */
65 View Code Duplication
    public function initialize(Grid $grid)
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...
66
    {
67
        parent::initialize($grid);
68
        Event::listen(Grid::EVENT_PREPARE, function (Grid $grid) {
69
            if ($this->grid !== $grid) {
70
                return;
71
            }
72
            if ($grid->getInputProcessor()->getValue(static::INPUT_PARAM, false)) {
73
                $this->renderExcel();
74
            }
75
        });
76
    }
77
78
    /**
79
     * Sets name of exported file.
80
     * 
81
     * @param string $name
82
     * @return $this
83
     */
84
    public function setFileName($name)
85
    {
86
        $this->fileName = $name;
87
        return $this;
88
    }
89
90
    /**
91
     * Returns name of exported file.
92
     * 
93
     * @return string
94
     */
95
    public function getFileName()
96
    {
97
        return $this->fileName ?: $this->grid->getConfig()->getName();
98
    }
99
100
    /**
101
     * @param string $name
102
     * @return $this
103
     */
104
    public function setSheetName($name)
105
    {
106
        $this->sheetName = $name;
107
        return $this;
108
    }
109
110
    /**
111
     * @return string
112
     */
113
    public function getSheetName()
114
    {
115
        return $this->sheetName;
116
    }
117
118
    /**
119
     * @param string $name
120
     * @return $this
121
     */
122
    public function setExtension($name)
123
    {
124
        $this->extension = $name;
125
        return $this;
126
    }
127
128
    /**
129
     * @return string
130
     */
131
    public function getExtension()
132
    {
133
        return $this->extension;
134
    }
135
136
    /**
137
     * @return int
138
     */
139
    public function getRowsLimit()
140
    {
141
        return $this->rows_limit;
142
    }
143
144
    /**
145
     * @param int $limit
146
     *
147
     * @return $this
148
     */
149
    public function setRowsLimit($limit)
150
    {
151
        $this->rows_limit = $limit;
152
        return $this;
153
    }
154
155 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...
156
    {
157
        if (version_compare(Application::VERSION, '5.0.0', '<')) {
158
            $provider->getPaginationFactory()->setPageName('page_unused');
159
        } else {
160
            Paginator::currentPageResolver(function () {
161
                return 1;
162
            });
163
        }
164
        $provider->setPageSize($this->getRowsLimit());
165
        $provider->setCurrentPage(1);
166
    }
167
168
    /**
169
     * @param FieldConfig $column
170
     * @return bool
171
     */
172
    protected function isColumnExported(FieldConfig $column)
173
    {
174
        return !in_array($column->getName(), $this->getIgnoredColumns())
175
            && ($this->isHiddenColumnsExported() || !$column->isHidden());
176
    }
177
178
    /**
179
     * @internal
180
     * @return array
181
     */
182
    public function getData()
183
    {
184
        // Build array
185
        $exportData = [];
186
        /** @var $provider DataProvider */
187
        $provider = $this->grid->getConfig()->getDataProvider();
188
189
        $exportData[] = $this->getHeaderRow();
190
191
        $this->resetPagination($provider);
192
        $provider->reset();
193
194
        /** @var DataRow $row */
195
        while ($row = $provider->getRow()) {
196
            $output = [];
197 View Code Duplication
            foreach ($this->grid->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...
198
                if ($this->isColumnExported($column)) {
199
                    $output[] = $this->escapeString($column->getValue($row));
200
                }
201
            }
202
            $exportData[] = $output;
203
        }
204
205
        return $exportData;
206
    }
207
208
    protected function renderExcel()
209
    {
210
        /** @var Excel $excel */
211
        $excel = app('excel');
212
        $excel
213
            ->create($this->getFileName(), $this->getOnFileCreate())
214
            ->export($this->getExtension());
215
    }
216
217
    protected function escapeString($str)
218
    {
219
        return str_replace('"', '\'', strip_tags(html_entity_decode($str)));
220
    }
221
222
    protected function getHeaderRow()
223
    {
224
        $output = [];
225 View Code Duplication
        foreach ($this->grid->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...
226
            if ($this->isColumnExported($column)) {
227
                $output[] = $this->escapeString($column->getLabel());
228
            }
229
        }
230
        return $output;
231
    }
232
233
    /**
234
     * @return string[]
235
     */
236
    public function getIgnoredColumns()
237
    {
238
        return $this->ignored_columns;
239
    }
240
241
    /**
242
     * @param string[] $ignoredColumns
243
     * @return $this
244
     */
245
    public function setIgnoredColumns(array $ignoredColumns)
246
    {
247
        $this->ignored_columns = $ignoredColumns;
248
        return $this;
249
    }
250
251
    /**
252
     * @return boolean
253
     */
254
    public function isHiddenColumnsExported()
255
    {
256
        return $this->is_hidden_columns_exported;
257
    }
258
259
    /**
260
     * @param bool $isHiddenColumnsExported
261
     * @return $this
262
     */
263
    public function setHiddenColumnsExported($isHiddenColumnsExported)
264
    {
265
        $this->is_hidden_columns_exported = $isHiddenColumnsExported;
266
        return $this;
267
    }
268
269
    /**
270
     * @return mixed
271
     */
272
    public function getOnFileCreate()
273
    {
274
        if ($this->on_file_create === null) {
275
            $this->on_file_create = function (LaravelExcelWriter $excel) {
276
                $excel->sheet($this->getSheetName(), $this->getOnSheetCreate());
277
            };
278
        }
279
        return $this->on_file_create;
280
    }
281
282
    /**
283
     * @param callable $onFileCreate
284
     *
285
     * @return $this
286
     */
287
    public function setOnFileCreate($onFileCreate)
288
    {
289
        $this->on_file_create = $onFileCreate;
290
        return $this;
291
    }
292
293
    /**
294
     * @return callable
295
     */
296
    public function getOnSheetCreate()
297
    {
298
        if ($this->on_sheet_create === null) {
299
            $this->on_sheet_create = function (LaravelExcelWorksheet $sheet) {
300
                $sheet->fromArray($this->getData(), null, 'A1', false, false);
301
            };
302
        }
303
        return $this->on_sheet_create;
304
    }
305
306
    /**
307
     * @param callable $onSheetCreate
308
     *
309
     * @return $this
310
     */
311
    public function setOnSheetCreate($onSheetCreate)
312
    {
313
        $this->on_sheet_create = $onSheetCreate;
314
        return $this;
315
    }
316
}
317