Completed
Push — develop ( 672893...dd9590 )
by Adrien
28:52 queued 21:58
created

StringTable::createStringTable()   C

Complexity

Conditions 15
Paths 9

Size

Total Lines 39
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 15.0144

Importance

Changes 0
Metric Value
cc 15
eloc 25
nc 9
nop 2
dl 0
loc 39
rs 5.0504
c 0
b 0
f 0
ccs 24
cts 25
cp 0.96
crap 15.0144

How to fix   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 PhpOffice\PhpSpreadsheet\Writer\Xlsx;
4
5
use PhpOffice\PhpSpreadsheet\Cell;
6
use PhpOffice\PhpSpreadsheet\RichText;
7
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
8
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
9
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
10
11
/**
12
 * Copyright (c) 2006 - 2016 PhpSpreadsheet.
13
 *
14
 * This library is free software; you can redistribute it and/or
15
 * modify it under the terms of the GNU Lesser General Public
16
 * License as published by the Free Software Foundation; either
17
 * version 2.1 of the License, or (at your option) any later version.
18
 *
19
 * This library is distributed in the hope that it will be useful,
20
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22
 * Lesser General Public License for more details.
23
 *
24
 * You should have received a copy of the GNU Lesser General Public
25
 * License along with this library; if not, write to the Free Software
26
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27
 *
28
 * @category   PhpSpreadsheet
29
 *
30
 * @copyright  Copyright (c) 2006 - 2016 PhpSpreadsheet (https://github.com/PHPOffice/PhpSpreadsheet)
31
 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt    LGPL
32
 */
33
class StringTable extends WriterPart
34
{
35
    /**
36
     * Create worksheet stringtable.
37
     *
38
     * @param Worksheet $pSheet Worksheet
39
     * @param string[] $pExistingTable Existing table to eventually merge with
40
     *
41
     * @throws WriterException
42
     *
43
     * @return string[] String table for worksheet
44
     */
45 56
    public function createStringTable($pSheet = null, $pExistingTable = null)
46
    {
47 56
        if ($pSheet !== null) {
48
            // Create string lookup table
49 56
            $aStringTable = [];
50 56
            $cellCollection = null;
0 ignored issues
show
Unused Code introduced by
$cellCollection is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
51 56
            $aFlippedStringTable = null; // For faster lookup
0 ignored issues
show
Unused Code introduced by
$aFlippedStringTable is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
52
53
            // Is an existing table given?
54 56
            if (($pExistingTable !== null) && is_array($pExistingTable)) {
55 56
                $aStringTable = $pExistingTable;
56
            }
57
58
            // Fill index array
59 56
            $aFlippedStringTable = $this->flipStringTable($aStringTable);
60
61
            // Loop through cells
62 56
            foreach ($pSheet->getCoordinates() as $coordinate) {
0 ignored issues
show
Bug introduced by
The method getCoordinates() does not seem to exist on object<PhpOffice\PhpSpre...\Writer\Xlsx\Worksheet>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
63 56
                $cell = $pSheet->getCell($coordinate);
0 ignored issues
show
Bug introduced by
The method getCell() does not seem to exist on object<PhpOffice\PhpSpre...\Writer\Xlsx\Worksheet>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
64 56
                $cellValue = $cell->getValue();
65 56
                if (!is_object($cellValue) &&
66 56
                    ($cellValue !== null) &&
67 56
                    $cellValue !== '' &&
68 56
                    !isset($aFlippedStringTable[$cellValue]) &&
69 56
                    ($cell->getDataType() == Cell\DataType::TYPE_STRING || $cell->getDataType() == Cell\DataType::TYPE_STRING2 || $cell->getDataType() == Cell\DataType::TYPE_NULL)) {
70 50
                    $aStringTable[] = $cellValue;
71 50
                    $aFlippedStringTable[$cellValue] = true;
72 53
                } elseif ($cellValue instanceof RichText &&
73 53
                          ($cellValue !== null) &&
74 53
                          !isset($aFlippedStringTable[$cellValue->getHashCode()])) {
75 10
                    $aStringTable[] = $cellValue;
76 56
                    $aFlippedStringTable[$cellValue->getHashCode()] = true;
77
                }
78
            }
79
80 56
            return $aStringTable;
81
        }
82
        throw new WriterException('Invalid Worksheet object passed.');
83
    }
84
85
    /**
86
     * Write string table to XML format.
87
     *
88
     * @param string[] $pStringTable
89
     *
90
     * @throws WriterException
91
     *
92
     * @return string XML Output
93
     */
94 56
    public function writeStringTable(array $pStringTable)
95
    {
96
        // Create XML writer
97 56
        $objWriter = null;
0 ignored issues
show
Unused Code introduced by
$objWriter is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
98 56 View Code Duplication
        if ($this->getParentWriter()->getUseDiskCaching()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
99
            $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
100
        } else {
101 56
            $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
102
        }
103
104
        // XML header
105 56
        $objWriter->startDocument('1.0', 'UTF-8', 'yes');
106
107
        // String table
108 56
        $objWriter->startElement('sst');
109 56
        $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
110 56
        $objWriter->writeAttribute('uniqueCount', count($pStringTable));
111
112
        // Loop through string table
113 56
        foreach ($pStringTable as $textElement) {
114 51
            $objWriter->startElement('si');
115
116 51
            if (!$textElement instanceof RichText) {
117 50
                $textToWrite = StringHelper::controlCharacterPHP2OOXML($textElement);
118 50
                $objWriter->startElement('t');
119 50
                if ($textToWrite !== trim($textToWrite)) {
120 1
                    $objWriter->writeAttribute('xml:space', 'preserve');
121
                }
122 50
                $objWriter->writeRawData($textToWrite);
123 50
                $objWriter->endElement();
124
            } elseif ($textElement instanceof RichText) {
125 10
                $this->writeRichText($objWriter, $textElement);
126
            }
127
128 51
            $objWriter->endElement();
129
        }
130
131 56
        $objWriter->endElement();
132
133 56
        return $objWriter->getData();
134
    }
135
136
    /**
137
     * Write Rich Text.
138
     *
139
     * @param XMLWriter $objWriter XML Writer
140
     * @param RichText $pRichText Rich text
141
     * @param string $prefix Optional Namespace prefix
142
     *
143
     * @throws WriterException
144
     */
145 13
    public function writeRichText(XMLWriter $objWriter, RichText $pRichText, $prefix = null)
146
    {
147 13
        if ($prefix !== null) {
148
            $prefix .= ':';
149
        }
150
151
        // Loop through rich text elements
152 13
        $elements = $pRichText->getRichTextElements();
153 13
        foreach ($elements as $element) {
154
            // r
155 13
            $objWriter->startElement($prefix . 'r');
156
157
            // rPr
158 13
            if ($element instanceof RichText\Run) {
159
                // rPr
160 10
                $objWriter->startElement($prefix . 'rPr');
161
162
                // rFont
163 10
                $objWriter->startElement($prefix . 'rFont');
164 10
                $objWriter->writeAttribute('val', $element->getFont()->getName());
165 10
                $objWriter->endElement();
166
167
                // Bold
168 10
                $objWriter->startElement($prefix . 'b');
169 10
                $objWriter->writeAttribute('val', ($element->getFont()->getBold() ? 'true' : 'false'));
170 10
                $objWriter->endElement();
171
172
                // Italic
173 10
                $objWriter->startElement($prefix . 'i');
174 10
                $objWriter->writeAttribute('val', ($element->getFont()->getItalic() ? 'true' : 'false'));
175 10
                $objWriter->endElement();
176
177
                // Superscript / subscript
178 10
                if ($element->getFont()->getSuperscript() || $element->getFont()->getSubscript()) {
179 1
                    $objWriter->startElement($prefix . 'vertAlign');
180 1
                    if ($element->getFont()->getSuperscript()) {
181 1
                        $objWriter->writeAttribute('val', 'superscript');
182 1
                    } elseif ($element->getFont()->getSubscript()) {
183 1
                        $objWriter->writeAttribute('val', 'subscript');
184
                    }
185 1
                    $objWriter->endElement();
186
                }
187
188
                // Strikethrough
189 10
                $objWriter->startElement($prefix . 'strike');
190 10
                $objWriter->writeAttribute('val', ($element->getFont()->getStrikethrough() ? 'true' : 'false'));
191 10
                $objWriter->endElement();
192
193
                // Color
194 10
                $objWriter->startElement($prefix . 'color');
195 10
                $objWriter->writeAttribute('rgb', $element->getFont()->getColor()->getARGB());
196 10
                $objWriter->endElement();
197
198
                // Size
199 10
                $objWriter->startElement($prefix . 'sz');
200 10
                $objWriter->writeAttribute('val', $element->getFont()->getSize());
201 10
                $objWriter->endElement();
202
203
                // Underline
204 10
                $objWriter->startElement($prefix . 'u');
205 10
                $objWriter->writeAttribute('val', $element->getFont()->getUnderline());
206 10
                $objWriter->endElement();
207
208 10
                $objWriter->endElement();
209
            }
210
211
            // t
212 13
            $objWriter->startElement($prefix . 't');
213 13
            $objWriter->writeAttribute('xml:space', 'preserve');
214 13
            $objWriter->writeRawData(StringHelper::controlCharacterPHP2OOXML($element->getText()));
215 13
            $objWriter->endElement();
216
217 13
            $objWriter->endElement();
218
        }
219 13
    }
220
221
    /**
222
     * Write Rich Text.
223
     *
224
     * @param XMLWriter $objWriter XML Writer
225
     * @param string|RichText $pRichText text string or Rich text
226
     * @param string $prefix Optional Namespace prefix
227
     *
228
     * @throws WriterException
229
     */
230 13
    public function writeRichTextForCharts(XMLWriter $objWriter, $pRichText = null, $prefix = null)
231
    {
232 13
        if (!$pRichText instanceof RichText) {
233 12
            $textRun = $pRichText;
234 12
            $pRichText = new RichText();
235 12
            $pRichText->createTextRun($textRun);
236
        }
237
238 13
        if ($prefix !== null) {
239 13
            $prefix .= ':';
240
        }
241
242
        // Loop through rich text elements
243 13
        $elements = $pRichText->getRichTextElements();
244 13
        foreach ($elements as $element) {
245
            // r
246 13
            $objWriter->startElement($prefix . 'r');
247
248
            // rPr
249 13
            $objWriter->startElement($prefix . 'rPr');
250
251
            // Bold
252 13
            $objWriter->writeAttribute('b', ($element->getFont()->getBold() ? 1 : 0));
253
            // Italic
254 13
            $objWriter->writeAttribute('i', ($element->getFont()->getItalic() ? 1 : 0));
255
            // Underline
256 13
            $underlineType = $element->getFont()->getUnderline();
257
            switch ($underlineType) {
258 13
                case 'single':
259 1
                    $underlineType = 'sng';
260 1
                    break;
261 13
                case 'double':
262 1
                    $underlineType = 'dbl';
263 1
                    break;
264
            }
265 13
            $objWriter->writeAttribute('u', $underlineType);
266
            // Strikethrough
267 13
            $objWriter->writeAttribute('strike', ($element->getFont()->getStrikethrough() ? 'sngStrike' : 'noStrike'));
268
269
            // rFont
270 13
            $objWriter->startElement($prefix . 'latin');
271 13
            $objWriter->writeAttribute('typeface', $element->getFont()->getName());
272 13
            $objWriter->endElement();
273
274 13
            $objWriter->endElement();
275
276
            // t
277 13
            $objWriter->startElement($prefix . 't');
278 13
            $objWriter->writeRawData(StringHelper::controlCharacterPHP2OOXML($element->getText()));
279 13
            $objWriter->endElement();
280
281 13
            $objWriter->endElement();
282
        }
283 13
    }
284
285
    /**
286
     * Flip string table (for index searching).
287
     *
288
     * @param array $stringTable Stringtable
289
     *
290
     * @return array
291
     */
292 56
    public function flipStringTable(array $stringTable)
293
    {
294
        // Return value
295 56
        $returnValue = [];
296
297
        // Loop through stringtable and add flipped items to $returnValue
298 56
        foreach ($stringTable as $key => $value) {
299 51
            if (!$value instanceof RichText) {
300 50
                $returnValue[$value] = $key;
301
            } elseif ($value instanceof RichText) {
302 51
                $returnValue[$value->getHashCode()] = $key;
303
            }
304
        }
305
306 56
        return $returnValue;
307
    }
308
}
309