Completed
Push — develop ( 75d3bd...a06533 )
by Adrien
21:48
created

StringTable::writeRichTextForCharts()   B

Complexity

Conditions 9
Paths 16

Size

Total Lines 54
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 31
CRAP Score 9

Importance

Changes 0
Metric Value
cc 9
eloc 31
nc 16
nop 3
dl 0
loc 54
ccs 31
cts 31
cp 1
crap 9
rs 7.255
c 0
b 0
f 0

How to fix   Long Method   

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
 *
24
 * @copyright  Copyright (c) 2006 - 2016 PhpSpreadsheet (https://github.com/PHPOffice/PhpSpreadsheet)
25
 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt    LGPL
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
     *
35
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
36
     *
37
     * @return string[] String table for worksheet
38
     */
39 55
    public function createStringTable($pSheet = null, $pExistingTable = null)
40
    {
41 55
        if ($pSheet !== null) {
42
            // Create string lookup table
43 55
            $aStringTable = [];
44 55
            $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...
45 55
            $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...
46
47
            // Is an existing table given?
48 55
            if (($pExistingTable !== null) && is_array($pExistingTable)) {
49 55
                $aStringTable = $pExistingTable;
50
            }
51
52
            // Fill index array
53 55
            $aFlippedStringTable = $this->flipStringTable($aStringTable);
54
55
            // Loop through cells
56 55
            foreach ($pSheet->getCoordinates() as $coordinate) {
57 55
                $cell = $pSheet->getCell($coordinate);
58 55
                $cellValue = $cell->getValue();
59 55
                if (!is_object($cellValue) &&
60 54
                    ($cellValue !== null) &&
61 51
                    $cellValue !== '' &&
62 51
                    !isset($aFlippedStringTable[$cellValue]) &&
63 51
                    ($cell->getDataType() == \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING || $cell->getDataType() == \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING2 || $cell->getDataType() == \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NULL)) {
64 49
                    $aStringTable[] = $cellValue;
65 49
                    $aFlippedStringTable[$cellValue] = true;
66
                } elseif ($cellValue instanceof \PhpOffice\PhpSpreadsheet\RichText &&
67 10
                          ($cellValue !== null) &&
68 10
                          !isset($aFlippedStringTable[$cellValue->getHashCode()])) {
69 10
                    $aStringTable[] = $cellValue;
70 10
                    $aFlippedStringTable[$cellValue->getHashCode()] = true;
71
                }
72
            }
73
74 55
            return $aStringTable;
75
        }
76
        throw new \PhpOffice\PhpSpreadsheet\Writer\Exception("Invalid \PhpOffice\PhpSpreadsheet\Worksheet object passed.");
77
    }
78
79
    /**
80
     * Write string table to XML format.
81
     *
82
     * @param string[] $pStringTable
83
     *
84
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
85
     *
86
     * @return string XML Output
87
     */
88 55
    public function writeStringTable(array $pStringTable)
89
    {
90
        // Create XML writer
91 55
        $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...
92 55 View Code Duplication
        if ($this->getParentWriter()->getUseDiskCaching()) {
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 getUseDiskCaching() does only exist in the following implementations of said interface: PhpOffice\PhpSpreadsheet\Writer\BaseWriter, PhpOffice\PhpSpreadsheet\Writer\Csv, PhpOffice\PhpSpreadsheet\Writer\Html, PhpOffice\PhpSpreadsheet\Writer\Ods, PhpOffice\PhpSpreadsheet\Writer\Pdf\Core, PhpOffice\PhpSpreadsheet\Writer\Pdf\DomPDF, PhpOffice\PhpSpreadsheet\Writer\Pdf\MPDF, PhpOffice\PhpSpreadsheet\Writer\Pdf\TcPDF, PhpOffice\PhpSpreadsheet\Writer\Xls, 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...
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...
93
            $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\Html, PhpOffice\PhpSpreadsheet\Writer\Ods, PhpOffice\PhpSpreadsheet\Writer\Pdf\Core, PhpOffice\PhpSpreadsheet\Writer\Pdf\DomPDF, PhpOffice\PhpSpreadsheet\Writer\Pdf\MPDF, PhpOffice\PhpSpreadsheet\Writer\Pdf\TcPDF, PhpOffice\PhpSpreadsheet\Writer\Xls, 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...
94
        } else {
95 55
            $objWriter = new \PhpOffice\PhpSpreadsheet\Shared\XMLWriter(\PhpOffice\PhpSpreadsheet\Shared\XMLWriter::STORAGE_MEMORY);
96
        }
97
98
        // XML header
99 55
        $objWriter->startDocument('1.0', 'UTF-8', 'yes');
100
101
        // String table
102 55
        $objWriter->startElement('sst');
103 55
        $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
104 55
        $objWriter->writeAttribute('uniqueCount', count($pStringTable));
105
106
        // Loop through string table
107 55
        foreach ($pStringTable as $textElement) {
108 50
            $objWriter->startElement('si');
109
110 50
            if (!$textElement instanceof \PhpOffice\PhpSpreadsheet\RichText) {
111 49
                $textToWrite = \PhpOffice\PhpSpreadsheet\Shared\StringHelper::controlCharacterPHP2OOXML($textElement);
112 49
                $objWriter->startElement('t');
113 49
                if ($textToWrite !== trim($textToWrite)) {
114 1
                    $objWriter->writeAttribute('xml:space', 'preserve');
115
                }
116 49
                $objWriter->writeRawData($textToWrite);
117 49
                $objWriter->endElement();
118
            } elseif ($textElement instanceof \PhpOffice\PhpSpreadsheet\RichText) {
119 10
                $this->writeRichText($objWriter, $textElement);
120
            }
121
122 50
            $objWriter->endElement();
123
        }
124
125 55
        $objWriter->endElement();
126
127 55
        return $objWriter->getData();
128
    }
129
130
    /**
131
     * Write Rich Text.
132
     *
133
     * @param \PhpOffice\PhpSpreadsheet\Shared\XMLWriter $objWriter XML Writer
134
     * @param \PhpOffice\PhpSpreadsheet\RichText $pRichText Rich text
135
     * @param string $prefix Optional Namespace prefix
136
     *
137
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
138
     */
139 13
    public function writeRichText(\PhpOffice\PhpSpreadsheet\Shared\XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\RichText $pRichText, $prefix = null)
140
    {
141 13
        if ($prefix !== null) {
142
            $prefix .= ':';
143
        }
144
145
        // Loop through rich text elements
146 13
        $elements = $pRichText->getRichTextElements();
147 13
        foreach ($elements as $element) {
148
            // r
149 13
            $objWriter->startElement($prefix . 'r');
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
     *
222
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
223
     */
224 13
    public function writeRichTextForCharts(\PhpOffice\PhpSpreadsheet\Shared\XMLWriter $objWriter, $pRichText = null, $prefix = null)
225
    {
226 13
        if (!$pRichText instanceof \PhpOffice\PhpSpreadsheet\RichText) {
227 12
            $textRun = $pRichText;
228 12
            $pRichText = new \PhpOffice\PhpSpreadsheet\RichText();
229 12
            $pRichText->createTextRun($textRun);
230
        }
231
232 13
        if ($prefix !== null) {
233 13
            $prefix .= ':';
234
        }
235
236
        // Loop through rich text elements
237 13
        $elements = $pRichText->getRichTextElements();
238 13
        foreach ($elements as $element) {
239
            // r
240 13
            $objWriter->startElement($prefix . 'r');
241
242
            // rPr
243 13
            $objWriter->startElement($prefix . 'rPr');
244
245
            // Bold
246 13
            $objWriter->writeAttribute('b', ($element->getFont()->getBold() ? 1 : 0));
247
            // Italic
248 13
            $objWriter->writeAttribute('i', ($element->getFont()->getItalic() ? 1 : 0));
249
            // Underline
250 13
            $underlineType = $element->getFont()->getUnderline();
251
            switch ($underlineType) {
252 13
                case 'single':
253 1
                    $underlineType = 'sng';
254 1
                    break;
255 13
                case 'double':
256 1
                    $underlineType = 'dbl';
257 1
                    break;
258
            }
259 13
            $objWriter->writeAttribute('u', $underlineType);
260
            // Strikethrough
261 13
            $objWriter->writeAttribute('strike', ($element->getFont()->getStrikethrough() ? 'sngStrike' : 'noStrike'));
262
263
            // rFont
264 13
            $objWriter->startElement($prefix . 'latin');
265 13
            $objWriter->writeAttribute('typeface', $element->getFont()->getName());
266 13
            $objWriter->endElement();
267
268 13
            $objWriter->endElement();
269
270
            // t
271 13
            $objWriter->startElement($prefix . 't');
272 13
            $objWriter->writeRawData(\PhpOffice\PhpSpreadsheet\Shared\StringHelper::controlCharacterPHP2OOXML($element->getText()));
273 13
            $objWriter->endElement();
274
275 13
            $objWriter->endElement();
276
        }
277 13
    }
278
279
    /**
280
     * Flip string table (for index searching).
281
     *
282
     * @param array $stringTable Stringtable
283
     *
284
     * @return array
285
     */
286 55
    public function flipStringTable(array $stringTable)
287
    {
288
        // Return value
289 55
        $returnValue = [];
290
291
        // Loop through stringtable and add flipped items to $returnValue
292 55
        foreach ($stringTable as $key => $value) {
293 50
            if (!$value instanceof \PhpOffice\PhpSpreadsheet\RichText) {
294 49
                $returnValue[$value] = $key;
295
            } elseif ($value instanceof \PhpOffice\PhpSpreadsheet\RichText) {
296 10
                $returnValue[$value->getHashCode()] = $key;
297
            }
298
        }
299
300 55
        return $returnValue;
301
    }
302
}
303