Completed
Push — 1.5 ( fb52dd...2fb592 )
by Colin
02:48
created

AttributesListener::getNext()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 5
cts 5
cp 1
rs 9.9332
c 0
b 0
f 0
cc 4
nc 4
nop 1
crap 4
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\Event;
16
17
use League\CommonMark\Block\Element\AbstractBlock;
18
use League\CommonMark\Block\Element\FencedCode;
19
use League\CommonMark\Block\Element\ListBlock;
20
use League\CommonMark\Block\Element\ListItem;
21
use League\CommonMark\Event\DocumentParsedEvent;
22
use League\CommonMark\Extension\Attributes\Node\Attributes;
23
use League\CommonMark\Extension\Attributes\Node\AttributesInline;
24
use League\CommonMark\Inline\Element\AbstractInline;
25
use League\CommonMark\Node\Node;
26
27
final class AttributesListener
28
{
29
    private const DIRECTION_PREFIX = 'prefix';
30
    private const DIRECTION_SUFFIX = 'suffix';
31
32 18
    public function processDocument(DocumentParsedEvent $event): void
33
    {
34 18
        $walker = $event->getDocument()->walker();
35 18
        while ($event = $walker->next()) {
36 18
            $node = $event->getNode();
37 18
            if (!$node instanceof AttributesInline && ($event->isEntering() || !$node instanceof Attributes)) {
38 18
                continue;
39
            }
40
41 18
            [$target, $direction] = self::findTargetAndDirection($node);
0 ignored issues
show
Bug introduced by
The variable $target 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...
Bug introduced by
The variable $direction 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...
42
43 18
            if ($target instanceof AbstractBlock || $target instanceof AbstractInline) {
44 18
                $parent = $target->parent();
45 18
                if ($parent instanceof ListItem && $parent->parent() instanceof ListBlock && $parent->parent()->isTight()) {
46 3
                    $target = $parent;
47
                }
48
49 18
                if ($direction === self::DIRECTION_SUFFIX) {
50 18
                    $attributes = self::merge($target, $node->getAttributes());
51
                } else {
52 9
                    $attributes = self::merge($node->getAttributes(), $target);
53
                }
54
55 18
                $target->data['attributes'] = $attributes;
56
            }
57
58 18
            if ($node instanceof AbstractBlock && $node->endsWithBlankLine() && $node->next() && $node->previous()) {
59 9
                $previous = $node->previous();
60 9
                if ($previous instanceof AbstractBlock) {
61 9
                    $previous->setLastLineBlank(true);
62
                }
63
            }
64
65 18
            $node->detach();
66
        }
67 18
    }
68
69
    /**
70
     * @param Node $node
71
     *
72
     * @return array<Node|string|null>
73
     */
74 18
    private static function findTargetAndDirection(Node $node): array
75
    {
76 18
        $target = null;
77 18
        $direction = null;
78 18
        $previous = $next = $node;
79 18
        while (true) {
80 18
            $previous = self::getPrevious($previous);
81 18
            $next = self::getNext($next);
82
83 18
            if ($previous === null && $next === null) {
84 15
                if (!$node->parent() instanceof FencedCode) {
85 12
                    $target = $node->parent();
86 12
                    $direction = self::DIRECTION_SUFFIX;
87
                }
88
89 15
                break;
90
            }
91
92 18
            if ($node instanceof AttributesInline && ($previous === null || ($previous instanceof AbstractInline && $node->isBlock()))) {
93 15
                continue;
94
            }
95
96 18
            if ($previous !== null && !self::isAttributesNode($previous)) {
97 18
                $target = $previous;
98 18
                $direction = self::DIRECTION_SUFFIX;
99
100 18
                break;
101
            }
102
103 9
            if ($next !== null && !self::isAttributesNode($next)) {
104 9
                $target = $next;
105 9
                $direction = self::DIRECTION_PREFIX;
106
107 9
                break;
108
            }
109
        }
110
111 18
        return [$target, $direction];
112
    }
113
114 18
    private static function getPrevious(?Node $node = null): ?Node
115
    {
116 18
        $previous = $node instanceof Node ? $node->previous() : null;
117
118 18
        if ($previous instanceof AbstractBlock && $previous->endsWithBlankLine()) {
119 6
            $previous = null;
120
        }
121
122 18
        return $previous;
123
    }
124
125 18
    private static function getNext(?Node $node = null): ?Node
126
    {
127 18
        $next = $node instanceof Node ? $node->next() : null;
128
129 18
        if ($node instanceof AbstractBlock && $node->endsWithBlankLine()) {
130 9
            $next = null;
131
        }
132
133 18
        return $next;
134
    }
135
136 18
    private static function isAttributesNode(Node $node): bool
137
    {
138 18
        return $node instanceof Attributes || $node instanceof AttributesInline;
139
    }
140
141
    /**
142
     * @param AbstractBlock|AbstractInline|array<string, mixed> $attributes1
143
     * @param AbstractBlock|AbstractInline|array<string, mixed> $attributes2
144
     *
145
     * @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...
146
     */
147 18
    private static function merge($attributes1, $attributes2): array
148
    {
149 18
        $attributes = [];
150 18
        foreach ([$attributes1, $attributes2] as $arg) {
151 18
            if ($arg instanceof AbstractBlock || $arg instanceof AbstractInline) {
152 18
                $arg = $arg->data['attributes'] ?? [];
153
            }
154
155
            /** @var array<string, mixed> $arg */
156 18
            $arg = (array) $arg;
157 18
            if (isset($arg['class'])) {
158 18
                foreach (\array_filter(\explode(' ', \trim($arg['class']))) as $class) {
159 18
                    $attributes['class'][] = $class;
160
                }
161
162 18
                unset($arg['class']);
163
            }
164
165 18
            $attributes = \array_merge($attributes, $arg);
166
        }
167
168 18
        if (isset($attributes['class'])) {
169 18
            $attributes['class'] = \implode(' ', $attributes['class']);
170
        }
171
172 18
        return $attributes;
173
    }
174
}
175