ExportableService   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 8

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 7
lcom 0
cbo 8
dl 0
loc 38
ccs 0
cts 25
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B run() 0 22 5
A clearBuffers() 0 6 2
1
<?php
2
3
/*
4
 * This file is part of the 2amigos/yii2-exportable-widget project.
5
 * (c) 2amigOS! <http://2amigos.us/>
6
 * For the full copyright and license information, please view
7
 * the LICENSE file that was distributed with this source code.
8
 */
9
10
namespace dosamigos\exportable\services;
11
12
use dosamigos\exportable\contracts\ExportableServiceInterface;
13
use dosamigos\exportable\factory\WriterFactory;
14
use dosamigos\exportable\helpers\TypeHelper;
15
use dosamigos\exportable\iterators\DataProviderIterator;
16
use dosamigos\exportable\iterators\SourceIterator;
17
use dosamigos\exportable\mappers\ColumnValueMapper;
18
use Yii;
19
use yii\data\BaseDataProvider;
20
use yii\grid\GridView;
21
22
class ExportableService implements ExportableServiceInterface
23
{
24
    /**
25
     * @inheritdoc
26
     */
27
    public function run(GridView $grid, $type, array $columns, $filename)
28
    {
29
        /** @var BaseDataProvider $dataProvider */
30
        $dataProvider = $grid->dataProvider;
31
        $mapper = new ColumnValueMapper($grid->columns, $columns, $type === TypeHelper::HTML);
32
        $source = new SourceIterator(new DataProviderIterator($dataProvider, $mapper));
33
        $model = $dataProvider->getTotalCount() > 0 ? $dataProvider->models[0] : null;
34
        $writer = WriterFactory::create($type);
35
36
        $this->clearBuffers();
37
        ob_start();
38
        $writer->openToBrowser($filename);
39
        if ($model !== null && !in_array($type, [TypeHelper::JSON, TypeHelper::XML])) {
40
            $writer->addRow($mapper->getHeaders($model));
41
        }
42
        foreach ($source as $data) {
43
            $writer->addRow($data);
44
        }
45
        $writer->close();
46
47
        Yii::$app->end();
48
    }
49
50
    /**
51
     * Clean (erase) the output buffers and turns off output buffering
52
     */
53
    protected function clearBuffers()
54
    {
55
        while (ob_get_level() > 0) {
56
            ob_end_clean();
57
        }
58
    }
59
}
60