Completed
Push — develop ( 91417a...f02c33 )
by Adrien
18:11
created

StringTable::writeRichText()   C

Complexity

Conditions 11
Paths 12

Size

Total Lines 75
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 132

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 11
eloc 42
c 2
b 0
f 0
nc 12
nop 3
dl 0
loc 75
ccs 0
cts 49
cp 0
crap 132
rs 5.4893

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 PhpSpreadsheet\Writer\Excel2007;
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     \PhpSpreadsheet\Worksheet     $pSheet                Worksheet
33
     * @param     string[]                 $pExistingTable     Existing table to eventually merge with
34
     * @throws     \PhpSpreadsheet\Writer\Exception
35
     * @return     string[]                 String table for worksheet
36
     */
37
    public function createStringTable($pSheet = null, $pExistingTable = null)
38
    {
39
        if ($pSheet !== null) {
40
            // Create string lookup table
41
            $aStringTable = [];
42
            $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
            $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
            if (($pExistingTable !== null) && is_array($pExistingTable)) {
47
                $aStringTable = $pExistingTable;
48
            }
49
50
            // Fill index array
51
            $aFlippedStringTable = $this->flipStringTable($aStringTable);
52
53
            // Loop through cells
54
            foreach ($pSheet->getCellCollection() as $cellID) {
55
                $cell = $pSheet->getCell($cellID);
56
                $cellValue = $cell->getValue();
57
                if (!is_object($cellValue) &&
58
                    ($cellValue !== null) &&
59
                    $cellValue !== '' &&
60
                    !isset($aFlippedStringTable[$cellValue]) &&
61
                    ($cell->getDataType() == \PhpSpreadsheet\Cell\DataType::TYPE_STRING || $cell->getDataType() == \PhpSpreadsheet\Cell\DataType::TYPE_STRING2 || $cell->getDataType() == \PhpSpreadsheet\Cell\DataType::TYPE_NULL)) {
62
                    $aStringTable[] = $cellValue;
63
                    $aFlippedStringTable[$cellValue] = true;
64
                } elseif ($cellValue instanceof \PhpSpreadsheet\RichText &&
65
                          ($cellValue !== null) &&
66
                          !isset($aFlippedStringTable[$cellValue->getHashCode()])) {
67
                    $aStringTable[] = $cellValue;
68
                    $aFlippedStringTable[$cellValue->getHashCode()] = true;
69
                }
70
            }
71
72
            return $aStringTable;
73
        } else {
74
            throw new \PhpSpreadsheet\Writer\Exception("Invalid \PhpSpreadsheet\Worksheet object passed.");
75
        }
76
    }
77
78
    /**
79
     * Write string table to XML format
80
     *
81
     * @param     string[]     $pStringTable
82
     * @throws     \PhpSpreadsheet\Writer\Exception
83
     * @return string  XML Output
84
     */
85
    public function writeStringTable($pStringTable = null)
86
    {
87
        if ($pStringTable !== null) {
88
            // Create XML writer
89
            $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 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 PhpSpreadsheet\Writer\IWriter as the method getUseDiskCaching() does only exist in the following implementations of said interface: PhpSpreadsheet\Writer\BaseWriter, PhpSpreadsheet\Writer\CSV, PhpSpreadsheet\Writer\Excel2007, PhpSpreadsheet\Writer\Excel5, PhpSpreadsheet\Writer\HTML, PhpSpreadsheet\Writer\OpenDocument, PhpSpreadsheet\Writer\PDF\Core, PhpSpreadsheet\Writer\PDF\DomPDF, PhpSpreadsheet\Writer\PDF\MPDF, PhpSpreadsheet\Writer\PDF\TcPDF.

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 \PhpSpreadsheet\Shared\XMLWriter(\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 PhpSpreadsheet\Writer\IWriter as the method getDiskCachingDirectory() does only exist in the following implementations of said interface: PhpSpreadsheet\Writer\BaseWriter, PhpSpreadsheet\Writer\CSV, PhpSpreadsheet\Writer\Excel2007, PhpSpreadsheet\Writer\Excel5, PhpSpreadsheet\Writer\HTML, PhpSpreadsheet\Writer\OpenDocument, PhpSpreadsheet\Writer\PDF\Core, PhpSpreadsheet\Writer\PDF\DomPDF, PhpSpreadsheet\Writer\PDF\MPDF, PhpSpreadsheet\Writer\PDF\TcPDF.

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