• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

PHPOffice / PHPWord / 12909093108

22 Jan 2025 01:18PM UTC coverage: 96.921% (-0.03%) from 96.947%
12909093108

Pull #2697

github

web-flow
Merge 9f75457b3 into 136f5499f
Pull Request #2697: Writer Word2007: Support for padding in Table Cell

73 of 79 new or added lines in 3 files covered. (92.41%)

3 existing lines in 1 file now uncovered.

11993 of 12374 relevant lines covered (96.92%)

34.23 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.91
/src/PhpWord/Shared/Html.php
1
<?php
2

3
/**
4
 * This file is part of PHPWord - A pure PHP library for reading and writing
5
 * word processing documents.
6
 *
7
 * PHPWord is free software distributed under the terms of the GNU Lesser
8
 * General Public License version 3 as published by the Free Software Foundation.
9
 *
10
 * For the full copyright and license information, please read the LICENSE
11
 * file that was distributed with this source code. For the full list of
12
 * contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
13
 *
14
 * @see         https://github.com/PHPOffice/PHPWord
15
 *
16
 * @license     http://www.gnu.org/licenses/lgpl.txt LGPL version 3
17
 */
18

19
namespace PhpOffice\PhpWord\Shared;
20

21
use DOMAttr;
22
use DOMDocument;
23
use DOMNode;
24
use DOMXPath;
25
use Exception;
26
use PhpOffice\PhpWord\Element\AbstractContainer;
27
use PhpOffice\PhpWord\Element\Row;
28
use PhpOffice\PhpWord\Element\Table;
29
use PhpOffice\PhpWord\Settings;
30
use PhpOffice\PhpWord\SimpleType\Jc;
31
use PhpOffice\PhpWord\SimpleType\NumberFormat;
32
use PhpOffice\PhpWord\Style\Paragraph;
33

34
/**
35
 * Common Html functions.
36
 *
37
 * @SuppressWarnings(PHPMD.UnusedPrivateMethod) For readWPNode
38
 */
39
class Html
40
{
41
    private const RGB_REGEXP = '/^\s*rgb\s*[(]\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*[)]\s*$/';
42

43
    protected static $listIndex = 0;
44

45
    protected static $xpath;
46

47
    protected static $options;
48

49
    /**
50
     * @var Css
51
     */
52
    protected static $css;
53

54
    /**
55
     * Add HTML parts.
56
     *
57
     * Note: $stylesheet parameter is removed to avoid PHPMD error for unused parameter
58
     * Warning: Do not pass user-generated HTML here, as that would allow an attacker to read arbitrary
59
     * files or perform server-side request forgery by passing local file paths or URLs in <img>.
60
     *
61
     * @param AbstractContainer $element Where the parts need to be added
62
     * @param string $html The code to parse
63
     * @param bool $fullHTML If it's a full HTML, no need to add 'body' tag
64
     * @param bool $preserveWhiteSpace If false, the whitespaces between nodes will be removed
65
     */
66
    public static function addHtml($element, $html, $fullHTML = false, $preserveWhiteSpace = true, $options = null): void
67
    {
68
        /*
69
         * @todo parse $stylesheet for default styles.  Should result in an array based on id, class and element,
70
         * which could be applied when such an element occurs in the parseNode function.
71
         */
72
        static::$options = $options;
59✔
73

74
        // Preprocess: remove all line ends, decode HTML entity,
75
        // fix ampersand and angle brackets and add body tag for HTML fragments
76
        $html = str_replace(["\n", "\r"], '', $html);
59✔
77
        $html = str_replace(['&lt;', '&gt;', '&amp;', '&quot;'], ['_lt_', '_gt_', '_amp_', '_quot_'], $html);
59✔
78
        $html = html_entity_decode($html, ENT_QUOTES, 'UTF-8');
59✔
79
        $html = str_replace('&', '&amp;', $html);
59✔
80
        $html = str_replace(['_lt_', '_gt_', '_amp_', '_quot_'], ['&lt;', '&gt;', '&amp;', '&quot;'], $html);
59✔
81

82
        if (false === $fullHTML) {
59✔
83
            $html = '<body>' . $html . '</body>';
57✔
84
        }
85

86
        // Load DOM
87
        if (\PHP_VERSION_ID < 80000) {
59✔
88
            $orignalLibEntityLoader = libxml_disable_entity_loader(true);
59✔
89
        }
90
        $dom = new DOMDocument();
59✔
91
        $dom->preserveWhiteSpace = $preserveWhiteSpace;
59✔
92
        $dom->loadXML($html);
59✔
93
        static::$xpath = new DOMXPath($dom);
59✔
94
        $node = $dom->getElementsByTagName('body');
59✔
95

96
        static::parseNode($node->item(0), $element);
59✔
97
        if (\PHP_VERSION_ID < 80000) {
58✔
98
            libxml_disable_entity_loader($orignalLibEntityLoader);
58✔
99
        }
100
    }
101

102
    /**
103
     * parse Inline style of a node.
104
     *
105
     * @param DOMNode $node Node to check on attributes and to compile a style array
106
     * @param array<string, mixed> $styles is supplied, the inline style attributes are added to the already existing style
107
     *
108
     * @return array
109
     */
110
    protected static function parseInlineStyle($node, $styles = [])
111
    {
112
        if (XML_ELEMENT_NODE == $node->nodeType) {
58✔
113
            $attributes = $node->attributes; // get all the attributes(eg: id, class)
58✔
114

115
            $attributeDir = $attributes->getNamedItem('dir');
58✔
116
            $attributeDirValue = $attributeDir ? $attributeDir->nodeValue : '';
58✔
117
            $bidi = $attributeDirValue === 'rtl';
58✔
118
            foreach ($attributes as $attribute) {
58✔
119
                $val = $attribute->value;
42✔
120
                switch (strtolower($attribute->name)) {
42✔
121
                    case 'align':
42✔
122
                        $styles['alignment'] = self::mapAlign(trim($val), $bidi);
2✔
123

124
                        break;
2✔
125
                    case 'lang':
42✔
126
                        $styles['lang'] = $val;
1✔
127

128
                        break;
1✔
129
                    case 'width':
41✔
130
                        // tables, cells
131
                        $val = $val === 'auto' ? '100%' : $val;
9✔
132
                        if (false !== strpos($val, '%')) {
9✔
133
                            // e.g. <table width="100%"> or <td width="50%">
134
                            $styles['width'] = (int) $val * 50;
5✔
135
                            $styles['unit'] = \PhpOffice\PhpWord\SimpleType\TblWidth::PERCENT;
5✔
136
                        } else {
137
                            // e.g. <table width="250> where "250" = 250px (always pixels)
138
                            $styles['width'] = Converter::pixelToTwip(self::convertHtmlSize($val));
4✔
139
                            $styles['unit'] = \PhpOffice\PhpWord\SimpleType\TblWidth::TWIP;
4✔
140
                        }
141

142
                        break;
9✔
143
                    case 'cellspacing':
36✔
144
                        // tables e.g. <table cellspacing="2">,  where "2" = 2px (always pixels)
145
                        $styles['cellSpacing'] = Converter::pixelToTwip(self::convertHtmlSize($val));
1✔
146

147
                        break;
1✔
148
                    case 'bgcolor':
36✔
149
                        // tables, rows, cells e.g. <tr bgColor="#FF0000">
150
                        $styles['bgColor'] = self::convertRgb($val);
3✔
151

152
                        break;
3✔
153
                    case 'valign':
35✔
154
                        // cells e.g. <td valign="middle">
155
                        if (preg_match('#(?:top|bottom|middle|baseline)#i', $val, $matches)) {
1✔
156
                            $styles['valign'] = self::mapAlignVertical($matches[0]);
1✔
157
                        }
158

159
                        break;
1✔
160
                }
161
            }
162

163
            $attributeIdentifier = $attributes->getNamedItem('id');
58✔
164
            if ($attributeIdentifier && self::$css) {
58✔
165
                $styles = self::parseStyleDeclarations(self::$css->getStyle('#' . $attributeIdentifier->nodeValue), $styles);
×
166
            }
167

168
            $attributeClass = $attributes->getNamedItem('class');
58✔
169
            if ($attributeClass) {
58✔
170
                if (self::$css) {
2✔
171
                    $styles = self::parseStyleDeclarations(self::$css->getStyle('.' . $attributeClass->nodeValue), $styles);
2✔
172
                }
173
                $styles['className'] = $attributeClass->nodeValue;
2✔
174
            }
175

176
            $attributeStyle = $attributes->getNamedItem('style');
58✔
177
            if ($attributeStyle) {
58✔
178
                $styles = self::parseStyle($attributeStyle, $styles);
30✔
179
            }
180
        }
181

182
        return $styles;
58✔
183
    }
184

185
    /**
186
     * Parse a node and add a corresponding element to the parent element.
187
     *
188
     * @param DOMNode $node node to parse
189
     * @param AbstractContainer $element object to add an element corresponding with the node
190
     * @param array $styles Array with all styles
191
     * @param array $data Array to transport data to a next level in the DOM tree, for example level of listitems
192
     */
193
    protected static function parseNode($node, $element, $styles = [], $data = []): void
194
    {
195
        if ($node->nodeName == 'style') {
59✔
196
            self::$css = new Css($node->textContent);
2✔
197
            self::$css->process();
2✔
198

199
            return;
2✔
200
        }
201

202
        // Populate styles array
203
        $styleTypes = ['font', 'paragraph', 'list', 'table', 'row', 'cell'];
59✔
204
        foreach ($styleTypes as $styleType) {
59✔
205
            if (!isset($styles[$styleType])) {
59✔
206
                $styles[$styleType] = [];
59✔
207
            }
208
        }
209

210
        // Node mapping table
211
        $nodes = [
59✔
212
            // $method        $node   $element    $styles     $data   $argument1      $argument2
213
            'p' => ['Paragraph',   $node,  $element,   $styles,    null,   null,           null],
59✔
214
            'h1' => ['Heading',     null,   $element,   $styles,    null,   'Heading1',     null],
59✔
215
            'h2' => ['Heading',     null,   $element,   $styles,    null,   'Heading2',     null],
59✔
216
            'h3' => ['Heading',     null,   $element,   $styles,    null,   'Heading3',     null],
59✔
217
            'h4' => ['Heading',     null,   $element,   $styles,    null,   'Heading4',     null],
59✔
218
            'h5' => ['Heading',     null,   $element,   $styles,    null,   'Heading5',     null],
59✔
219
            'h6' => ['Heading',     null,   $element,   $styles,    null,   'Heading6',     null],
59✔
220
            '#text' => ['Text',        $node,  $element,   $styles,    null,   null,           null],
59✔
221
            'strong' => ['Property',    null,   null,       $styles,    null,   'bold',         true],
59✔
222
            'b' => ['Property',    null,   null,       $styles,    null,   'bold',         true],
59✔
223
            'em' => ['Property',    null,   null,       $styles,    null,   'italic',       true],
59✔
224
            'i' => ['Property',    null,   null,       $styles,    null,   'italic',       true],
59✔
225
            'u' => ['Property',    null,   null,       $styles,    null,   'underline',    'single'],
59✔
226
            'sup' => ['Property',    null,   null,       $styles,    null,   'superScript',  true],
59✔
227
            'sub' => ['Property',    null,   null,       $styles,    null,   'subScript',    true],
59✔
228
            'span' => ['Span',        $node,  null,       $styles,    null,   null,           null],
59✔
229
            'font' => ['Span',        $node,  null,       $styles,    null,   null,           null],
59✔
230
            'table' => ['Table',       $node,  $element,   $styles,    null,   null,           null],
59✔
231
            'tr' => ['Row',         $node,  $element,   $styles,    null,   null,           null],
59✔
232
            'td' => ['Cell',        $node,  $element,   $styles,    null,   null,           null],
59✔
233
            'th' => ['Cell',        $node,  $element,   $styles,    null,   null,           null],
59✔
234
            'ul' => ['List',        $node,  $element,   $styles,    $data,  null,           null],
59✔
235
            'ol' => ['List',        $node,  $element,   $styles,    $data,  null,           null],
59✔
236
            'li' => ['ListItem',    $node,  $element,   $styles,    $data,  null,           null],
59✔
237
            'img' => ['Image',       $node,  $element,   $styles,    null,   null,           null],
59✔
238
            'br' => ['LineBreak',   null,   $element,   $styles,    null,   null,           null],
59✔
239
            'a' => ['Link',        $node,  $element,   $styles,    null,   null,           null],
59✔
240
            'input' => ['Input',       $node,  $element,   $styles,    null,   null,           null],
59✔
241
            'hr' => ['HorizRule',   $node,  $element,   $styles,    null,   null,           null],
59✔
242
        ];
59✔
243

244
        $newElement = null;
59✔
245
        $keys = ['node', 'element', 'styles', 'data', 'argument1', 'argument2'];
59✔
246

247
        if (isset($nodes[$node->nodeName])) {
59✔
248
            // Execute method based on node mapping table and return $newElement or null
249
            // Arguments are passed by reference
250
            $arguments = [];
59✔
251
            $args = [];
59✔
252
            [$method, $args[0], $args[1], $args[2], $args[3], $args[4], $args[5]] = $nodes[$node->nodeName];
59✔
253
            for ($i = 0; $i <= 5; ++$i) {
59✔
254
                if ($args[$i] !== null) {
59✔
255
                    $arguments[$keys[$i]] = &$args[$i];
59✔
256
                }
257
            }
258
            $method = "parse{$method}";
59✔
259
            $newElement = call_user_func_array(['PhpOffice\PhpWord\Shared\Html', $method], array_values($arguments));
59✔
260

261
            // Retrieve back variables from arguments
262
            foreach ($keys as $key) {
59✔
263
                if (array_key_exists($key, $arguments)) {
59✔
264
                    $$key = $arguments[$key];
59✔
265
                }
266
            }
267
        }
268

269
        if ($newElement === null) {
59✔
270
            $newElement = $element;
59✔
271
        }
272

273
        static::parseChildNodes($node, $newElement, $styles, $data);
59✔
274
    }
275

276
    /**
277
     * Parse child nodes.
278
     *
279
     * @param DOMNode $node
280
     * @param AbstractContainer|Row|Table $element
281
     * @param array $styles
282
     * @param array $data
283
     */
284
    protected static function parseChildNodes($node, $element, $styles, $data): void
285
    {
286
        if ('li' != $node->nodeName) {
59✔
287
            $cNodes = $node->childNodes;
59✔
288
            if (!empty($cNodes)) {
59✔
289
                foreach ($cNodes as $cNode) {
59✔
290
                    if ($element instanceof AbstractContainer || $element instanceof Table || $element instanceof Row) {
59✔
291
                        self::parseNode($cNode, $element, $styles, $data);
59✔
292
                    }
293
                }
294
            }
295
        }
296
    }
297

298
    /**
299
     * Parse paragraph node.
300
     *
301
     * @param DOMNode $node
302
     * @param AbstractContainer $element
303
     * @param array &$styles
304
     *
305
     * @return \PhpOffice\PhpWord\Element\PageBreak|\PhpOffice\PhpWord\Element\TextRun
306
     */
307
    protected static function parseParagraph($node, $element, &$styles)
308
    {
309
        $styles['paragraph'] = self::recursiveParseStylesInHierarchy($node, $styles['paragraph']);
31✔
310
        if (isset($styles['paragraph']['isPageBreak']) && $styles['paragraph']['isPageBreak']) {
31✔
311
            return $element->addPageBreak();
1✔
312
        }
313

314
        return $element->addTextRun($styles['paragraph']);
30✔
315
    }
316

317
    /**
318
     * Parse input node.
319
     *
320
     * @param DOMNode $node
321
     * @param AbstractContainer $element
322
     * @param array &$styles
323
     */
324
    protected static function parseInput($node, $element, &$styles): void
325
    {
326
        $attributes = $node->attributes;
1✔
327
        if (null === $attributes->getNamedItem('type')) {
1✔
328
            return;
×
329
        }
330

331
        $inputType = $attributes->getNamedItem('type')->nodeValue;
1✔
332
        switch ($inputType) {
333
            case 'checkbox':
1✔
334
                $checked = ($checked = $attributes->getNamedItem('checked')) && $checked->nodeValue === 'true' ? true : false;
1✔
335
                $textrun = $element->addTextRun($styles['paragraph']);
1✔
336
                $textrun->addFormField('checkbox')->setValue($checked);
1✔
337

338
                break;
1✔
339
        }
340
    }
341

342
    /**
343
     * Parse heading node.
344
     *
345
     * @param AbstractContainer $element
346
     * @param array &$styles
347
     * @param string $argument1 Name of heading style
348
     *
349
     * @return \PhpOffice\PhpWord\Element\TextRun
350
     *
351
     * @todo Think of a clever way of defining header styles, now it is only based on the assumption, that
352
     * Heading1 - Heading6 are already defined somewhere
353
     */
354
    protected static function parseHeading($element, &$styles, $argument1)
355
    {
356
        $styles['paragraph'] = $argument1;
2✔
357
        $newElement = $element->addTextRun($styles['paragraph']);
2✔
358

359
        return $newElement;
2✔
360
    }
361

362
    /**
363
     * Parse text node.
364
     *
365
     * @param DOMNode $node
366
     * @param AbstractContainer $element
367
     * @param array &$styles
368
     */
369
    protected static function parseText($node, $element, &$styles): void
370
    {
371
        $styles['font'] = self::recursiveParseStylesInHierarchy($node, $styles['font']);
44✔
372

373
        //alignment applies on paragraph, not on font. Let's copy it there
374
        if (isset($styles['font']['alignment']) && is_array($styles['paragraph'])) {
44✔
375
            $styles['paragraph']['alignment'] = $styles['font']['alignment'];
8✔
376
        }
377

378
        if (is_callable([$element, 'addText'])) {
44✔
379
            $element->addText($node->nodeValue, $styles['font'], $styles['paragraph']);
44✔
380
        }
381
    }
382

383
    /**
384
     * Parse property node.
385
     *
386
     * @param array &$styles
387
     * @param string $argument1 Style name
388
     * @param string $argument2 Style value
389
     */
390
    protected static function parseProperty(&$styles, $argument1, $argument2): void
391
    {
392
        $styles['font'][$argument1] = $argument2;
6✔
393
    }
394

395
    /**
396
     * Parse span node.
397
     *
398
     * @param DOMNode $node
399
     * @param array &$styles
400
     */
401
    protected static function parseSpan($node, &$styles): void
402
    {
403
        self::parseInlineStyle($node, $styles['font']);
12✔
404
    }
405

406
    /**
407
     * Parse table node.
408
     *
409
     * @param DOMNode $node
410
     * @param AbstractContainer $element
411
     * @param array &$styles
412
     *
413
     * @return Table $element
414
     *
415
     * @todo As soon as TableItem, RowItem and CellItem support relative width and height
416
     */
417
    protected static function parseTable($node, $element, &$styles)
418
    {
419
        $elementStyles = self::parseInlineStyle($node, $styles['table']);
16✔
420

421
        $newElement = $element->addTable($elementStyles);
16✔
422

423
        // Add style name from CSS Class
424
        if (isset($elementStyles['className'])) {
16✔
425
            $newElement->getStyle()->setStyleName($elementStyles['className']);
1✔
426
        }
427

428
        $attributes = $node->attributes;
16✔
429
        if ($attributes->getNamedItem('border')) {
16✔
430
            $border = (int) $attributes->getNamedItem('border')->nodeValue;
1✔
431
            $newElement->getStyle()->setBorderSize(Converter::pixelToTwip($border));
1✔
432
        }
433

434
        return $newElement;
16✔
435
    }
436

437
    /**
438
     * Parse a table row.
439
     *
440
     * @param DOMNode $node
441
     * @param Table $element
442
     * @param array &$styles
443
     *
444
     * @return Row $element
445
     */
446
    protected static function parseRow($node, $element, &$styles)
447
    {
448
        $rowStyles = self::parseInlineStyle($node, $styles['row']);
16✔
449
        if ($node->parentNode->nodeName == 'thead') {
16✔
450
            $rowStyles['tblHeader'] = true;
2✔
451
        }
452

453
        // set cell height to control row heights
454
        $height = $rowStyles['height'] ?? null;
16✔
455
        unset($rowStyles['height']); // would not apply
16✔
456

457
        return $element->addRow($height, $rowStyles);
16✔
458
    }
459

460
    /**
461
     * Parse table cell.
462
     *
463
     * @param DOMNode $node
464
     * @param Table $element
465
     * @param array &$styles
466
     *
467
     * @return \PhpOffice\PhpWord\Element\Cell|\PhpOffice\PhpWord\Element\TextRun $element
468
     */
469
    protected static function parseCell($node, $element, &$styles)
470
    {
471
        $cellStyles = self::recursiveParseStylesInHierarchy($node, $styles['cell']);
16✔
472

473
        $colspan = $node->getAttribute('colspan');
16✔
474
        if (!empty($colspan)) {
16✔
475
            $cellStyles['gridSpan'] = $colspan - 0;
2✔
476
        }
477

478
        // set cell width to control column widths
479
        $width = $cellStyles['width'] ?? null;
16✔
480
        unset($cellStyles['width']); // would not apply
16✔
481
        $cell = $element->addCell($width, $cellStyles);
16✔
482

483
        if (self::shouldAddTextRun($node)) {
16✔
484
            return $cell->addTextRun(self::filterOutNonInheritedStyles(self::parseInlineStyle($node, $styles['paragraph'])));
16✔
485
        }
486

487
        return $cell;
3✔
488
    }
489

490
    /**
491
     * Checks if $node contains an HTML element that cannot be added to TextRun.
492
     *
493
     * @return bool Returns true if the node contains an HTML element that cannot be added to TextRun
494
     */
495
    protected static function shouldAddTextRun(DOMNode $node)
496
    {
497
        $containsBlockElement = self::$xpath->query('.//table|./p|./ul|./ol|./h1|./h2|./h3|./h4|./h5|./h6', $node)->length > 0;
16✔
498
        if ($containsBlockElement) {
16✔
499
            return false;
3✔
500
        }
501

502
        return true;
16✔
503
    }
504

505
    /**
506
     * Recursively parses styles on parent nodes
507
     * TODO if too slow, add caching of parent nodes, !! everything is static here so watch out for concurrency !!
508
     */
509
    protected static function recursiveParseStylesInHierarchy(DOMNode $node, array $style)
510
    {
511
        $parentStyle = [];
58✔
512
        if ($node->parentNode != null && XML_ELEMENT_NODE == $node->parentNode->nodeType) {
58✔
513
            $parentStyle = self::recursiveParseStylesInHierarchy($node->parentNode, []);
58✔
514
        }
515
        if ($node->nodeName === '#text') {
58✔
516
            $parentStyle = array_merge($parentStyle, $style);
44✔
517
        } else {
518
            $parentStyle = self::filterOutNonInheritedStyles($parentStyle);
58✔
519
        }
520
        $style = self::parseInlineStyle($node, $parentStyle);
58✔
521

522
        return $style;
58✔
523
    }
524

525
    /**
526
     * Removes non-inherited styles from array.
527
     */
528
    protected static function filterOutNonInheritedStyles(array $styles)
529
    {
530
        $nonInheritedStyles = [
58✔
531
            'borderSize',
58✔
532
            'borderTopSize',
58✔
533
            'borderRightSize',
58✔
534
            'borderBottomSize',
58✔
535
            'borderLeftSize',
58✔
536
            'borderColor',
58✔
537
            'borderTopColor',
58✔
538
            'borderRightColor',
58✔
539
            'borderBottomColor',
58✔
540
            'borderLeftColor',
58✔
541
            'borderStyle',
58✔
542
            'spaceAfter',
58✔
543
            'spaceBefore',
58✔
544
            'underline',
58✔
545
            'strikethrough',
58✔
546
            'hidden',
58✔
547
        ];
58✔
548

549
        $styles = array_diff_key($styles, array_flip($nonInheritedStyles));
58✔
550

551
        return $styles;
58✔
552
    }
553

554
    /**
555
     * Parse list node.
556
     *
557
     * @param DOMNode $node
558
     * @param AbstractContainer $element
559
     * @param array &$styles
560
     * @param array &$data
561
     */
562
    protected static function parseList($node, $element, &$styles, &$data)
563
    {
564
        $isOrderedList = $node->nodeName === 'ol';
7✔
565
        if (isset($data['listdepth'])) {
7✔
566
            ++$data['listdepth'];
3✔
567
        } else {
568
            $data['listdepth'] = 0;
7✔
569
            $styles['list'] = 'listStyle_' . self::$listIndex++;
7✔
570
            $style = $element->getPhpWord()->addNumberingStyle($styles['list'], self::getListStyle($isOrderedList));
7✔
571

572
            // extract attributes start & type e.g. <ol type="A" start="3">
573
            $start = 0;
7✔
574
            $type = '';
7✔
575
            foreach ($node->attributes as $attribute) {
7✔
576
                switch ($attribute->name) {
1✔
577
                    case 'start':
1✔
578
                        $start = (int) $attribute->value;
1✔
579

580
                        break;
1✔
581
                    case 'type':
1✔
582
                        $type = $attribute->value;
1✔
583

584
                        break;
1✔
585
                }
586
            }
587

588
            $levels = $style->getLevels();
7✔
589
            /** @var \PhpOffice\PhpWord\Style\NumberingLevel */
590
            $level = $levels[0];
7✔
591
            if ($start > 0) {
7✔
592
                $level->setStart($start);
1✔
593
            }
594
            $type = $type ? self::mapListType($type) : null;
7✔
595
            if ($type) {
7✔
596
                $level->setFormat($type);
1✔
597
            }
598
        }
599
        if ($node->parentNode->nodeName === 'li') {
7✔
600
            return $element->getParent();
1✔
601
        }
602
    }
603

604
    /**
605
     * @param bool $isOrderedList
606
     *
607
     * @return array
608
     */
609
    protected static function getListStyle($isOrderedList)
610
    {
611
        if ($isOrderedList) {
7✔
612
            return [
5✔
613
                'type' => 'multilevel',
5✔
614
                'levels' => [
5✔
615
                    ['format' => NumberFormat::DECIMAL,      'text' => '%1.', 'alignment' => 'left',  'tabPos' => 720,  'left' => 720,  'hanging' => 360],
5✔
616
                    ['format' => NumberFormat::LOWER_LETTER, 'text' => '%2.', 'alignment' => 'left',  'tabPos' => 1440, 'left' => 1440, 'hanging' => 360],
5✔
617
                    ['format' => NumberFormat::LOWER_ROMAN,  'text' => '%3.', 'alignment' => 'right', 'tabPos' => 2160, 'left' => 2160, 'hanging' => 180],
5✔
618
                    ['format' => NumberFormat::DECIMAL,      'text' => '%4.', 'alignment' => 'left',  'tabPos' => 2880, 'left' => 2880, 'hanging' => 360],
5✔
619
                    ['format' => NumberFormat::LOWER_LETTER, 'text' => '%5.', 'alignment' => 'left',  'tabPos' => 3600, 'left' => 3600, 'hanging' => 360],
5✔
620
                    ['format' => NumberFormat::LOWER_ROMAN,  'text' => '%6.', 'alignment' => 'right', 'tabPos' => 4320, 'left' => 4320, 'hanging' => 180],
5✔
621
                    ['format' => NumberFormat::DECIMAL,      'text' => '%7.', 'alignment' => 'left',  'tabPos' => 5040, 'left' => 5040, 'hanging' => 360],
5✔
622
                    ['format' => NumberFormat::LOWER_LETTER, 'text' => '%8.', 'alignment' => 'left',  'tabPos' => 5760, 'left' => 5760, 'hanging' => 360],
5✔
623
                    ['format' => NumberFormat::LOWER_ROMAN,  'text' => '%9.', 'alignment' => 'right', 'tabPos' => 6480, 'left' => 6480, 'hanging' => 180],
5✔
624
                ],
5✔
625
            ];
5✔
626
        }
627

628
        return [
4✔
629
            'type' => 'hybridMultilevel',
4✔
630
            'levels' => [
4✔
631
                ['format' => NumberFormat::BULLET, 'text' => '•', 'alignment' => 'left', 'tabPos' => 720,  'left' => 720,  'hanging' => 360, 'font' => 'Symbol',      'hint' => 'default'],
4✔
632
                ['format' => NumberFormat::BULLET, 'text' => 'â—¦',  'alignment' => 'left', 'tabPos' => 1440, 'left' => 1440, 'hanging' => 360, 'font' => 'Courier New', 'hint' => 'default'],
4✔
633
                ['format' => NumberFormat::BULLET, 'text' => '•', 'alignment' => 'left', 'tabPos' => 2160, 'left' => 2160, 'hanging' => 360, 'font' => 'Wingdings',   'hint' => 'default'],
4✔
634
                ['format' => NumberFormat::BULLET, 'text' => '•', 'alignment' => 'left', 'tabPos' => 2880, 'left' => 2880, 'hanging' => 360, 'font' => 'Symbol',      'hint' => 'default'],
4✔
635
                ['format' => NumberFormat::BULLET, 'text' => 'â—¦',  'alignment' => 'left', 'tabPos' => 3600, 'left' => 3600, 'hanging' => 360, 'font' => 'Courier New', 'hint' => 'default'],
4✔
636
                ['format' => NumberFormat::BULLET, 'text' => '•', 'alignment' => 'left', 'tabPos' => 4320, 'left' => 4320, 'hanging' => 360, 'font' => 'Wingdings',   'hint' => 'default'],
4✔
637
                ['format' => NumberFormat::BULLET, 'text' => '•', 'alignment' => 'left', 'tabPos' => 5040, 'left' => 5040, 'hanging' => 360, 'font' => 'Symbol',      'hint' => 'default'],
4✔
638
                ['format' => NumberFormat::BULLET, 'text' => 'â—¦',  'alignment' => 'left', 'tabPos' => 5760, 'left' => 5760, 'hanging' => 360, 'font' => 'Courier New', 'hint' => 'default'],
4✔
639
                ['format' => NumberFormat::BULLET, 'text' => '•', 'alignment' => 'left', 'tabPos' => 6480, 'left' => 6480, 'hanging' => 360, 'font' => 'Wingdings',   'hint' => 'default'],
4✔
640
            ],
4✔
641
        ];
4✔
642
    }
643

644
    /**
645
     * Parse list item node.
646
     *
647
     * @param DOMNode $node
648
     * @param AbstractContainer $element
649
     * @param array &$styles
650
     * @param array $data
651
     *
652
     * @todo This function is almost the same like `parseChildNodes`. Merged?
653
     * @todo As soon as ListItem inherits from AbstractContainer or TextRun delete parsing part of childNodes
654
     */
655
    protected static function parseListItem($node, $element, &$styles, $data): void
656
    {
657
        $cNodes = $node->childNodes;
7✔
658
        if (!empty($cNodes)) {
7✔
659
            $listRun = $element->addListItemRun($data['listdepth'], $styles['list'], $styles['paragraph']);
7✔
660
            foreach ($cNodes as $cNode) {
7✔
661
                self::parseNode($cNode, $listRun, $styles, $data);
7✔
662
            }
663
        }
664
    }
665

666
    /**
667
     * Parse style.
668
     *
669
     * @param DOMAttr $attribute
670
     * @param array $styles
671
     *
672
     * @return array
673
     */
674
    protected static function parseStyle($attribute, $styles)
675
    {
676
        $properties = explode(';', trim($attribute->value, " \t\n\r\0\x0B;"));
30✔
677

678
        $selectors = [];
30✔
679
        foreach ($properties as $property) {
30✔
680
            [$cKey, $cValue] = array_pad(explode(':', $property, 2), 2, null);
30✔
681
            $selectors[strtolower(trim($cKey))] = trim($cValue ?? '');
30✔
682
        }
683

684
        return self::parseStyleDeclarations($selectors, $styles);
30✔
685
    }
686

687
    protected static function parseStyleDeclarations(array $selectors, array $styles)
688
    {
689
        $bidi = ($selectors['direction'] ?? '') === 'rtl';
32✔
690
        foreach ($selectors as $property => $value) {
32✔
691
            switch ($property) {
692
                case 'text-decoration':
32✔
693
                    switch ($value) {
694
                        case 'underline':
4✔
695
                            $styles['underline'] = 'single';
3✔
696

697
                            break;
3✔
698
                        case 'line-through':
1✔
699
                            $styles['strikethrough'] = true;
1✔
700

701
                            break;
1✔
702
                    }
703

704
                    break;
4✔
705
                case 'text-align':
30✔
706
                    $styles['alignment'] = self::mapAlign($value, $bidi);
7✔
707

708
                    break;
7✔
709
                case 'display':
29✔
710
                    $styles['hidden'] = $value === 'none' || $value === 'hidden';
1✔
711

712
                    break;
1✔
713
                case 'direction':
28✔
714
                    $styles['rtl'] = $value === 'rtl';
3✔
715
                    $styles['bidi'] = $value === 'rtl';
3✔
716

717
                    break;
3✔
718
                case 'font-size':
25✔
719
                    $styles['size'] = Converter::cssToPoint($value);
5✔
720

721
                    break;
5✔
722
                case 'font-family':
22✔
723
                    $value = array_map('trim', explode(',', $value));
5✔
724
                    $styles['name'] = ucwords($value[0]);
5✔
725

726
                    break;
5✔
727
                case 'color':
18✔
728
                    $styles['color'] = self::convertRgb($value);
4✔
729

730
                    break;
4✔
731
                case 'background-color':
17✔
732
                    $styles['bgColor'] = self::convertRgb($value);
5✔
733

734
                    break;
5✔
735
                case 'line-height':
16✔
736
                    $matches = [];
1✔
737
                    if ($value === 'normal') {
1✔
738
                        $spacingLineRule = \PhpOffice\PhpWord\SimpleType\LineSpacingRule::AUTO;
1✔
739
                        $spacing = 0;
1✔
740
                    } elseif (preg_match('/([0-9]+\.?[0-9]*[a-z]+)/', $value, $matches)) {
1✔
741
                        //matches number with a unit, e.g. 12px, 15pt, 20mm, ...
742
                        $spacingLineRule = \PhpOffice\PhpWord\SimpleType\LineSpacingRule::EXACT;
1✔
743
                        $spacing = Converter::cssToTwip($matches[1]);
1✔
744
                    } elseif (preg_match('/([0-9]+)%/', $value, $matches)) {
1✔
745
                        //matches percentages
746
                        $spacingLineRule = \PhpOffice\PhpWord\SimpleType\LineSpacingRule::AUTO;
1✔
747
                        //we are subtracting 1 line height because the Spacing writer is adding one line
748
                        $spacing = ((((int) $matches[1]) / 100) * Paragraph::LINE_HEIGHT) - Paragraph::LINE_HEIGHT;
1✔
749
                    } else {
750
                        //any other, wich is a multiplier. E.g. 1.2
751
                        $spacingLineRule = \PhpOffice\PhpWord\SimpleType\LineSpacingRule::AUTO;
1✔
752
                        //we are subtracting 1 line height because the Spacing writer is adding one line
753
                        $spacing = ($value * Paragraph::LINE_HEIGHT) - Paragraph::LINE_HEIGHT;
1✔
754
                    }
755
                    $styles['spacingLineRule'] = $spacingLineRule;
1✔
756
                    $styles['line-spacing'] = $spacing;
1✔
757

758
                    break;
1✔
759
                case 'letter-spacing':
15✔
760
                    $styles['letter-spacing'] = Converter::cssToTwip($value);
1✔
761

762
                    break;
1✔
763
                case 'text-indent':
14✔
764
                    $styles['indentation']['firstLine'] = Converter::cssToTwip($value);
1✔
765

766
                    break;
1✔
767
                case 'font-weight':
13✔
768
                    $tValue = false;
3✔
769
                    if (preg_match('#bold#', $value)) {
3✔
770
                        $tValue = true; // also match bolder
3✔
771
                    }
772
                    $styles['bold'] = $tValue;
3✔
773

774
                    break;
3✔
775
                case 'font-style':
12✔
776
                    $tValue = false;
1✔
777
                    if (preg_match('#(?:italic|oblique)#', $value)) {
1✔
778
                        $tValue = true;
1✔
779
                    }
780
                    $styles['italic'] = $tValue;
1✔
781

782
                    break;
1✔
783
                case 'font-variant':
11✔
784
                    $tValue = false;
1✔
785
                    if (preg_match('#small-caps#', $value)) {
1✔
786
                        $tValue = true;
1✔
787
                    }
788
                    $styles['smallCaps'] = $tValue;
1✔
789

790
                    break;
1✔
791
                case 'margin':
10✔
792
                    $value = Converter::cssToTwip($value);
×
793
                    $styles['spaceBefore'] = $value;
×
794
                    $styles['spaceAfter'] = $value;
×
795

796
                    break;
×
797
                case 'margin-top':
10✔
798
                    // BC change: up to ver. 0.17.0 incorrectly converted to points - Converter::cssToPoint($value)
799
                    $styles['spaceBefore'] = Converter::cssToTwip($value);
2✔
800

801
                    break;
2✔
802
                case 'margin-bottom':
10✔
803
                    // BC change: up to ver. 0.17.0 incorrectly converted to points - Converter::cssToPoint($value)
804
                    $styles['spaceAfter'] = Converter::cssToTwip($value);
2✔
805

806
                    break;
2✔
807

808
                case 'padding':
9✔
809
                    $valueTop = $valueRight = $valueBottom = $valueLeft = null;
1✔
810
                    $cValue = preg_replace('# +#', ' ', trim($value));
1✔
811
                    $paddingArr = explode(' ', $cValue);
1✔
812
                    $countParams = count($paddingArr);
1✔
813
                    if ($countParams == 1) {
1✔
NEW
814
                        $valueTop = $valueRight = $valueBottom = $valueLeft = $paddingArr[0];
×
815
                    } elseif ($countParams == 2) {
1✔
NEW
816
                        $valueTop = $valueBottom = $paddingArr[0];
×
NEW
817
                        $valueRight = $valueLeft = $paddingArr[1];
×
818
                    } elseif ($countParams == 3) {
1✔
NEW
819
                        $valueTop = $paddingArr[0];
×
NEW
820
                        $valueRight = $valueLeft = $paddingArr[1];
×
NEW
821
                        $valueBottom = $paddingArr[2];
×
822
                    } elseif ($countParams == 4) {
1✔
823
                        $valueTop = $paddingArr[0];
1✔
824
                        $valueRight = $paddingArr[1];
1✔
825
                        $valueBottom = $paddingArr[2];
1✔
826
                        $valueLeft = $paddingArr[3];
1✔
827
                    }
828
                    if ($valueTop !== null) {
1✔
829
                        $styles['paddingTop'] = Converter::cssToTwip($valueTop);
1✔
830
                    }
831
                    if ($valueRight !== null) {
1✔
832
                        $styles['paddingRight'] = Converter::cssToTwip($valueRight);
1✔
833
                    }
834
                    if ($valueBottom !== null) {
1✔
835
                        $styles['paddingBottom'] = Converter::cssToTwip($valueBottom);
1✔
836
                    }
837
                    if ($valueLeft !== null) {
1✔
838
                        $styles['paddingLeft'] = Converter::cssToTwip($valueLeft);
1✔
839
                    }
840

841
                    break;
1✔
842
                case 'padding-top':
9✔
843
                    $styles['paddingTop'] = Converter::cssToTwip($value);
1✔
844

845
                    break;
1✔
846
                case 'padding-right':
9✔
847
                    $styles['paddingRight'] = Converter::cssToTwip($value);
1✔
848

849
                    break;
1✔
850
                case 'padding-bottom':
9✔
851
                    $styles['paddingBottom'] = Converter::cssToTwip($value);
1✔
852

853
                    break;
1✔
854
                case 'padding-left':
9✔
855
                    $styles['paddingLeft'] = Converter::cssToTwip($value);
1✔
856

857
                    break;
1✔
858

859
                case 'border-color':
8✔
860
                    self::mapBorderColor($styles, $value);
1✔
861

862
                    break;
1✔
863
                case 'border-width':
8✔
864
                    $styles['borderSize'] = Converter::cssToPoint($value);
1✔
865

866
                    break;
1✔
867
                case 'border-style':
8✔
868
                    $styles['borderStyle'] = self::mapBorderStyle($value);
1✔
869

870
                    break;
1✔
871
                case 'width':
8✔
872
                    if (preg_match('/([0-9]+[a-z]+)/', $value, $matches)) {
3✔
873
                        $styles['width'] = Converter::cssToTwip($matches[1]);
2✔
874
                        $styles['unit'] = \PhpOffice\PhpWord\SimpleType\TblWidth::TWIP;
2✔
875
                    } elseif (preg_match('/([0-9]+)%/', $value, $matches)) {
3✔
876
                        $styles['width'] = $matches[1] * 50;
3✔
877
                        $styles['unit'] = \PhpOffice\PhpWord\SimpleType\TblWidth::PERCENT;
3✔
878
                    } elseif (preg_match('/([0-9]+)/', $value, $matches)) {
1✔
879
                        $styles['width'] = $matches[1];
1✔
880
                        $styles['unit'] = \PhpOffice\PhpWord\SimpleType\TblWidth::AUTO;
1✔
881
                    }
882

883
                    break;
3✔
884
                case 'height':
7✔
885
                    $styles['height'] = Converter::cssToTwip($value);
1✔
886
                    $styles['exactHeight'] = true;
1✔
887

888
                    break;
1✔
889
                case 'border':
6✔
890
                case 'border-top':
4✔
891
                case 'border-bottom':
4✔
892
                case 'border-right':
3✔
893
                case 'border-left':
3✔
894
                    // must have exact order [width color style], e.g. "1px #0011CC solid" or "2pt green solid"
895
                    // Word does not accept shortened hex colors e.g. #CCC, only full e.g. #CCCCCC
896
                    if (preg_match('/([0-9]+[^0-9]*)\s+(\#[a-fA-F0-9]+|[a-zA-Z]+)\s+([a-z]+)/', $value, $matches)) {
4✔
897
                        if (false !== strpos($property, '-')) {
4✔
898
                            $tmp = explode('-', $property);
1✔
899
                            $which = $tmp[1];
1✔
900
                            $which = ucfirst($which); // e.g. bottom -> Bottom
1✔
901
                        } else {
902
                            $which = '';
3✔
903
                        }
904
                        // Note - border width normalization:
905
                        // Width of border in Word is calculated differently than HTML borders, usually showing up too bold.
906
                        // Smallest 1px (or 1pt) appears in Word like 2-3px/pt in HTML once converted to twips.
907
                        // Therefore we need to normalize converted twip value to cca 1/2 of value.
908
                        // This may be adjusted, if better ratio or formula found.
909
                        // BC change: up to ver. 0.17.0 was $size converted to points - Converter::cssToPoint($size)
910
                        $size = Converter::cssToTwip($matches[1]);
4✔
911
                        $size = (int) ($size / 2);
4✔
912
                        // valid variants may be e.g. borderSize, borderTopSize, borderLeftColor, etc ..
913
                        $styles["border{$which}Size"] = $size; // twips
4✔
914
                        $styles["border{$which}Color"] = trim($matches[2], '#');
4✔
915
                        $styles["border{$which}Style"] = self::mapBorderStyle($matches[3]);
4✔
916
                    }
917

918
                    break;
4✔
919
                case 'vertical-align':
3✔
920
                    // https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align
921
                    if (preg_match('#(?:top|bottom|middle|sub|baseline)#i', $value, $matches)) {
1✔
922
                        $styles['valign'] = self::mapAlignVertical($matches[0]);
1✔
923
                    }
924

925
                    break;
1✔
926
                case 'page-break-after':
2✔
927
                    if ($value == 'always') {
1✔
928
                        $styles['isPageBreak'] = true;
1✔
929
                    }
930

931
                    break;
1✔
932
            }
933
        }
934

935
        return $styles;
32✔
936
    }
937

938
    /**
939
     * Parse image node.
940
     *
941
     * @param DOMNode $node
942
     * @param AbstractContainer $element
943
     *
944
     * @return \PhpOffice\PhpWord\Element\Image
945
     */
946
    protected static function parseImage($node, $element)
947
    {
948
        $style = [];
9✔
949
        $src = null;
9✔
950
        foreach ($node->attributes as $attribute) {
9✔
951
            switch ($attribute->name) {
9✔
952
                case 'src':
9✔
953
                    $src = $attribute->value;
9✔
954

955
                    break;
9✔
956
                case 'width':
9✔
957
                    $style['width'] = self::convertHtmlSize($attribute->value);
9✔
958
                    $style['unit'] = \PhpOffice\PhpWord\Style\Image::UNIT_PX;
9✔
959

960
                    break;
9✔
961
                case 'height':
9✔
962
                    $style['height'] = self::convertHtmlSize($attribute->value);
9✔
963
                    $style['unit'] = \PhpOffice\PhpWord\Style\Image::UNIT_PX;
9✔
964

965
                    break;
9✔
966
                case 'style':
6✔
967
                    $styleattr = explode(';', $attribute->value);
5✔
968
                    foreach ($styleattr as $attr) {
5✔
969
                        if (strpos($attr, ':')) {
5✔
970
                            [$k, $v] = explode(':', $attr);
5✔
971
                            switch ($k) {
972
                                case 'float':
5✔
973
                                    if (trim($v) == 'right') {
5✔
974
                                        $style['hPos'] = \PhpOffice\PhpWord\Style\Image::POS_RIGHT;
5✔
975
                                        $style['hPosRelTo'] = \PhpOffice\PhpWord\Style\Image::POS_RELTO_MARGIN; // inner section area
5✔
976
                                        $style['pos'] = \PhpOffice\PhpWord\Style\Image::POS_RELATIVE;
5✔
977
                                        $style['wrap'] = \PhpOffice\PhpWord\Style\Image::WRAP_TIGHT;
5✔
978
                                        $style['overlap'] = true;
5✔
979
                                    }
980
                                    if (trim($v) == 'left') {
5✔
981
                                        $style['hPos'] = \PhpOffice\PhpWord\Style\Image::POS_LEFT;
3✔
982
                                        $style['hPosRelTo'] = \PhpOffice\PhpWord\Style\Image::POS_RELTO_MARGIN; // inner section area
3✔
983
                                        $style['pos'] = \PhpOffice\PhpWord\Style\Image::POS_RELATIVE;
3✔
984
                                        $style['wrap'] = \PhpOffice\PhpWord\Style\Image::WRAP_TIGHT;
3✔
985
                                        $style['overlap'] = true;
3✔
986
                                    }
987

988
                                    break;
5✔
989
                            }
990
                        }
991
                    }
992

993
                    break;
5✔
994
            }
995
        }
996
        $originSrc = $src;
9✔
997
        if (strpos($src, 'data:image') !== false) {
9✔
998
            $tmpDir = Settings::getTempDir() . '/';
1✔
999

1000
            $match = [];
1✔
1001
            preg_match('/data:image\/(\w+);base64,(.+)/', $src, $match);
1✔
1002
            if (!empty($match)) {
1✔
1003
                $src = $imgFile = $tmpDir . uniqid() . '.' . $match[1];
1✔
1004

1005
                $ifp = fopen($imgFile, 'wb');
1✔
1006

1007
                if ($ifp !== false) {
1✔
1008
                    fwrite($ifp, base64_decode($match[2]));
1✔
1009
                    fclose($ifp);
1✔
1010
                }
1011
            }
1012
        }
1013
        $src = urldecode($src);
9✔
1014

1015
        if (!is_file($src)
9✔
1016
            && null !== self::$options
9✔
1017
            && isset(self::$options['IMG_SRC_SEARCH'], self::$options['IMG_SRC_REPLACE'])
9✔
1018
        ) {
1019
            $src = str_replace(self::$options['IMG_SRC_SEARCH'], self::$options['IMG_SRC_REPLACE'], $src);
1✔
1020
        }
1021

1022
        if (!is_file($src)) {
9✔
1023
            if ($imgBlob = @file_get_contents($src)) {
3✔
1024
                $tmpDir = Settings::getTempDir() . '/';
3✔
1025
                $match = [];
3✔
1026
                preg_match('/.+\.(\w+)$/', $src, $match);
3✔
1027
                $src = $tmpDir . uniqid();
3✔
1028
                if (isset($match[1])) {
3✔
1029
                    $src .= '.' . $match[1];
2✔
1030
                }
1031

1032
                $ifp = fopen($src, 'wb');
3✔
1033

1034
                if ($ifp !== false) {
3✔
1035
                    fwrite($ifp, $imgBlob);
3✔
1036
                    fclose($ifp);
3✔
1037
                }
1038
            }
1039
        }
1040

1041
        if (is_file($src)) {
9✔
1042
            $newElement = $element->addImage($src, $style);
9✔
1043
        } else {
1044
            throw new Exception("Could not load image $originSrc");
×
1045
        }
1046

1047
        return $newElement;
8✔
1048
    }
1049

1050
    /**
1051
     * Transforms a CSS border style into a word border style.
1052
     *
1053
     * @param string $cssBorderStyle
1054
     *
1055
     * @return null|string
1056
     */
1057
    protected static function mapBorderStyle($cssBorderStyle)
1058
    {
1059
        switch ($cssBorderStyle) {
1060
            case 'none':
4✔
1061
            case 'dashed':
4✔
1062
            case 'dotted':
4✔
1063
            case 'double':
4✔
1064
                return $cssBorderStyle;
2✔
1065
            default:
1066
                return 'single';
3✔
1067
        }
1068
    }
1069

1070
    protected static function mapBorderColor(&$styles, $cssBorderColor): void
1071
    {
1072
        $numColors = substr_count($cssBorderColor, '#');
1✔
1073
        if ($numColors === 1) {
1✔
1074
            $styles['borderColor'] = trim($cssBorderColor, '#');
1✔
1075
        } elseif ($numColors > 1) {
1✔
1076
            $colors = explode(' ', $cssBorderColor);
1✔
1077
            $borders = ['borderTopColor', 'borderRightColor', 'borderBottomColor', 'borderLeftColor'];
1✔
1078
            for ($i = 0; $i < min(4, $numColors, count($colors)); ++$i) {
1✔
1079
                $styles[$borders[$i]] = trim($colors[$i], '#');
1✔
1080
            }
1081
        }
1082
    }
1083

1084
    /**
1085
     * Transforms a HTML/CSS alignment into a \PhpOffice\PhpWord\SimpleType\Jc.
1086
     *
1087
     * @param string $cssAlignment
1088
     * @param bool $bidi
1089
     *
1090
     * @return null|string
1091
     */
1092
    protected static function mapAlign($cssAlignment, $bidi)
1093
    {
1094
        switch ($cssAlignment) {
1095
            case 'right':
8✔
1096
                return $bidi ? Jc::START : Jc::END;
1✔
1097
            case 'center':
8✔
1098
                return Jc::CENTER;
6✔
1099
            case 'justify':
4✔
1100
                return Jc::BOTH;
1✔
1101
            default:
1102
                return $bidi ? Jc::END : Jc::START;
4✔
1103
        }
1104
    }
1105

1106
    /**
1107
     * Transforms a HTML/CSS vertical alignment.
1108
     *
1109
     * @param string $alignment
1110
     *
1111
     * @return null|string
1112
     */
1113
    protected static function mapAlignVertical($alignment)
1114
    {
1115
        $alignment = strtolower($alignment);
1✔
1116
        switch ($alignment) {
1117
            case 'top':
1✔
1118
            case 'baseline':
1✔
1119
            case 'bottom':
1✔
1120
                return $alignment;
1✔
1121
            case 'middle':
1✔
1122
                return 'center';
1✔
1123
            case 'sub':
×
1124
                return 'bottom';
×
1125
            case 'text-top':
×
1126
            case 'baseline':
×
1127
                return 'top';
×
1128
            default:
1129
                // @discuss - which one should apply:
1130
                // - Word uses default vert. alignment: top
1131
                // - all browsers use default vert. alignment: middle
1132
                // Returning empty string means attribute wont be set so use Word default (top).
1133
                return '';
×
1134
        }
1135
    }
1136

1137
    /**
1138
     * Map list style for ordered list.
1139
     *
1140
     * @param string $cssListType
1141
     */
1142
    protected static function mapListType($cssListType)
1143
    {
1144
        switch ($cssListType) {
1145
            case 'a':
1✔
1146
                return NumberFormat::LOWER_LETTER; // a, b, c, ..
×
1147
            case 'A':
1✔
1148
                return NumberFormat::UPPER_LETTER; // A, B, C, ..
1✔
1149
            case 'i':
1✔
1150
                return NumberFormat::LOWER_ROMAN; // i, ii, iii, iv, ..
1✔
1151
            case 'I':
×
1152
                return NumberFormat::UPPER_ROMAN; // I, II, III, IV, ..
×
1153
            case '1':
×
1154
            default:
1155
                return NumberFormat::DECIMAL; // 1, 2, 3, ..
×
1156
        }
1157
    }
1158

1159
    /**
1160
     * Parse line break.
1161
     *
1162
     * @param AbstractContainer $element
1163
     */
1164
    protected static function parseLineBreak($element): void
1165
    {
1166
        $element->addTextBreak();
2✔
1167
    }
1168

1169
    /**
1170
     * Parse link node.
1171
     *
1172
     * @param DOMNode $node
1173
     * @param AbstractContainer $element
1174
     * @param array $styles
1175
     */
1176
    protected static function parseLink($node, $element, &$styles)
1177
    {
1178
        $target = null;
3✔
1179
        foreach ($node->attributes as $attribute) {
3✔
1180
            switch ($attribute->name) {
3✔
1181
                case 'href':
3✔
1182
                    $target = $attribute->value;
3✔
1183

1184
                    break;
3✔
1185
            }
1186
        }
1187
        $styles['font'] = self::parseInlineStyle($node, $styles['font']);
3✔
1188

1189
        if (empty($target)) {
3✔
1190
            $target = '#';
1✔
1191
        }
1192

1193
        if (strpos($target, '#') === 0 && strlen($target) > 1) {
3✔
1194
            return $element->addLink(substr($target, 1), $node->textContent, $styles['font'], $styles['paragraph'], true);
1✔
1195
        }
1196

1197
        return $element->addLink($target, $node->textContent, $styles['font'], $styles['paragraph']);
2✔
1198
    }
1199

1200
    /**
1201
     * Render horizontal rule
1202
     * Note: Word rule is not the same as HTML's <hr> since it does not support width and thus neither alignment.
1203
     *
1204
     * @param DOMNode $node
1205
     * @param AbstractContainer $element
1206
     */
1207
    protected static function parseHorizRule($node, $element): void
1208
    {
1209
        $styles = self::parseInlineStyle($node);
1✔
1210

1211
        // <hr> is implemented as an empty paragraph - extending 100% inside the section
1212
        // Some properties may be controlled, e.g. <hr style="border-bottom: 3px #DDDDDD solid; margin-bottom: 0;">
1213

1214
        $fontStyle = $styles + ['size' => 3];
1✔
1215

1216
        $paragraphStyle = $styles + [
1✔
1217
            'lineHeight' => 0.25, // multiply default line height - e.g. 1, 1.5 etc
1✔
1218
            'spacing' => 0, // twip
1✔
1219
            'spaceBefore' => 120, // twip, 240/2 (default line height)
1✔
1220
            'spaceAfter' => 120, // twip
1✔
1221
            'borderBottomSize' => empty($styles['line-height']) ? 1 : $styles['line-height'],
1✔
1222
            'borderBottomColor' => empty($styles['color']) ? '000000' : $styles['color'],
1✔
1223
            'borderBottomStyle' => 'single', // same as "solid"
1✔
1224
        ];
1✔
1225

1226
        $element->addText('', $fontStyle, $paragraphStyle);
1✔
1227

1228
        // Notes: <hr/> cannot be:
1229
        // - table - throws error "cannot be inside textruns", e.g. lists
1230
        // - line - that is a shape, has different behaviour
1231
        // - repeated text, e.g. underline "_", because of unpredictable line wrapping
1232
    }
1233

1234
    private static function convertRgb(string $rgb): string
1235
    {
1236
        if (preg_match(self::RGB_REGEXP, $rgb, $matches) === 1) {
8✔
1237
            return sprintf('%02X%02X%02X', $matches[1], $matches[2], $matches[3]);
1✔
1238
        }
1239

1240
        return trim($rgb, '# ');
8✔
1241
    }
1242

1243
    /**
1244
     * Transform HTML sizes (pt, px) in pixels.
1245
     */
1246
    protected static function convertHtmlSize(string $size): float
1247
    {
1248
        // pt
1249
        if (false !== strpos($size, 'pt')) {
14✔
1250
            return Converter::pointToPixel((float) str_replace('pt', '', $size));
2✔
1251
        }
1252

1253
        // px
1254
        if (false !== strpos($size, 'px')) {
12✔
1255
            return (float) str_replace('px', '', $size);
2✔
1256
        }
1257

1258
        return (float) $size;
10✔
1259
    }
1260
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc