Completed
Push — develop ( 2b41bd...39b55d )
by Adrien
22:48
created

StringTable::createStringTable()   C

Complexity

Conditions 15
Paths 9

Size

Total Lines 40
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 15.0144

Importance

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

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
/**
6
 * Copyright (c) 2006 - 2016 PhpSpreadsheet
7
 *
8
 * This library is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU Lesser General Public
10
 * License as published by the Free Software Foundation; either
11
 * version 2.1 of the License, or (at your option) any later version.
12
 *
13
 * This library is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
 * Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General Public
19
 * License along with this library; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21
 *
22
 * @category   PhpSpreadsheet
23
 * @copyright  Copyright (c) 2006 - 2016 PhpSpreadsheet (https://github.com/PHPOffice/PhpSpreadsheet)
24
 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt    LGPL
25
 * @version    ##VERSION##, ##DATE##
26
 */
27
class StringTable extends WriterPart
28
{
29
    /**
30
     * Create worksheet stringtable
31
     *
32
     * @param     \PhpOffice\PhpSpreadsheet\Worksheet     $pSheet                Worksheet
33
     * @param     string[]                 $pExistingTable     Existing table to eventually merge with
34
     * @throws     \PhpOffice\PhpSpreadsheet\Writer\Exception
35
     * @return     string[]                 String table for worksheet
36
     */
37 56
    public function createStringTable($pSheet = null, $pExistingTable = null)
38
    {
39 56
        if ($pSheet !== null) {
40
            // Create string lookup table
41 56
            $aStringTable = [];
42 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...
43 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...
44
45
            // Is an existing table given?
46 56
            if (($pExistingTable !== null) && is_array($pExistingTable)) {
47 56
                $aStringTable = $pExistingTable;
48
            }
49
50
            // Fill index array
51 56
            $aFlippedStringTable = $this->flipStringTable($aStringTable);
52
53
            // Loop through cells
54 56
            foreach ($pSheet->getCellCollection() as $cellID) {
55 56
                $cell = $pSheet->getCell($cellID);
56 56
                $cellValue = $cell->getValue();
57 56
                if (!is_object($cellValue) &&
58 56
                    ($cellValue !== null) &&
59 56
                    $cellValue !== '' &&
60 56
                    !isset($aFlippedStringTable[$cellValue]) &&
61 56
                    ($cell->getDataType() == \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING || $cell->getDataType() == \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING2 || $cell->getDataType() == \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NULL)) {
62 50
                    $aStringTable[] = $cellValue;
63 50
                    $aFlippedStringTable[$cellValue] = true;
64 53
                } elseif ($cellValue instanceof \PhpOffice\PhpSpreadsheet\RichText &&
65 53
                          ($cellValue !== null) &&
66 53
                          !isset($aFlippedStringTable[$cellValue->getHashCode()])) {
67 10
                    $aStringTable[] = $cellValue;
68 56
                    $aFlippedStringTable[$cellValue->getHashCode()] = true;
69
                }
70
            }
71
72 56
            return $aStringTable;
73
        } else {
74
            throw new \PhpOffice\PhpSpreadsheet\Writer\Exception("Invalid \PhpOffice\PhpSpreadsheet\Worksheet object passed.");
75
        }
76
    }
77
78
    /**
79
     * Write string table to XML format
80
     *
81
     * @param     string[]     $pStringTable
82
     * @throws     \PhpOffice\PhpSpreadsheet\Writer\Exception
83
     * @return string  XML Output
84
     */
85 56
    public function writeStringTable($pStringTable = null)
86
    {
87 56
        if ($pStringTable !== null) {
88
            // Create XML writer
89 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...
90 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...
Bug introduced by
It seems like you code against a concrete implementation and not the interface PhpOffice\PhpSpreadsheet\Writer\IWriter as the method getUseDiskCaching() does only exist in the following implementations of said interface: PhpOffice\PhpSpreadsheet\Writer\BaseWriter, PhpOffice\PhpSpreadsheet\Writer\CSV, PhpOffice\PhpSpreadsheet\Writer\Excel5, PhpOffice\PhpSpreadsheet\Writer\HTML, PhpOffice\PhpSpreadsheet\Writer\OpenDocument, PhpOffice\PhpSpreadsheet\Writer\PDF\Core, PhpOffice\PhpSpreadsheet\Writer\PDF\DomPDF, PhpOffice\PhpSpreadsheet\Writer\PDF\MPDF, PhpOffice\PhpSpreadsheet\Writer\PDF\TcPDF, PhpOffice\PhpSpreadsheet\Writer\Xlsx.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
91
                $objWriter = new \PhpOffice\PhpSpreadsheet\Shared\XMLWriter(\PhpOffice\PhpSpreadsheet\Shared\XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface PhpOffice\PhpSpreadsheet\Writer\IWriter as the method getDiskCachingDirectory() does only exist in the following implementations of said interface: PhpOffice\PhpSpreadsheet\Writer\BaseWriter, PhpOffice\PhpSpreadsheet\Writer\CSV, PhpOffice\PhpSpreadsheet\Writer\Excel5, PhpOffice\PhpSpreadsheet\Writer\HTML, PhpOffice\PhpSpreadsheet\Writer\OpenDocument, PhpOffice\PhpSpreadsheet\Writer\PDF\Core, PhpOffice\PhpSpreadsheet\Writer\PDF\DomPDF, PhpOffice\PhpSpreadsheet\Writer\PDF\MPDF, PhpOffice\PhpSpreadsheet\Writer\PDF\TcPDF, PhpOffice\PhpSpreadsheet\Writer\Xlsx.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
92
            } else {
93 56
                $objWriter = new \PhpOffice\PhpSpreadsheet\Shared\XMLWriter(\PhpOffice\PhpSpreadsheet\Shared\XMLWriter::STORAGE_MEMORY);
94
            }
95
96
            // XML header
97 56
            $objWriter->startDocument('1.0', 'UTF-8', 'yes');
98
99
            // String table
100 56
            $objWriter->startElement('sst');
101 56
            $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
102 56
            $objWriter->writeAttribute('uniqueCount', count($pStringTable));
103
104
            // Loop through string table
105 56
            foreach ($pStringTable as $textElement) {
106 51
                $objWriter->startElement('si');
107
108 51
                if (!$textElement instanceof \PhpOffice\PhpSpreadsheet\RichText) {
109 50
                    $textToWrite = \PhpOffice\PhpSpreadsheet\Shared\StringHelper::controlCharacterPHP2OOXML($textElement);
110 50
                    $objWriter->startElement('t');
111 50
                    if ($textToWrite !== trim($textToWrite)) {
112 1
                        $objWriter->writeAttribute('xml:space', 'preserve');
113
                    }
114 50
                    $objWriter->writeRawData($textToWrite);
115 50
                    $objWriter->endElement();
116
                } elseif ($textElement instanceof \PhpOffice\PhpSpreadsheet\RichText) {
117 10
                    $this->writeRichText($objWriter, $textElement);
118
                }
119
120 51
                $objWriter->endElement();
121
            }
122
123 56
            $objWriter->endElement();
124
125 56
            return $objWriter->getData();
126
        } else {
127
            throw new \PhpOffice\PhpSpreadsheet\Writer\Exception('Invalid string table array passed.');
128
        }
129
    }
130
131
    /**
132
     * Write Rich Text
133
     *
134
     * @param     \PhpOffice\PhpSpreadsheet\Shared\XMLWriter    $objWriter         XML Writer
135
     * @param     \PhpOffice\PhpSpreadsheet\RichText            $pRichText        Rich text
136
     * @param     string                        $prefix            Optional Namespace prefix
137
     * @throws     \PhpOffice\PhpSpreadsheet\Writer\Exception
138
     */
139 13
    public function writeRichText(\PhpOffice\PhpSpreadsheet\Shared\XMLWriter $objWriter = null, \PhpOffice\PhpSpreadsheet\RichText $pRichText = null, $prefix = null)
140
    {
141 13
        if ($prefix !== null) {
142
            $prefix .= ':';
143
        }
144
145
        // Loop through rich text elements
146 13
        $elements = $pRichText->getRichTextElements();
0 ignored issues
show
Bug introduced by
It seems like $pRichText is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
147 13
        foreach ($elements as $element) {
148
            // r
149 13
            $objWriter->startElement($prefix . 'r');
0 ignored issues
show
Bug introduced by
It seems like $objWriter is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
150
151
            // rPr
152 13
            if ($element instanceof \PhpOffice\PhpSpreadsheet\RichText\Run) {
153
                // rPr
154 10
                $objWriter->startElement($prefix . 'rPr');
155
156
                // rFont
157 10
                $objWriter->startElement($prefix . 'rFont');
158 10
                $objWriter->writeAttribute('val', $element->getFont()->getName());
159 10
                $objWriter->endElement();
160
161
                // Bold
162 10
                $objWriter->startElement($prefix . 'b');
163 10
                $objWriter->writeAttribute('val', ($element->getFont()->getBold() ? 'true' : 'false'));
164 10
                $objWriter->endElement();
165
166
                // Italic
167 10
                $objWriter->startElement($prefix . 'i');
168 10
                $objWriter->writeAttribute('val', ($element->getFont()->getItalic() ? 'true' : 'false'));
169 10
                $objWriter->endElement();
170
171
                // Superscript / subscript
172 10
                if ($element->getFont()->getSuperScript() || $element->getFont()->getSubScript()) {
173 1
                    $objWriter->startElement($prefix . 'vertAlign');
174 1
                    if ($element->getFont()->getSuperScript()) {
175 1
                        $objWriter->writeAttribute('val', 'superscript');
176 1
                    } elseif ($element->getFont()->getSubScript()) {
177 1
                        $objWriter->writeAttribute('val', 'subscript');
178
                    }
179 1
                    $objWriter->endElement();
180
                }
181
182
                // Strikethrough
183 10
                $objWriter->startElement($prefix . 'strike');
184 10
                $objWriter->writeAttribute('val', ($element->getFont()->getStrikethrough() ? 'true' : 'false'));
185 10
                $objWriter->endElement();
186
187
                // Color
188 10
                $objWriter->startElement($prefix . 'color');
189 10
                $objWriter->writeAttribute('rgb', $element->getFont()->getColor()->getARGB());
190 10
                $objWriter->endElement();
191
192
                // Size
193 10
                $objWriter->startElement($prefix . 'sz');
194 10
                $objWriter->writeAttribute('val', $element->getFont()->getSize());
195 10
                $objWriter->endElement();
196
197
                // Underline
198 10
                $objWriter->startElement($prefix . 'u');
199 10
                $objWriter->writeAttribute('val', $element->getFont()->getUnderline());
200 10
                $objWriter->endElement();
201
202 10
                $objWriter->endElement();
203
            }
204
205
            // t
206 13
            $objWriter->startElement($prefix . 't');
207 13
            $objWriter->writeAttribute('xml:space', 'preserve');
208 13
            $objWriter->writeRawData(\PhpOffice\PhpSpreadsheet\Shared\StringHelper::controlCharacterPHP2OOXML($element->getText()));
209 13
            $objWriter->endElement();
210
211 13
            $objWriter->endElement();
212
        }
213 13
    }
214
215
    /**
216
     * Write Rich Text
217
     *
218
     * @param     \PhpOffice\PhpSpreadsheet\Shared\XMLWriter    $objWriter         XML Writer
219
     * @param     string|\PhpOffice\PhpSpreadsheet\RichText    $pRichText        text string or Rich text
220
     * @param     string                        $prefix            Optional Namespace prefix
221
     * @throws     \PhpOffice\PhpSpreadsheet\Writer\Exception
222
     */
223 13
    public function writeRichTextForCharts(\PhpOffice\PhpSpreadsheet\Shared\XMLWriter $objWriter = null, $pRichText = null, $prefix = null)
224
    {
225 13
        if (!$pRichText instanceof \PhpOffice\PhpSpreadsheet\RichText) {
226 12
            $textRun = $pRichText;
227 12
            $pRichText = new \PhpOffice\PhpSpreadsheet\RichText();
228 12
            $pRichText->createTextRun($textRun);
229
        }
230
231 13
        if ($prefix !== null) {
232 13
            $prefix .= ':';
233
        }
234
235
        // Loop through rich text elements
236 13
        $elements = $pRichText->getRichTextElements();
237 13
        foreach ($elements as $element) {
238
            // r
239 13
            $objWriter->startElement($prefix . 'r');
0 ignored issues
show
Bug introduced by
It seems like $objWriter is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
240
241
            // rPr
242 13
            $objWriter->startElement($prefix . 'rPr');
243
244
            // Bold
245 13
            $objWriter->writeAttribute('b', ($element->getFont()->getBold() ? 1 : 0));
246
            // Italic
247 13
            $objWriter->writeAttribute('i', ($element->getFont()->getItalic() ? 1 : 0));
248
            // Underline
249 13
            $underlineType = $element->getFont()->getUnderline();
250
            switch ($underlineType) {
251 13
                case 'single':
252 1
                    $underlineType = 'sng';
253 1
                    break;
254 13
                case 'double':
255 1
                    $underlineType = 'dbl';
256 1
                    break;
257
            }
258 13
            $objWriter->writeAttribute('u', $underlineType);
259
            // Strikethrough
260 13
            $objWriter->writeAttribute('strike', ($element->getFont()->getStrikethrough() ? 'sngStrike' : 'noStrike'));
261
262
            // rFont
263 13
            $objWriter->startElement($prefix . 'latin');
264 13
            $objWriter->writeAttribute('typeface', $element->getFont()->getName());
265 13
            $objWriter->endElement();
266
267 13
            $objWriter->endElement();
268
269
            // t
270 13
            $objWriter->startElement($prefix . 't');
271 13
            $objWriter->writeRawData(\PhpOffice\PhpSpreadsheet\Shared\StringHelper::controlCharacterPHP2OOXML($element->getText()));
272 13
            $objWriter->endElement();
273
274 13
            $objWriter->endElement();
275
        }
276 13
    }
277
278
    /**
279
     * Flip string table (for index searching)
280
     *
281
     * @param     array    $stringTable    Stringtable
282
     * @return     array
283
     */
284 56
    public function flipStringTable($stringTable = [])
285
    {
286
        // Return value
287 56
        $returnValue = [];
288
289
        // Loop through stringtable and add flipped items to $returnValue
290 56
        foreach ($stringTable as $key => $value) {
291 51
            if (!$value instanceof \PhpOffice\PhpSpreadsheet\RichText) {
292 50
                $returnValue[$value] = $key;
293
            } elseif ($value instanceof \PhpOffice\PhpSpreadsheet\RichText) {
294 51
                $returnValue[$value->getHashCode()] = $key;
295
            }
296
        }
297
298 56
        return $returnValue;
299
    }
300
}
301