Completed
Push — master ( 742fba...7a6aee )
by Colin
14s
created

CloseBracketParser::tryParseInlineLinkAndTitle()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 34
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 6.042

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 34
ccs 17
cts 19
cp 0.8947
rs 8.439
cc 6
eloc 18
nc 8
nop 1
crap 6.042
1
<?php
2
3
/*
4
 * This file is part of the league/commonmark package.
5
 *
6
 * (c) Colin O'Dell <[email protected]>
7
 *
8
 * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js)
9
 *  - (c) John MacFarlane
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
15
namespace League\CommonMark\Inline\Parser;
16
17
use League\CommonMark\Cursor;
18
use League\CommonMark\Delimiter\Delimiter;
19
use League\CommonMark\Delimiter\DelimiterStack;
20
use League\CommonMark\Environment;
21
use League\CommonMark\EnvironmentAwareInterface;
22
use League\CommonMark\Inline\Element\AbstractWebResource;
23
use League\CommonMark\Inline\Element\Image;
24
use League\CommonMark\Inline\Element\Link;
25
use League\CommonMark\InlineParserContext;
26
use League\CommonMark\Reference\Reference;
27
use League\CommonMark\Reference\ReferenceMap;
28
use League\CommonMark\Util\LinkParserHelper;
29
use League\CommonMark\Util\RegexHelper;
30
31
class CloseBracketParser extends AbstractInlineParser implements EnvironmentAwareInterface
32
{
33
    /**
34
     * @var Environment
35
     */
36
    protected $environment;
37
38
    /**
39
     * @return string[]
40
     */
41 1935
    public function getCharacters()
42
    {
43 1935
        return [']'];
44
    }
45
46
    /**
47
     * @param InlineParserContext $inlineContext
48
     *
49
     * @return bool
50
     */
51 405
    public function parse(InlineParserContext $inlineContext)
52
    {
53 405
        $cursor = $inlineContext->getCursor();
54
55 405
        $startPos = $cursor->getPosition();
56 405
        $previousState = $cursor->saveState();
57
58
        // Look through stack of delimiters for a [ or !
59 405
        $opener = $inlineContext->getDelimiterStack()->searchByCharacter(['[', '!']);
60 405
        if ($opener === null) {
61 12
            return false;
62
        }
63
64 396
        if (!$opener->isActive()) {
65
            // no matched opener; remove from emphasis stack
66 19
            $inlineContext->getDelimiterStack()->removeDelimiter($opener);
67
68 18
            return false;
69
        }
70
71 396
        $isImage = $opener->getChar() === '!';
72
73 396
        $cursor->advance();
74
75
        // Check to see if we have a link/image
76 396
        if (!($link = $this->tryParseLink($cursor, $inlineContext->getReferenceMap(), $opener, $startPos))) {
77
            // No match
78 87
            $inlineContext->getDelimiterStack()->removeDelimiter($opener); // Remove this opener from stack
79 87
            $cursor->restoreState($previousState);
80
81 87
            return false;
82
        }
83
84 333
        $inline = $this->createInline($link['url'], $link['title'], $isImage);
85 333
        $opener->getInlineNode()->replaceWith($inline);
86 333
        while (($label = $inline->next()) !== null) {
87 330
            $inline->appendChild($label);
88 110
        }
89
90 333
        $delimiterStack = $inlineContext->getDelimiterStack();
91 333
        $stackBottom = $opener->getPrevious();
92 333
        foreach ($this->environment->getInlineProcessors() as $inlineProcessor) {
93 333
            $inlineProcessor->processInlines($delimiterStack, $stackBottom);
94 111
        }
95 333
        if ($delimiterStack instanceof DelimiterStack) {
96 333
            $delimiterStack->removeAll($stackBottom);
97 111
        }
98
99
        // processEmphasis will remove this and later delimiters.
100
        // Now, for a link, we also remove earlier link openers (no links in links)
101 333
        if (!$isImage) {
102 279
            $inlineContext->getDelimiterStack()->removeEarlierMatches('[');
103 93
        }
104
105 333
        return true;
106
    }
107
108
    /**
109
     * @param Environment $environment
110
     */
111 1935
    public function setEnvironment(Environment $environment)
112
    {
113 1935
        $this->environment = $environment;
114 1935
    }
115
116
    /**
117
     * @param Cursor       $cursor
118
     * @param ReferenceMap $referenceMap
119
     * @param Delimiter    $opener
120
     * @param int          $startPos
121
     *
122
     * @return array|bool
123
     */
124 396
    protected function tryParseLink(Cursor $cursor, ReferenceMap $referenceMap, Delimiter $opener, $startPos)
125
    {
126
        // Check to see if we have a link/image
127
        // Inline link?
128 396
        if ($result = $this->tryParseInlineLinkAndTitle($cursor)) {
129 150
            return $result;
130
        }
131
132 255
        if ($link = $this->tryParseReference($cursor, $referenceMap, $opener, $startPos)) {
133 189
            return ['url' => $link->getDestination(), 'title' => $link->getTitle()];
134
        }
135
136 87
        return false;
137
    }
138
139
    /**
140
     * @param Cursor $cursor
141
     *
142
     * @return array|bool
143
     */
144 396
    protected function tryParseInlineLinkAndTitle(Cursor $cursor)
145
    {
146 396
        if ($cursor->getCharacter() !== '(') {
147 237
            return false;
148
        }
149
150 168
        $previousState = $cursor->saveState();
151
152 168
        $cursor->advance();
153 168
        $cursor->advanceToNextNonSpaceOrNewline();
154 168
        if (($dest = LinkParserHelper::parseLinkDestination($cursor)) === null) {
155
            $cursor->restoreState($previousState);
156
157
            return false;
158
        }
159
160 168
        $cursor->advanceToNextNonSpaceOrNewline();
161
162 168
        $title = null;
163
        // make sure there's a space before the title:
164 168
        if (preg_match(RegexHelper::REGEX_WHITESPACE_CHAR, $cursor->peek(-1))) {
165 45
            $title = LinkParserHelper::parseLinkTitle($cursor) ?: '';
166 15
        }
167
168 168
        $cursor->advanceToNextNonSpaceOrNewline();
169
170 168
        if ($cursor->match('/^\\)/') === null) {
171 18
            $cursor->restoreState($previousState);
172
173 18
            return false;
174
        }
175
176 150
        return ['url' => $dest, 'title' => $title];
177
    }
178
179
    /**
180
     * @param Cursor       $cursor
181
     * @param ReferenceMap $referenceMap
182
     * @param Delimiter    $opener
183
     * @param int          $startPos
184
     *
185
     * @return Reference|null
186
     */
187 255
    protected function tryParseReference(Cursor $cursor, ReferenceMap $referenceMap, Delimiter $opener, $startPos)
188
    {
189 255
        $savePos = $cursor->saveState();
190 255
        $beforeLabel = $cursor->getPosition();
191 255
        $n = LinkParserHelper::parseLinkLabel($cursor);
192 255
        if ($n === 0 || $n === 2) {
193
            // Empty or missing second label
194 204
            $reflabel = mb_substr($cursor->getLine(), $opener->getIndex(), $startPos - $opener->getIndex(), 'utf-8');
195 68
        } else {
196 63
            $reflabel = mb_substr($cursor->getLine(), $beforeLabel + 1, $n - 2, 'utf-8');
197
        }
198
199 255
        if ($n === 0) {
200
            // If shortcut reference link, rewind before spaces we skipped
201 180
            $cursor->restoreState($savePos);
202 60
        }
203
204 255
        return $referenceMap->getReference($reflabel);
205
    }
206
207
    /**
208
     * @param string $url
209
     * @param string $title
210
     * @param bool   $isImage
211
     *
212
     * @return AbstractWebResource
213
     */
214 333
    protected function createInline($url, $title, $isImage)
215
    {
216 333
        if ($isImage) {
217 78
            return new Image($url, null, $title);
218
        } else {
219 279
            return new Link($url, null, $title);
220
        }
221
    }
222
}
223