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

dg / texy / 42063752054

05 Nov 2026 04:20PM UTC coverage: 95.817% (+0.4%) from 95.456%
42063752054

push

github

dg
Output\Html\Renderer: image rejected by UrlPolicy renders as its alternative text

Unlike a link, an image was not checked here, so an image node built outside the
Texy syntax (Markdown, a custom syntax, addDefinition()) got through with any
scheme. A node without URL no longer gives <img> without src either.

4a920e54-b1ea-4016-969f-be6e25ca6ad0

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

29 existing lines in 2 files now uncovered.

3528 of 3682 relevant lines covered (95.82%)

0.96 hits per line

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

97.81
/src/Texy/Modules/ImageModule.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\{Compat, Helpers, Modifier, Node, NodeHelpers, NodeTraverser, Patterns, Range, Regexp, Syntax};
12
use Texy\Nodes\{ContentNode, DocumentNode, FigureNode, ImageDefinitionNode, ImageNode, LinkNode};
13
use Texy\Parsing\ParseContext;
14
use function count, strlen;
15

16

17
/**
18
 * Processes image and figure (image with caption) syntax.
19
 */
20
final class ImageModule extends Texy\Module
21
{
22
        /** the [* url .(title) alignment ] part, shared by the image and figure syntaxes */
23
        private const ImagePattern = '
24
                        \[\* [ \t]*+                      # opening bracket with asterisk
25
                        ([^\n]{1,1000})                   # URLs (1)
26
                        ' . Patterns::Modifier . '?       # modifier (2)
27
                        [ \t]*+
28
                        ( \* | (?<! < ) > | < )           # alignment (3)
29
                        ]';
30

31
        /** the optional :LINK (or :: self link) suffix */
32
        private const LinkPattern = '
33
                        (?:
34
                                :(' . Patterns::LinkUrl . ' | : ) # link or just colon (4)
35
                        )??';
36

37
        /** @var array<string, ImageDefinitionNode> collected image definitions */
38
        private array $definitions = [];
39

40
        /** @var array<string, ImageDefinitionNode> user-defined definitions (persist across process() calls) */
41
        private array $userDefinitions = [];
42

43

44
        public function __construct(
1 ✔
45
                private Texy\Texy $texy,
46
        ) {
47
                $texy->allowed[Syntax::ImageDefinition] = true;
1 ✔
48
                $texy->addPass($this->resolveReferences(...));
1 ✔
49
        }
1 ✔
50

51

52
        public function beforeParse(): void
53
        {
54
                // [*image*]:LINK
55
                $this->texy->addLineSyntax(
1 ✔
56
                        Syntax::Image,
1 ✔
57
                        '~' . self::ImagePattern . self::LinkPattern . '
1 ✔
58
                        ~Ux',
59
                        $this->parseImage(...),
1 ✔
60
                );
61

62
                // [*ref*]: url .(title)[class]{style}
63
                $this->texy->addBlockSyntax(
1 ✔
64
                        Syntax::ImageDefinition,
1 ✔
65
                        '~^
66
                                \[\*                              # opening [*
67
                                ( [^\n]{1,100} )                  # reference (1)
68
                                \*]                               # closing *]
69
                                : [ \t]+
70
                                (.{1,1000})                       # URL (2)
71
                                [ \t]*
72
                                ' . Patterns::Modifier . '?       # modifier (3)
1 ✔
73
                                \s*
74
                        $~mUx',
75
                        $this->parseDefinition(...),
1 ✔
76
                );
77

78
                // [*image*]:link *** caption
79
                $this->texy->addBlockSyntax(
1 ✔
80
                        Syntax::Figure,
1 ✔
81
                        '~^
82
                                (?>' . self::ImagePattern . ')' . self::LinkPattern . '
1 ✔
83
                                (?:
84
                                        [ \t]++ \*\*\* [ \t]++        # separator
85
                                        (.{0,2000})                   # caption (5)
86
                                )?
87
                                ' . Patterns::ModifierHAlign . '?     # modifier (6)
1 ✔
88
                        $~mUx',
89
                        $this->parseFigure(...),
1 ✔
90
                );
91
        }
1 ✔
92

93

94
        /**
95
         * Parses [*image*]: urls .(title)[class]{style}
96
         * @param  array{string, string, string, ?string}  $matches
97
         * @param  array{int, int, int, ?int}  $offsets
98
         */
99
        public function parseDefinition(ParseContext $context, array $matches, array $offsets): ImageDefinitionNode|ContentNode
100
        {
101
                [, $mRef, $mURLs, $mMod] = $matches;
1 ✔
102
                $parsed = $this->parseImageContent($mURLs);
1 ✔
103
                $modifier = Modifier::parse($mMod, $offsets[3] ?? null);
1 ✔
104

105
                if ($parsed['url'] === null) {
1 ✔
106
                        return new ContentNode;
1 ✔
107
                }
108

109
                return new ImageDefinitionNode(
1 ✔
110
                        trim($mRef),
1 ✔
111
                        $parsed['url'],
1 ✔
112
                        $parsed['width'],
1 ✔
113
                        $parsed['height'],
1 ✔
114
                        $modifier,
115
                        new Range($offsets[0], strlen($matches[0])),
1 ✔
116
                );
117
        }
118

119

120
        /**
121
         * Parses [* small.jpg 80x13 .(alternative text)[class]{style}>]:LINK
122
         * @param  array{string, string, ?string, string, ?string}  $matches
123
         * @param  array{int, int, ?int, int, ?int}  $offsets
124
         */
125
        public function parseImage(ParseContext $context, array $matches, array $offsets): ImageNode|LinkNode|null
126
        {
127
                [, $mURLs, $mMod, $mAlign, $mLink] = $matches;
1 ✔
128
                $parsed = $this->parseImageContent($mURLs, $offsets[1]);
1 ✔
129
                $modifier = Modifier::parse($mMod . $mAlign);
1 ✔
130

131
                if ($parsed['url'] === null) {
1 ✔
132
                        return null;
1 ✔
133
                }
134

135
                // ImageNode source span is "[* ... <alignment>]"
136
                $imageNode = new ImageNode(
1 ✔
137
                        $parsed['url'],
1 ✔
138
                        $parsed['width'],
1 ✔
139
                        $parsed['height'],
1 ✔
140
                        $modifier,
141
                        new Range($offsets[0], $offsets[3] + strlen($mAlign) + 1 - $offsets[0]), // 1 = "]"
1 ✔
142
                        urlRange: $parsed['urlRange'],
1 ✔
143
                );
144

145
                return $mLink
1 ✔
146
                        ? $this->wrapInLink(
1 ✔
147
                                $imageNode,
1 ✔
148
                                $mLink,
149
                                $offsets[0],
1 ✔
150
                                $offsets[4] ?? throw new \LogicException('Link without group 4.'),
1 ✔
151
                                Syntax::Image,
1 ✔
152
                        )
153
                        : $imageNode;
1 ✔
154
        }
155

156

157
        /**
158
         * Parses [*image*]:link *** caption .(title)[class]{style}>.
159
         * @param  array{string, string, ?string, string, ?string, ?string, ?string}  $matches
160
         * @param  array{int, int, ?int, int, ?int, ?int, ?int}  $offsets
161
         */
162
        public function parseFigure(ParseContext $context, array $matches, array $offsets): ?FigureNode
163
        {
164
                [, $mURLs, $mImgMod, $mAlign, $mLink, $mContent, $mMod] = $matches;
1 ✔
165

166
                $parsed = $this->parseImageContent($mURLs, $offsets[1]);
1 ✔
167
                $modifier = Modifier::parse($mImgMod . $mAlign);
1 ✔
168

169
                if ($parsed['url'] === null) {
1 ✔
170
                        return null;
1 ✔
171
                }
172

173
                // ImageNode source span is "[* ... <alignment>]"
174
                $imageNode = new ImageNode(
1 ✔
175
                        $parsed['url'],
1 ✔
176
                        $parsed['width'],
1 ✔
177
                        $parsed['height'],
1 ✔
178
                        $modifier,
179
                        new Range($offsets[0], $offsets[3] + strlen($mAlign) + 1 - $offsets[0]), // 1 = "]"
1 ✔
180
                        urlRange: $parsed['urlRange'],
1 ✔
181
                );
182

183
                $image = $mLink
1 ✔
184
                        ? $this->wrapInLink(
1 ✔
185
                                $imageNode,
1 ✔
186
                                $mLink,
187
                                $offsets[0],
1 ✔
188
                                $offsets[4] ?? throw new \LogicException('Link without group 4.'),
1 ✔
189
                                Syntax::Figure,
1 ✔
190
                        )
191
                        : $imageNode;
1 ✔
192

193
                // Parse caption as inline content
194
                $caption = null;
1 ✔
195
                $mContent = trim($mContent ?? '');
1 ✔
196
                if ($mContent !== '') {
1 ✔
197
                        $caption = $context->parseInline($mContent, $offsets[5] ?? $offsets[0]);
1 ✔
198
                }
199

200
                return new FigureNode(
1 ✔
201
                        $image,
202
                        $caption,
203
                        Modifier::parse($mMod, $offsets[6] ?? null),
1 ✔
204
                        new Range($offsets[0], strlen($matches[0])),
1 ✔
205
                );
206
        }
207

208

209
        /** Wraps the image written at $offset in the link written after it at $linkOffset. */
210
        private function wrapInLink(ImageNode $imageNode, string $mLink, int $offset, int $linkOffset, string $syntax): LinkNode
211
        {
212
                // ':' links to the image itself; a reference like [ref] or [*img*] is recognized by LinkReferenceModule
213
                $isSelf = $mLink === ':';
1 ✔
214
                return new LinkNode(
1 ✔
215
                        url: $isSelf ? $imageNode->url : Helpers::removeSoftHyphens($mLink),
1 ✔
216
                        content: new ContentNode([$imageNode]),
1 ✔
217
                        range: new Range($offset, $linkOffset + strlen($mLink) - $offset),
1 ✔
218
                        isImageLink: $isSelf,
219
                        syntax: $syntax,
220
                        urlRange: new Range($linkOffset, strlen($mLink)),
1 ✔
221
                );
222
        }
223

224

225
        /**
226
         * Parse image content: "image.jpg 100x200"; $offset is where the content is written.
227
         * @return array{url: ?string, width: ?int, height: ?int, urlRange: ?Range}
228
         */
229
        public function parseImageContent(string $content, ?int $offset = null): array
230
        {
231
                $parts = explode('|', $content);
1 ✔
232
                $main = $written = trim($parts[0]);
1 ✔
233

234
                if (count($parts) > 1) {
1 ✔
235
                        trigger_error(
1 ✔
236
                                "Image syntax with '|' or '||' inside brackets is deprecated. Use [* image *]:url for linked images.",
1 ✔
237
                                E_USER_DEPRECATED,
1 ✔
238
                        );
239
                }
240

241
                $url = Helpers::removeSoftHyphens($main);
1 ✔
242
                $width = $height = null;
1 ✔
243

244
                // Parse dimensions: "image.jpg 100x200" or "image.jpg 100X200" (asMax)
245
                if ($m = Regexp::match($main, '~^(.*)\ (\d+|\?)\ *[xX]\ *(\d+|\?)\ *$~U')) {
1 ✔
246
                        /** @var array{string, string, string, string} $m */
247
                        $url = $written = trim($m[1]);
1 ✔
248
                        $width = $m[2] === '?' ? null : (int) $m[2];
1 ✔
249
                        $height = $m[3] === '?' ? null : (int) $m[3];
1 ✔
250
                }
251

252
                // Check URL
253
                if (!$this->texy->urlPolicy->isImageAllowed($url)) {
1 ✔
254
                        $url = null;
1 ✔
255
                }
256

257
                return [
258
                        'url' => $url,
1 ✔
259
                        'width' => $width,
1 ✔
260
                        'height' => $height,
1 ✔
261
                        'urlRange' => $offset === null ? null : new Range($offset + strlen($parts[0]) - strlen(ltrim($parts[0])), strlen($written)),
1 ✔
262
                ];
263
        }
264

265

266
        /**
267
         * Adds a user-defined image definition (persists across process() calls).
268
         */
269
        public function addDefinition(
270
                string $name,
271
                string $url,
272
                ?int $width = null,
273
                ?int $height = null,
274
                ?string $alt = null,
275
        ): void
276
        {
277
                $modifier = $alt !== null ? Modifier::parse('(' . $alt . ')') : null;
1 ✔
278
                $this->userDefinitions[Helpers::toLower($name)] = new ImageDefinitionNode($name, $url, $width, $height, $modifier);
1 ✔
279
        }
1 ✔
280

281

282
        /**
283
         * Resolve image references in the document.
284
         */
285
        public function resolveReferences(DocumentNode $doc): void
286
        {
287
                // Start with user-defined definitions
288
                $this->definitions = $this->userDefinitions;
1 ✔
289

290
                // Pass 1: Collect document definitions (overwrites user-defined)
291
                foreach (NodeHelpers::find($doc, ImageDefinitionNode::class) as $node) {
1 ✔
292
                        $this->definitions[Helpers::toLower($node->reference)] = $node;
1 ✔
293
                }
294

295
                // Pass 2: Resolve ImageNode references (NodeTraverser visits all nodes including FigureNode.image)
296
                (new NodeTraverser)->traverse($doc, function (Node $node): ?int {
1 ✔
297
                        if ($node instanceof ImageNode) {
1 ✔
298
                                $this->resolveImageNode($node);
1 ✔
299
                        } elseif (
300
                                $node instanceof LinkNode
1 ✔
301
                                && ($imageNode = $node->content->children[0] ?? null) instanceof ImageNode
1 ✔
302
                        ) {
303
                                // LinkNode wrapping ImageNode - resolve image and possibly the link URL
304
                                $imageKey = $imageNode->url !== null ? Helpers::toLower(trim($imageNode->url)) : null;
1 ✔
305
                                $linkKey = $node->url !== null ? Helpers::toLower(trim($node->url)) : null;
1 ✔
306

307
                                // Resolve the image
308
                                $this->resolveImageNode($imageNode);
1 ✔
309

310
                                // If link URL matches the original image reference (from :: syntax), resolve it too
311
                                if ($imageKey !== null && $linkKey === $imageKey && isset($this->definitions[$imageKey])) {
1 ✔
312
                                        $node->url = $this->definitions[$imageKey]->url;
1 ✔
313
                                }
314
                        }
315
                        return null;
1 ✔
316
                });
1 ✔
317
        }
1 ✔
318

319

320
        private function resolveImageNode(ImageNode $node): void
321
        {
322
                if ($node->url === null) {
1 ✔
323
                        return;
1 ✔
324
                }
325

326
                $key = Helpers::toLower(trim($node->url));
1 ✔
327
                if (!isset($this->definitions[$key])) {
1 ✔
328
                        return;
1 ✔
329
                }
330

331
                $def = $this->definitions[$key];
1 ✔
332

333
                $node->ref = trim($node->url); // keep the written reference name for analyzers
1 ✔
334
                $node->url = $def->url;
1 ✔
335
                $node->width ??= $def->width;
1 ✔
336
                $node->height ??= $def->height;
1 ✔
337

338
                // Merge modifier from definition if node doesn't have one
339
                if ($def->modifier && !$node->modifier) {
1 ✔
UNCOV
340
                        $node->modifier = clone $def->modifier;
×
341
                } elseif ($def->modifier) {
1 ✔
342
                        // Merge: node modifier takes precedence, but inherit missing values from definition
343
                        if ($node->modifier->title === null && $def->modifier->title !== null) {
1 ✔
344
                                $node->modifier->title = $def->modifier->title;
1 ✔
345
                        }
346
                }
347
        }
1 ✔
348

349

350
        /**
351
         * Get image definition by name (for LinkReferenceModule to resolve [*img*] links).
352
         */
353
        public function getDefinition(string $name): ?ImageDefinitionNode
354
        {
355
                return $this->definitions[Helpers::toLower($name)] ?? null;
1 ✔
356
        }
357

358

359
        /**
360
         * @deprecated use $texy->htmlOutput->imageRoot etc. instead
361
         */
362
        public function &__get(string $name): mixed
363
        {
UNCOV
364
                return Compat\Legacy::ref($this->texy, Compat\Legacy::OfModule['imageModule'], '$texy->imageModule', $name, 'read');
×
365
        }
366

367

368
        /**
369
         * @deprecated use $texy->htmlOutput->imageRoot etc. instead
370
         */
371
        public function __set(string $name, mixed $value): void
372
        {
373
                Compat\Legacy::set($this->texy, Compat\Legacy::OfModule['imageModule'], '$texy->imageModule', $name, $value);
1 ✔
374
        }
1 ✔
375

376

377
        public function __isset(string $name): bool
378
        {
UNCOV
379
                return Compat\Legacy::isSet($this->texy, Compat\Legacy::OfModule['imageModule'], $name);
×
380
        }
381
}
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