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 Setup Failed
Push — master ( 78f8b7...0f754d )
by Elemér
04:15
created

DocumentWrapper::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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