GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Test Failed
Push — master ( c38bf5...417d52 )
by Mewes
03:09
created

DocumentWrapper   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 212
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 89.06%

Importance

Changes 0
Metric Value
wmc 25
lcom 1
cbo 11
dl 0
loc 212
ccs 57
cts 64
cp 0.8906
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A start() 0 19 2
C end() 0 70 12
A getObject() 0 4 1
A setObject() 0 4 1
A configureMappings() 0 26 1
B expandPath() 0 22 7
1
<?php
2
3
namespace MewesK\TwigSpreadsheetBundle\Wrapper;
4
5
use MewesK\TwigSpreadsheetBundle\Helper\Filesystem;
6
use PhpOffice\PhpSpreadsheet\Exception;
7
use PhpOffice\PhpSpreadsheet\IOFactory;
8
use PhpOffice\PhpSpreadsheet\Spreadsheet;
9
use PhpOffice\PhpSpreadsheet\Writer\BaseWriter;
10
use PhpOffice\PhpSpreadsheet\Writer\Csv;
11
use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf;
12
use Symfony\Bridge\Twig\AppVariable;
13
14
/**
15
 * Class DocumentWrapper.
16
 */
17
class DocumentWrapper extends BaseWrapper
18
{
19
    /**
20
     * @var Spreadsheet|null
21
     */
22
    protected $object;
23
    /**
24
     * @var array
25
     */
26
    protected $attributes;
27
28
    /**
29
     * DocumentWrapper constructor.
30
     *
31
     * @param array             $context
32
     * @param \Twig_Environment $environment
33
     * @param array             $attributes
34
     */
35 118
    public function __construct(array $context, \Twig_Environment $environment, array $attributes = [])
36
    {
37 118
        parent::__construct($context, $environment);
38
39 118
        $this->object = null;
40 118
        $this->attributes = $attributes;
41 118
    }
42
43
    /**
44
     * @param array $properties
45
     *
46
     * @throws \RuntimeException
47
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
48
     * @throws \PhpOffice\PhpSpreadsheet\Exception
49
     */
50 118
    public function start(array $properties = [])
51
    {
52
        // load template
53 118
        if (isset($properties['template'])) {
54 17
            $templatePath = $this->expandPath($properties['template']);
55 17
            $reader = IOFactory::createReaderForFile($templatePath);
56 17
            $this->object = $reader->load($templatePath);
57
        }
58
59
        // create new
60
        else {
61 101
            $this->object = new Spreadsheet();
62 101
            $this->object->removeSheetByIndex(0);
63
        }
64
65 118
        $this->parameters['properties'] = $properties;
66
67 118
        $this->setProperties($properties);
68 118
    }
69
70
    /**
71
     * @throws \LogicException
72
     * @throws \RuntimeException
73
     * @throws \InvalidArgumentException
74
     * @throws \PhpOffice\PhpSpreadsheet\Exception
75
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
76
     * @throws \Symfony\Component\Filesystem\Exception\IOException
77
     */
78 110
    public function end()
79
    {
80 110
        if ($this->object === null) {
81
            throw new \LogicException();
82
        }
83
84 110
        $format = null;
85
86
        // try document property
87 110
        if (isset($this->parameters['format'])) {
88
            $format = $this->parameters['format'];
89
        }
90
91
         // try Symfony request
92 110
        elseif (isset($this->context['app'])) {
93
            /**
94
             * @var AppVariable
95
             */
96 110
            $appVariable = $this->context['app'];
97 110
            if ($appVariable instanceof AppVariable && $appVariable->getRequest() !== null) {
98 110
                $format = $appVariable->getRequest()->getRequestFormat();
99
            }
100
        }
101
102
        // set default
103 110
        if ($format === null || !\is_string($format)) {
104
            $format = 'xlsx';
105
        } else {
106 110
            $format = strtolower($format);
107
        }
108
109
        // set up mPDF
110 110
        if ($format === 'pdf') {
111 1
            if (!class_exists('\Mpdf\Mpdf')) {
112
                throw new \RuntimeException('Error loading mPDF. Is mPDF correctly installed?');
113
            }
114 1
            IOFactory::registerWriter('Pdf', Mpdf::class);
115
        }
116
117
        /**
118
         * @var BaseWriter $writer
119
         */
120 110
        $writer = IOFactory::createWriter($this->object, ucfirst($format));
121 110
        $writer->setPreCalculateFormulas($this->attributes['preCalculateFormulas'] ?? true);
122
123
        // set up XML cache
124 110
        if ($this->attributes['cache']['xml'] !== false) {
125 25
            Filesystem::mkdir($this->attributes['cache']['xml']);
126 25
            $writer->setUseDiskCaching(true, $this->attributes['cache']['xml']);
127
        }
128
129
        // set special CSV writer attributes
130 110
        if ($writer instanceof Csv) {
131
            /**
132
             * @var Csv $writer
133
             */
134 3
            $writer->setDelimiter($this->attributes['csv_writer']['delimiter']);
135 3
            $writer->setEnclosure($this->attributes['csv_writer']['enclosure']);
136 3
            $writer->setExcelCompatibility($this->attributes['csv_writer']['excel_compatibility']);
137 3
            $writer->setIncludeSeparatorLine($this->attributes['csv_writer']['include_separator_line']);
138 3
            $writer->setLineEnding($this->attributes['csv_writer']['line_ending']);
139 3
            $writer->setSheetIndex($this->attributes['csv_writer']['sheet_index']);
140 3
            $writer->setUseBOM($this->attributes['csv_writer']['use_bom']);
141
        }
142
143 110
        $writer->save('php://output');
144
145 110
        $this->object = null;
146 110
        $this->parameters = [];
147 110
    }
148
149
    /**
150
     * @return Spreadsheet|null
151
     */
152 106
    public function getObject()
153
    {
154 106
        return $this->object;
155
    }
156
157
    /**
158
     * @param Spreadsheet|null $object
159
     */
160
    public function setObject(Spreadsheet $object = null)
161
    {
162
        $this->object = $object;
163
    }
164
165
    /**
166
     * {@inheritdoc}
167
     *
168
     * @throws \PhpOffice\PhpSpreadsheet\Exception
169
     */
170
    protected function configureMappings(): array
171
    {
172
        return [
173
            'category' => function ($value) { $this->object->getProperties()->setCategory($value); },
174
            'company' => function ($value) { $this->object->getProperties()->setCompany($value); },
175
            'created' => function ($value) { $this->object->getProperties()->setCreated($value); },
176
            'creator' => function ($value) { $this->object->getProperties()->setCreator($value); },
177
            'defaultStyle' => function ($value) { $this->object->getDefaultStyle()->applyFromArray($value); },
178
            'description' => function ($value) { $this->object->getProperties()->setDescription($value); },
179
            'format' => function ($value) { $this->parameters['format'] = $value; },
180
            'keywords' => function ($value) { $this->object->getProperties()->setKeywords($value); },
181
            'lastModifiedBy' => function ($value) { $this->object->getProperties()->setLastModifiedBy($value); },
182
            'manager' => function ($value) { $this->object->getProperties()->setManager($value); },
183
            'modified' => function ($value) { $this->object->getProperties()->setModified($value); },
184
            'security' => [
185
                'lockRevision' => function ($value) { $this->object->getSecurity()->setLockRevision($value); },
186
                'lockStructure' => function ($value) { $this->object->getSecurity()->setLockStructure($value); },
187
                'lockWindows' => function ($value) { $this->object->getSecurity()->setLockWindows($value); },
188
                'revisionsPassword' => function ($value) { $this->object->getSecurity()->setRevisionsPassword($value); },
189
                'workbookPassword' => function ($value) { $this->object->getSecurity()->setWorkbookPassword($value); },
190
            ],
191
            'subject' => function ($value) { $this->object->getProperties()->setSubject($value); },
192
            'template' => function ($value) { $this->parameters['template'] = $value; },
193
            'title' => function ($value) { $this->object->getProperties()->setTitle($value); },
194
        ];
195
    }
196
197
    /**
198
     * Resolves paths using Twig namespaces.
199
     * The path must start with the namespace.
200
     * Namespaces are case sensitive.
201
     *
202
     * @param string $path
203
     *
204
     * @return string
205
     */
206 17
    private function expandPath(string $path): string
207
    {
208 17
        $loader = $this->environment->getLoader();
209
210 17
        if ($loader instanceof \Twig_Loader_Filesystem && mb_strpos($path, '@') === 0) {
211
            /*
212
             * @var \Twig_Loader_Filesystem
213
             */
214 11
            foreach ($loader->getNamespaces() as $namespace) {
215 11
                if (mb_strpos($path, $namespace) === 1) {
216 11
                    foreach ($loader->getPaths($namespace) as $namespacePath) {
217 11
                        $expandedPathAttribute = str_replace('@'.$namespace, $namespacePath, $path);
218 11
                        if (Filesystem::exists($expandedPathAttribute)) {
219 11
                            return $expandedPathAttribute;
220
                        }
221
                    }
222
                }
223
            }
224
        }
225
226 6
        return $path;
227
    }
228
}
229