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 ( 6df24a...0dcb27 )
by Mewes
04:06
created

DocumentWrapper::end()   D

Complexity

Conditions 18
Paths 176

Size

Total Lines 74
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 24.2575

Importance

Changes 0
Metric Value
dl 0
loc 74
ccs 30
cts 41
cp 0.7317
rs 4.9555
c 0
b 0
f 0
cc 18
eloc 45
nc 176
nop 0
crap 24.2575

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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