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
Pull Request — master (#23)
by
unknown
04:15
created

DocumentWrapper::getObject()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
namespace MyWheels\TwigSpreadsheetBundle\Wrapper;
4
5
use MyWheels\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 121
    public function __construct(array $context, \Twig_Environment $environment, array $attributes = [])
36
    {
37 121
        parent::__construct($context, $environment);
38
39 121
        $this->object = null;
40 121
        $this->attributes = $attributes;
41 121
    }
42
43
    /**
44
     * @param array $properties
45
     *
46
     * @throws \RuntimeException
47
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
48
     * @throws \PhpOffice\PhpSpreadsheet\Exception
49
     */
50 121
    public function start(array $properties = [])
51
    {
52
        // load template
53 121
        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 104
            $this->object = new Spreadsheet();
62 104
            $this->object->removeSheetByIndex(0);
63
        }
64
65 121
        $this->parameters['properties'] = $properties;
66
67 121
        $this->setProperties($properties);
68 121
    }
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 113
    public function end()
79
    {
80 113
        if ($this->object === null) {
81
            throw new \LogicException();
82
        }
83
84 113
        $format = null;
85
86
        // try document property
87 113
        if (isset($this->parameters['format'])) {
88
            $format = $this->parameters['format'];
89
        }
90
91
         // try Symfony request
92 113
        elseif (isset($this->context['app'])) {
93
            /**
94
             * @var AppVariable
95
             */
96 113
            $appVariable = $this->context['app'];
97 113
            if ($appVariable instanceof AppVariable && $appVariable->getRequest() !== null) {
98 113
                $format = $appVariable->getRequest()->getRequestFormat();
99
            }
100
        }
101
102
        // set default
103 113
        if ($format === null || !\is_string($format)) {
104
            $format = 'xlsx';
105
        } else {
106 113
            $format = strtolower($format);
107
        }
108
109
        // set up mPDF
110 113
        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 113
        $writer = IOFactory::createWriter($this->object, ucfirst($format));
121 113
        $writer->setPreCalculateFormulas($this->attributes['pre_calculate_formulas'] ?? true);
122
123
        // set up XML cache
124 113
        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 113
        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 113
        $writer->save('php://output');
144
145 113
        $this->object = null;
146 113
        $this->parameters = [];
147 113
    }
148
149
    /**
150
     * @return Spreadsheet|null
151
     */
152 109
    public function getObject()
153
    {
154 109
        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