XlsDocumentWrapper   A
last analyzed

Complexity

Total Complexity 32

Size/Duplication

Total Lines 285
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 0
Metric Value
wmc 32
lcom 1
cbo 12
dl 0
loc 285
rs 9.6
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
A initializeMappings() 0 60 1
A start() 0 21 4
C end() 0 65 14
B expandPath() 0 20 6
A getObject() 0 4 1
A setObject() 0 4 1
A getAttributes() 0 4 1
A setAttributes() 0 4 1
A getMappings() 0 4 1
A setMappings() 0 4 1
1
<?php
2
3
namespace MewesK\TwigExcelBundle\Wrapper;
4
5
use PHPExcel_IOFactory;
6
use PHPExcel_Settings;
7
use PHPExcel_Writer_Abstract;
8
use ReflectionClass;
9
use Symfony\Bridge\Twig\AppVariable;
10
use Twig_Environment;
11
use Twig_Loader_Filesystem;
12
13
/**
14
 * Class XlsDocumentWrapper
15
 *
16
 * @package MewesK\TwigExcelBundle\Wrapper
17
 */
18
class XlsDocumentWrapper extends AbstractWrapper
19
{
20
    /**
21
     * @var array
22
     */
23
    protected $context;
24
    /**
25
     * @var Twig_Environment
26
     */
27
    protected $environment;
28
    /**
29
     * @var \PHPExcel
30
     */
31
    protected $object;
32
    /**
33
     * @var array
34
     */
35
    protected $attributes;
36
    /**
37
     * @var array
38
     */
39
    protected $mappings;
40
41
    /**
42
     * XlsDocumentWrapper constructor.
43
     * 
44
     * @param array $context
45
     * @param Twig_Environment $environment
46
     */
47
    public function __construct(array $context, Twig_Environment $environment)
48
    {
49
        $this->context = $context;
50
        $this->environment = $environment;
51
52
        $this->object = null;
53
        $this->attributes = [];
54
        $this->mappings = [];
55
56
        $this->initializeMappings();
57
    }
58
59
    protected function initializeMappings()
60
    {
61
        $this->mappings['category'] = function ($value) {
62
            $this->object->getProperties()->setCategory($value);
63
        };
64
        $this->mappings['company'] = function ($value) {
65
            $this->object->getProperties()->setCompany($value);
66
        };
67
        $this->mappings['created'] = function ($value) {
68
            $this->object->getProperties()->setCreated($value);
69
        };
70
        $this->mappings['creator'] = function ($value) {
71
            $this->object->getProperties()->setCreator($value);
72
        };
73
        $this->mappings['defaultStyle'] = function ($value) {
74
            $this->object->getDefaultStyle()->applyFromArray($value);
75
        };
76
        $this->mappings['description'] = function ($value) {
77
            $this->object->getProperties()->setDescription($value);
78
        };
79
        $this->mappings['format'] = function ($value) {
80
            $this->attributes['format'] = $value;
81
        };
82
        $this->mappings['keywords'] = function ($value) {
83
            $this->object->getProperties()->setKeywords($value);
84
        };
85
        $this->mappings['lastModifiedBy'] = function ($value) {
86
            $this->object->getProperties()->setLastModifiedBy($value);
87
        };
88
        $this->mappings['manager'] = function ($value) {
89
            $this->object->getProperties()->setManager($value);
90
        };
91
        $this->mappings['modified'] = function ($value) {
92
            $this->object->getProperties()->setModified($value);
93
        };
94
        $this->mappings['security']['lockRevision'] = function ($value) {
95
            $this->object->getSecurity()->setLockRevision($value);
96
        };
97
        $this->mappings['security']['lockStructure'] = function ($value) {
98
            $this->object->getSecurity()->setLockStructure($value);
99
        };
100
        $this->mappings['security']['lockWindows'] = function ($value) {
101
            $this->object->getSecurity()->setLockWindows($value);
102
        };
103
        $this->mappings['security']['revisionsPassword'] = function ($value) {
104
            $this->object->getSecurity()->setRevisionsPassword($value);
105
        };
106
        $this->mappings['security']['workbookPassword'] = function ($value) {
107
            $this->object->getSecurity()->setWorkbookPassword($value);
108
        };
109
        $this->mappings['subject'] = function ($value) {
110
            $this->object->getProperties()->setSubject($value);
111
        };
112
        $this->mappings['template'] = function ($value) {
113
            $this->attributes['template'] = $value;
114
        };
115
        $this->mappings['title'] = function ($value) {
116
            $this->object->getProperties()->setTitle($value);
117
        };
118
    }
119
120
    /**
121
     * @param null|array $properties
122
     * @throws \PHPExcel_Exception
123
     */
124
    public function start(array $properties = null)
125
    {
126
        // load template
127
        if (array_key_exists('template', $properties)) {
128
            $templatePath = $this->expandPath($properties['template']);
129
            $reader = PHPExcel_IOFactory::createReaderForFile($templatePath);
130
            $this->object = $reader->load($templatePath);
131
        }
132
133
        // create new
134
        else {
135
            $this->object = new \PHPExcel();
136
            $this->object->removeSheetByIndex(0);
137
        }
138
139
        $this->attributes['properties'] = $properties ?: [];
140
141
        if ($properties !== null) {
142
            $this->setProperties($properties, $this->mappings);
143
        }
144
    }
145
146
    /**
147
     * @param bool $preCalculateFormulas
148
     * @param null|string $diskCachingDirectory
149
     * @throws \InvalidArgumentException
150
     * @throws \PHPExcel_Exception
151
     * @throws \PHPExcel_Reader_Exception
152
     * @throws \PHPExcel_Writer_Exception
153
     */
154
    public function end($preCalculateFormulas = true, $diskCachingDirectory = null)
155
    {
156
        $format = null;
157
158
        // try document property
159
        if (array_key_exists('format', $this->attributes)) {
160
            $format = $this->attributes['format'];
161
        }
162
163
         // try Symfony request
164
        else if (array_key_exists('app', $this->context)) {
165
            /**
166
             * @var $appVariable AppVariable
167
             */
168
            $appVariable = $this->context['app'];
169
            if ($appVariable instanceof AppVariable && $appVariable->getRequest() !== null) {
170
                $format = $appVariable->getRequest()->getRequestFormat();
171
            }
172
        }
173
174
        // set default
175
        if ($format === null || !is_string($format)) {
176
            $format = 'xlsx';
177
        }
178
179
        switch (strtolower($format)) {
180
            case 'csv':
181
                $writerType = 'CSV';
182
                break;
183
            case 'ods':
184
                $writerType = 'OpenDocument';
185
                break;
186
            case 'pdf':
187
                $writerType = 'PDF';
188
                try {
189
                    $reflectionClass = new ReflectionClass('mPDF');
190
                    $path = dirname($reflectionClass->getFileName());
191
                    if (!PHPExcel_Settings::setPdfRenderer(PHPExcel_Settings::PDF_RENDERER_MPDF, $path)) {
192
                        throw new \PHPExcel_Exception();
193
                    }
194
                } catch (\Exception $e) {
195
                    throw new \PHPExcel_Exception('Error loading mPDF. Is mPDF correctly installed?', $e->getCode(), $e);
196
                }
197
                break;
198
            case 'xls':
199
                $writerType = 'Excel5';
200
                break;
201
            case 'xlsx':
202
                $writerType = 'Excel2007';
203
                break;
204
            default:
205
                throw new \InvalidArgumentException(sprintf('Unknown format "%s"', $format));
206
        }
207
208
        /**
209
         * @var $writer PHPExcel_Writer_Abstract
210
         */
211
        $writer = \PHPExcel_IOFactory::createWriter($this->object, $writerType);
212
        $writer->setPreCalculateFormulas($preCalculateFormulas);
213
        $writer->setUseDiskCaching($diskCachingDirectory !== null, $diskCachingDirectory);
214
        $writer->save('php://output');
215
216
        $this->object = null;
217
        $this->attributes = [];
218
    }
219
220
    //
221
    // Helpers
222
    //
223
224
    /**
225
     * Resolves properties containing paths using namespaces.
226
     *
227
     * @param string $path
228
     * @return bool
229
     */
230
    private function expandPath($path)
231
    {
232
        $loader = $this->environment->getLoader();
233
        if ($loader instanceof Twig_Loader_Filesystem) {
0 ignored issues
show
Bug introduced by
The class Twig_Loader_Filesystem does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
234
            /**
235
             * @var Twig_Loader_Filesystem $loader
236
             */
237
            foreach ($loader->getNamespaces() as $namespace) {
238
                if (strpos($path, $namespace) === 1) {
239
                    foreach ($loader->getPaths($namespace) as $namespacePath) {
240
                        $expandedPathAttribute = str_replace('@' . $namespace, $namespacePath, $path);
241
                        if (file_exists($expandedPathAttribute)) {
242
                            return $expandedPathAttribute;
243
                        }
244
                    }
245
                }
246
            }
247
        }
248
        return $path;
249
    }
250
251
    //
252
    // Getters/Setters
253
    //
254
255
    /**
256
     * @return \PHPExcel
257
     */
258
    public function getObject()
259
    {
260
        return $this->object;
261
    }
262
263
    /**
264
     * @param \PHPExcel $object
265
     */
266
    public function setObject($object)
267
    {
268
        $this->object = $object;
269
    }
270
271
    /**
272
     * @return array
273
     */
274
    public function getAttributes()
275
    {
276
        return $this->attributes;
277
    }
278
279
    /**
280
     * @param array $attributes
281
     */
282
    public function setAttributes($attributes)
283
    {
284
        $this->attributes = $attributes;
285
    }
286
287
    /**
288
     * @return array
289
     */
290
    public function getMappings()
291
    {
292
        return $this->mappings;
293
    }
294
295
    /**
296
     * @param array $mappings
297
     */
298
    public function setMappings($mappings)
299
    {
300
        $this->mappings = $mappings;
301
    }
302
}
303