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

dg / texy / 43760211708

15 Nov 2026 08:43PM UTC coverage: 97.217% (+0.3%) from 96.951%
43760211708

push

github

dg
cs

3 of 5 new or added lines in 1 file covered. (60.0%)

45 existing lines in 12 files now uncovered.

3878 of 3989 relevant lines covered (97.22%)

0.97 hits per line

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

97.53
/src/Modules/LinkReferenceModule.php
1
<?php declare(strict_types=1);
2

3
/**
4
 * This file is part of the Texy! (https://texy.deegee.dev)
5
 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6
 */
7

8
namespace Texy\Modules;
9

10
use Texy;
11
use Texy\{Helpers, Nodes, Patterns, Range, Syntax};
12
use Texy\Nodes\{DocumentNode, LinkDefinitionNode};
13
use Texy\Parsing\ParseContext;
14
use function in_array, strlen;
15

16

17
/**
18
 * Processes link references and generates link elements.
19
 */
20
final class LinkReferenceModule extends Texy\Module
21
{
22
        /** @var array<string, LinkDefinitionNode> link definitions */
23
        private array $definitions = [];
24

25

26
        public function __construct(
1 ✔
27
                private Texy\Config $config,
28
                private ImageModule $imageModule,
29
        ) {
30
        }
1 ✔
31

32

33
        public function register(Texy\Parsing\Engine $engine): void
34
        {
35
                $engine->declare(Syntax::LinkReference, enabled: false);
1 ✔
36

37
                // [ref]: url label .(title)[class]{style}
38
                $engine->addBlock(
1 ✔
39
                        Syntax::LinkDefinition,
1 ✔
40
                        '~^
41
                                \[
42
                                ( [^\[\]#?*\n]{1,100} )           # reference (1)
43
                                ] : [ \t]++
44
                                ( \S{1,1000} )                    # URL (2)
45
                                ( [ \t] .{1,1000} )?              # optional label (3)
46
                                ' . Patterns::Modifier . '?       # modifier (4)
1 ✔
47
                                \s*
48
                        $~mUx',
49
                        $this->parseDefinition(...),
1 ✔
50
                );
51

52
                // [reference] - bare reference link (opt-in), resolved like "text":[reference]
53
                $engine->addInline(
1 ✔
54
                        Syntax::LinkReference,
1 ✔
55
                        '~
1 ✔
56
                                (?<! [.\#\[] )        # exclude modifier .[class], PHP attribute \#[Attr] and nested [
57
                                \[
58
                                ( [^\[\]*|\n]++ )     # reference name (1); * would be an image, | a labeled form
59
                                ]
60
                        ~Ux',
61
                        $this->parseReference(...),
1 ✔
62
                );
63
        }
1 ✔
64

65

66
        /**
67
         * Parses [ref]: url
68
         * @param  array{string, string, string, ?string, ?string}  $matches
69
         * @param  array{int, int, int, ?int, ?int}  $offsets
70
         */
71
        public function parseDefinition(ParseContext $context, array $matches, array $offsets): LinkDefinitionNode
72
        {
73
                [, $mRef, $mLink, $mLabel, $mMod] = $matches;
1 ✔
74
                if ($mMod || $mLabel) {
1 ✔
UNCOV
75
                        trigger_error('Modifiers and label in link definitions are deprecated.', E_USER_DEPRECATED);
×
76
                }
77
                return new LinkDefinitionNode(
1 ✔
78
                        $mRef,
79
                        Helpers::decodeEntities($mLink),
1 ✔
80
                        new Range($offsets[0], strlen($matches[0])),
1 ✔
81
                );
82
        }
83

84

85
        /**
86
         * Parses bare [ref]
87
         * @param  array{string, string}  $matches
88
         * @param  array{int, int}  $offsets
89
         */
90
        public function parseReference(ParseContext $context, array $matches, array $offsets): Nodes\LinkNode
91
        {
92
                [, $mRef] = $matches;
1 ✔
93
                $refRange = new Range($offsets[1], strlen($mRef));
1 ✔
94
                return new Nodes\LinkNode(
1 ✔
95
                        content: new Nodes\ContentNode([new Nodes\TextNode(Helpers::decodeEntities($mRef), $refRange)]),
1 ✔
96
                        range: new Range($offsets[0], strlen($matches[0])),
1 ✔
97
                        isBareRef: true,
1 ✔
98
                        ref: $mRef,
99
                        syntax: Syntax::LinkReference,
1 ✔
100
                        textRange: $refRange,
101
                        urlRange: $refRange,
102
                );
103
        }
104

105

106
        /**
107
         * Recognizes link targets written as a reference, [ref] or [*img*]: the name goes
108
         * to LinkNode::$ref and the URL is left to resolveReferences().
109
         */
110
        public function recognizeReferences(DocumentNode $doc): void
111
        {
112
                foreach ($doc->find(Nodes\LinkNode::class) as $node) {
1 ✔
113
                        $url = $node->url ?? '';
1 ✔
114
                        $len = strlen($url);
1 ✔
115
                        if ($len > 4 && $url[0] === '[' && $url[1] === '*' && $url[$len - 1] === ']'
1 ✔
116
                                && in_array($url[$len - 2], ['*', '<', '>'], true)
1 ✔
117
                        ) {
118
                                $node->ref = trim(substr($url, 2, -2));
1 ✔
119
                                $node->isImageLink = true;
1 ✔
120
                                $node->url = null;
1 ✔
121

122
                        } elseif ($len > 2 && $url[0] === '[' && $url[$len - 1] === ']') {
1 ✔
123
                                $node->ref = substr($url, 1, -1);
1 ✔
124
                                $node->url = null;
1 ✔
125
                        }
126
                }
127
        }
1 ✔
128

129

130
        /**
131
         * Resolve link references in the document. A Transform pass, runs after the one of ImageModule.
132
         */
133
        public function resolveReferences(DocumentNode $doc): void
134
        {
135
                $this->definitions = [];
1 ✔
136

137
                // Pass 1: Collect document definitions
138
                foreach ($doc->find(LinkDefinitionNode::class) as $node) {
1 ✔
139
                        $this->definitions[Helpers::toLower($node->reference)] = $node;
1 ✔
140
                }
141

142
                // Pass 2: Resolve references in LinkNode.url
143
                foreach ($doc->find(Nodes\LinkNode::class) as $node) {
1 ✔
144
                        $this->resolveLinkNodeUrl($node);
1 ✔
145
                }
146
        }
1 ✔
147

148

149
        /**
150
         * Resolves the URL of a link written as [ref] or [*img*] by the definitions of the document, then by
151
         * the link resolver; a reference not found is used as the URL. A %s in the URL stands for the link text,
152
         * such as "strlen":[php] with php.net/%s.
153
         */
154
        private function resolveLinkNodeUrl(Nodes\LinkNode $node): void
155
        {
156
                if ($node->url !== null) {
1 ✔
157
                        $node->url = Helpers::insertLinkText($node->url, $node);
1 ✔
158

159
                } elseif ($node->ref !== null) {
1 ✔
160
                        if ($node->isImageLink) {
1 ✔
161
                                $node->url = $this->imageModule->getDefinition($node->ref)->url ?? $node->ref;
1 ✔
162
                                return;
1 ✔
163
                        }
164
                        $definition = $this->resolveDefinition($node->ref);
1 ✔
165
                        $node->url = $definition
1 ✔
166
                                ? Helpers::insertLinkText($definition->url, $node)
1 ✔
167
                                : $this->config->resolveLink($node->ref, $node) ?? $node->ref;
1 ✔
168
                }
169

170
                $this->convertEmailUrl($node);
1 ✔
171
        }
1 ✔
172

173

174
        /**
175
         * Convert e-mail URLs to mailto: scheme. Requires a full e-mail address
176
         * (Patterns::Email) so that wiki-style targets containing @ are left alone.
177
         */
178
        private function convertEmailUrl(Nodes\LinkNode $node): void
179
        {
180
                if (
181
                        $node->url !== null
1 ✔
182
                        && !str_contains($node->url, '/')
1 ✔
183
                        && !preg_match('~^[a-z][a-z0-9+.-]*:~i', $node->url)
1 ✔
184
                        && Texy\Regexp::match($node->url, '~' . Patterns::Email . '(\?\S*)?$~A')
1 ✔
185
                ) { // optional ?subject=... query
186
                        $node->url = 'mailto:' . $node->url;
1 ✔
187
                }
188
        }
1 ✔
189

190

191
        /**
192
         * Find definition by identifier, supports #fragment and ?query.
193
         */
194
        private function resolveDefinition(string $identifier): ?LinkDefinitionNode
195
        {
196
                $key = Helpers::toLower($identifier);
1 ✔
197

198
                if (isset($this->definitions[$key])) {
1 ✔
199
                        return $this->definitions[$key];
1 ✔
200
                }
201

202
                // Support #fragment and ?query
203
                $hashPos = strpos($key, '#');
1 ✔
204
                $queryPos = strpos($key, '?');
1 ✔
205

206
                // Find the earliest delimiter
207
                $pos = null;
1 ✔
208
                if ($hashPos !== false && $queryPos !== false) {
1 ✔
UNCOV
209
                        $pos = min($hashPos, $queryPos);
×
210
                } elseif ($hashPos !== false) {
1 ✔
211
                        $pos = $hashPos;
1 ✔
212
                } elseif ($queryPos !== false) {
1 ✔
213
                        $pos = $queryPos;
1 ✔
214
                }
215

216
                if ($pos !== null) {
1 ✔
217
                        $baseKey = substr($key, 0, $pos);
1 ✔
218
                        if (isset($this->definitions[$baseKey])) {
1 ✔
219
                                $def = clone $this->definitions[$baseKey];
1 ✔
220
                                $def->url .= substr($identifier, $pos);
1 ✔
221
                                return $def;
1 ✔
222
                        }
223
                }
224

225
                return null;
1 ✔
226
        }
227
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc