Completed
Push — 1.5 ( 2fb592...563c17 )
by Colin
01:07
created

AttributesHelper::mergeAttributes()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 27
ccs 14
cts 14
cp 1
rs 8.5546
c 0
b 0
f 0
cc 7
nc 10
nop 2
crap 7
1
<?php
2
3
/*
4
 * This file is part of the league/commonmark package.
5
 *
6
 * (c) Colin O'Dell <[email protected]>
7
 * (c) 2015 Martin Hasoň <[email protected]>
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
declare(strict_types=1);
14
15
namespace League\CommonMark\Extension\Attributes\Util;
16
17
use League\CommonMark\Block\Element\AbstractBlock;
18
use League\CommonMark\Cursor;
19
use League\CommonMark\Inline\Element\AbstractInline;
20
use League\CommonMark\Util\RegexHelper;
21
22
/**
23
 * @internal
24
 */
25
final class AttributesHelper
26
{
27
    /**
28
     * @param Cursor $cursor
29
     *
30
     * @return array<string, mixed>
0 ignored issues
show
Documentation introduced by
The doc-type array<string, could not be parsed: Expected ">" at position 5, but found "end of type". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
31
     */
32 111
    public static function parseAttributes(Cursor $cursor): array
33
    {
34 111
        $state = $cursor->saveState();
35 111
        $cursor->advanceToNextNonSpaceOrNewline();
36 111
        if ($cursor->getCharacter() !== '{') {
37 18
            $cursor->restoreState($state);
38
39 18
            return [];
40
        }
41
42 108
        $cursor->advanceBy(1);
43 108
        if ($cursor->getCharacter() === ':') {
44 57
            $cursor->advanceBy(1);
45
        }
46
47 108
        $attributes = [];
48 108
        $regex = '/^\s*([.#][_a-z0-9-]+|' . RegexHelper::PARTIAL_ATTRIBUTENAME . RegexHelper::PARTIAL_ATTRIBUTEVALUESPEC . ')(?<!})\s*/i';
49 108
        while ($attribute = \trim((string) $cursor->match($regex))) {
50 102
            if ($attribute[0] === '#') {
51 57
                $attributes['id'] = \substr($attribute, 1);
52
53 57
                continue;
54
            }
55
56 63
            if ($attribute[0] === '.') {
57 30
                $attributes['class'][] = \substr($attribute, 1);
58
59 30
                continue;
60
            }
61
62 45
            [$name, $value] = \explode('=', $attribute, 2);
0 ignored issues
show
Bug introduced by
The variable $name does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $value does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
63 45
            $first = $value[0];
64 45
            $last = \substr($value, -1);
65 45
            if ((($first === '"' && $last === '"') || ($first === "'" && $last === "'")) && \strlen($value) > 1) {
66 45
                $value = \substr($value, 1, -1);
67
            }
68
69 45
            if (\strtolower(\trim($name)) === 'class') {
70
                foreach (\array_filter(\explode(' ', \trim($value))) as $class) {
71
                    $attributes['class'][] = $class;
72
                }
73
            } else {
74 45
                $attributes[trim($name)] = trim($value);
75
            }
76
        }
77
78 108
        if ($cursor->match('/}/') === null) {
79 6
            $cursor->restoreState($state);
80
81 6
            return [];
82
        }
83
84 105
        if ($attributes === []) {
85 9
            $cursor->restoreState($state);
86
87 9
            return [];
88
        }
89
90 99
        if (isset($attributes['class'])) {
91 30
            $attributes['class'] = \implode(' ', (array) $attributes['class']);
92
        }
93
94 99
        return $attributes;
95
    }
96
97
    /**
98
     * @param AbstractBlock|AbstractInline|array<string, mixed> $attributes1
99
     * @param AbstractBlock|AbstractInline|array<string, mixed> $attributes2
100
     *
101
     * @return array<string, mixed>
0 ignored issues
show
Documentation introduced by
The doc-type array<string, could not be parsed: Expected ">" at position 5, but found "end of type". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
102
     */
103 45
    public static function mergeAttributes($attributes1, $attributes2): array
104
    {
105 45
        $attributes = [];
106 45
        foreach ([$attributes1, $attributes2] as $arg) {
107 45
            if ($arg instanceof AbstractBlock || $arg instanceof AbstractInline) {
108 36
                $arg = $arg->data['attributes'] ?? [];
109
            }
110
111
            /** @var array<string, mixed> $arg */
112 45
            $arg = (array) $arg;
113 45
            if (isset($arg['class'])) {
114 39
                foreach (\array_filter(\explode(' ', \trim($arg['class']))) as $class) {
115 39
                    $attributes['class'][] = $class;
116
                }
117
118 39
                unset($arg['class']);
119
            }
120
121 45
            $attributes = \array_merge($attributes, $arg);
122
        }
123
124 45
        if (isset($attributes['class'])) {
125 39
            $attributes['class'] = \implode(' ', $attributes['class']);
126
        }
127
128 45
        return $attributes;
129
    }
130
}
131