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

dg / texy / 42887648368

10 Nov 2026 01:51PM UTC coverage: 96.622% (-0.1%) from 96.735%
42887648368

push

github

dg
Config::$locales: each locale is a list of four quotes (BC break)

Opening and closing double quotes, then the single ones, instead of the pairs
singleQuotes and doubleQuotes. The compatibility layer converts the old table.

cabae8f0-9dec-45ab-a919-45e6dadc3ad6

8 of 8 new or added lines in 3 files covered. (100.0%)

73 existing lines in 18 files now uncovered.

3719 of 3849 relevant lines covered (96.62%)

0.97 hits per line

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

99.27
/src/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\{Helpers, Modifier, Node, NodeTraverser, Patterns, Range, Regexp, Syntax, TraverseAction};
12
use Texy\Nodes\{ContentNode, DocumentNode, FigureNode, ImageDefinitionNode, ImageNode, LinkNode};
13
use Texy\Parsing\ParseContext;
14
use function count, in_array, is_array, 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

41
        public function __construct(
1 ✔
42
                private Texy\TexyConfig $config,
43
                private Texy\UrlPolicy $urlPolicy,
44
        ) {
45
        }
1 ✔
46

47

48
        public function register(Texy\Parsing\Registry $registry): void
49
        {
50
                // [*image*]:LINK
51
                $registry->addInline(
1 ✔
52
                        Syntax::Image,
1 ✔
53
                        '~' . self::ImagePattern . self::LinkPattern . '
1 ✔
54
                        ~Ux',
55
                        $this->parseImage(...),
1 ✔
56
                );
57

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

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

89

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

101
                if ($parsed['url'] === null) {
1 ✔
102
                        return new ContentNode;
1 ✔
103
                }
104

105
                return new ImageDefinitionNode(
1 ✔
106
                        trim($mRef),
1 ✔
107
                        $parsed['url'],
1 ✔
108
                        self::takeAlt($modifier),
1 ✔
109
                        $parsed['width'],
1 ✔
110
                        $parsed['height'],
1 ✔
111
                        $modifier,
112
                        new Range($offsets[0], strlen($matches[0])),
1 ✔
113
                );
114
        }
115

116

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

130
                return $mLink
1 ✔
131
                        ? $this->wrapInLink(
1 ✔
132
                                $imageNode,
1 ✔
133
                                $mLink,
134
                                $offsets[0],
1 ✔
135
                                $offsets[4] ?? throw new \LogicException('Link without group 4.'),
1 ✔
136
                                Syntax::Image,
1 ✔
137
                        )
138
                        : $imageNode;
1 ✔
139
        }
140

141

142
        /**
143
         * Parses [*image*]:link *** caption .(title)[class]{style}>.
144
         * @param  array{string, string, ?string, string, ?string, ?string, ?string}  $matches
145
         * @param  array{int, int, ?int, int, ?int, ?int, ?int}  $offsets
146
         */
147
        public function parseFigure(ParseContext $context, array $matches, array $offsets): ?FigureNode
148
        {
149
                [, $mURLs, $mImgMod, $mAlign, $mLink, $mContent, $mMod] = $matches;
1 ✔
150
                $imageNode = $this->createImage($mURLs, $mImgMod . $mAlign, $offsets);
1 ✔
151
                if ($imageNode === null) {
1 ✔
152
                        return null;
1 ✔
153
                }
154

155
                // the float is written in the brackets of the image, but it is the figure that floats
156
                $float = $imageNode->float;
1 ✔
157
                $imageNode->float = null;
1 ✔
158

159
                $image = $mLink
1 ✔
160
                        ? $this->wrapInLink(
1 ✔
161
                                $imageNode,
1 ✔
162
                                $mLink,
163
                                $offsets[0],
1 ✔
164
                                $offsets[4] ?? throw new \LogicException('Link without group 4.'),
1 ✔
165
                                Syntax::Figure,
1 ✔
166
                        )
167
                        : $imageNode;
1 ✔
168

169
                // Parse caption as inline content
170
                $caption = null;
1 ✔
171
                $mContent = trim($mContent ?? '');
1 ✔
172
                if ($mContent !== '') {
1 ✔
173
                        $caption = $context->parseInline($mContent, $offsets[5] ?? $offsets[0]);
1 ✔
174
                }
175

176
                return new FigureNode(
1 ✔
177
                        $image,
178
                        $caption,
179
                        $float,
180
                        Modifier::parse($mMod, $offsets[6] ?? null),
1 ✔
181
                        new Range($offsets[0], strlen($matches[0])),
1 ✔
182
                );
183
        }
184

185

186
        /**
187
         * Creates the image written as [* $mURLs $mMod *]; the source span is "[* ... <alignment>]".
188
         * @param  array<?int>  $offsets
189
         */
190
        private function createImage(string $mURLs, string $mMod, array $offsets): ?ImageNode
191
        {
192
                $parsed = $this->parseImageContent($mURLs, $offsets[1]);
1 ✔
193
                if ($parsed['url'] === null) {
1 ✔
194
                        return null;
1 ✔
195
                }
196

197
                $modifier = Modifier::parse($mMod);
1 ✔
198
                $float = $modifier !== null && in_array($modifier->hAlign, ['left', 'right'], true) ? $modifier->hAlign : null;
1 ✔
199
                if ($float !== null) {
1 ✔
200
                        $modifier->hAlign = null;
1 ✔
201
                }
202

203
                $start = $offsets[0] ?? throw new \LogicException('Match without group 0.');
1 ✔
204
                $alignEnd = ($offsets[3] ?? throw new \LogicException('Match without group 3.')) + 1; // the alignment is one character
1 ✔
205
                return new ImageNode(
1 ✔
206
                        $parsed['url'],
1 ✔
207
                        self::takeAlt($modifier),
1 ✔
208
                        $parsed['width'],
1 ✔
209
                        $parsed['height'],
1 ✔
210
                        $float,
211
                        $modifier,
212
                        new Range($start, $alignEnd + 1 - $start), // 1 = "]"
1 ✔
213
                        urlRange: $parsed['urlRange'],
1 ✔
214
                );
215
        }
216

217

218
        /**
219
         * Takes the alternative text out of the modifier, which writes it as .(text); {alt: text} wins.
220
         */
221
        private static function takeAlt(?Modifier $modifier): ?string
222
        {
223
                if ($modifier === null) {
1 ✔
224
                        return null;
1 ✔
225
                }
226

227
                $alt = $modifier->attrs['alt'] ?? $modifier->title;
1 ✔
228
                unset($modifier->attrs['alt']);
1 ✔
229
                $modifier->title = null;
1 ✔
230
                return is_array($alt) ? implode(' ', $alt) : $alt;
1 ✔
231
        }
232

233

234
        /** Wraps the image written at $offset in the link written after it at $linkOffset. */
235
        private function wrapInLink(ImageNode $imageNode, string $mLink, int $offset, int $linkOffset, string $syntax): LinkNode
236
        {
237
                // ':' links to the image itself; a reference like [ref] or [*img*] is recognized by LinkReferenceModule
238
                $isSelf = $mLink === ':';
1 ✔
239
                return new LinkNode(
1 ✔
240
                        url: $isSelf ? $imageNode->url : Helpers::decodeEntities($mLink),
1 ✔
241
                        content: new ContentNode([$imageNode]),
1 ✔
242
                        range: new Range($offset, $linkOffset + strlen($mLink) - $offset),
1 ✔
243
                        isImageLink: $isSelf,
244
                        syntax: $syntax,
245
                        urlRange: new Range($linkOffset, strlen($mLink)),
1 ✔
246
                );
247
        }
248

249

250
        /**
251
         * Parse image content: "image.jpg 100x200"; $offset is where the content is written.
252
         * @return array{url: ?string, width: ?int, height: ?int, urlRange: ?Range}
253
         */
254
        public function parseImageContent(string $content, ?int $offset = null): array
255
        {
256
                $parts = explode('|', $content);
1 ✔
257
                $main = $written = trim($parts[0]);
1 ✔
258

259
                if (count($parts) > 1) {
1 ✔
260
                        trigger_error(
1 ✔
261
                                "Image syntax with '|' or '||' inside brackets is deprecated. Use [* image *]:url for linked images.",
1 ✔
262
                                E_USER_DEPRECATED,
1 ✔
263
                        );
264
                }
265

266
                $url = Helpers::decodeEntities($main);
1 ✔
267
                $width = $height = null;
1 ✔
268

269
                // Parse dimensions: "image.jpg 100x200" or "image.jpg 100X200" (asMax)
270
                if ($m = Regexp::match($main, '~^(.*)\ (\d+|\?)\ *[xX]\ *(\d+|\?)\ *$~U')) {
1 ✔
271
                        /** @var array{string, string, string, string} $m */
272
                        $url = $written = trim($m[1]);
1 ✔
273
                        $width = $m[2] === '?' ? null : (int) $m[2];
1 ✔
274
                        $height = $m[3] === '?' ? null : (int) $m[3];
1 ✔
275
                }
276

277
                // Check URL
278
                if (!$this->urlPolicy->isImageAllowed($url)) {
1 ✔
279
                        $url = null;
1 ✔
280
                }
281

282
                return [
283
                        'url' => $url,
1 ✔
284
                        'width' => $width,
1 ✔
285
                        'height' => $height,
1 ✔
286
                        'urlRange' => $offset === null ? null : new Range($offset + strlen($parts[0]) - strlen(ltrim($parts[0])), strlen($written)),
1 ✔
287
                ];
288
        }
289

290

291
        /**
292
         * Resolve image references in the document.
293
         */
294
        public function resolveReferences(DocumentNode $doc): void
295
        {
296
                // Start with the definitions of the application
297
                $this->definitions = $this->config->imageDefinitions;
1 ✔
298

299
                // Pass 1: Collect document definitions (overwrites user-defined)
300
                foreach ($doc->find(ImageDefinitionNode::class) as $node) {
1 ✔
301
                        $this->definitions[Helpers::toLower($node->reference)] = $node;
1 ✔
302
                }
303

304
                // Pass 2: Resolve ImageNode references (NodeTraverser visits all nodes including FigureNode.image)
305
                (new NodeTraverser)->traverse($doc, function (Node $node): ?TraverseAction {
1 ✔
306
                        if ($node instanceof ImageNode) {
1 ✔
307
                                $this->resolveImageNode($node);
1 ✔
308
                        } elseif (
309
                                $node instanceof LinkNode
1 ✔
310
                                && ($imageNode = $node->content->children[0] ?? null) instanceof ImageNode
1 ✔
311
                        ) {
312
                                // LinkNode wrapping ImageNode - resolve image and possibly the link URL
313
                                $imageKey = $imageNode->url !== null ? Helpers::toLower(trim($imageNode->url)) : null;
1 ✔
314
                                $linkKey = $node->url !== null ? Helpers::toLower(trim($node->url)) : null;
1 ✔
315

316
                                // Resolve the image
317
                                $this->resolveImageNode($imageNode);
1 ✔
318

319
                                // If link URL matches the original image reference (from :: syntax), resolve it too
320
                                if ($imageKey !== null && $linkKey === $imageKey && isset($this->definitions[$imageKey])) {
1 ✔
321
                                        $node->url = $this->definitions[$imageKey]->url;
1 ✔
322
                                }
323
                        }
324
                        return null;
1 ✔
325
                });
1 ✔
326
        }
1 ✔
327

328

329
        private function resolveImageNode(ImageNode $node): void
330
        {
331
                if ($node->url === null) {
1 ✔
332
                        return;
1 ✔
333
                }
334

335
                $key = Helpers::toLower(trim($node->url));
1 ✔
336
                if (!isset($this->definitions[$key])) {
1 ✔
337
                        return;
1 ✔
338
                }
339

340
                $def = $this->definitions[$key];
1 ✔
341

342
                $node->ref = trim($node->url); // keep the written reference name for analyzers
1 ✔
343
                $node->url = $def->url;
1 ✔
344
                $node->alt ??= $def->alt;
1 ✔
345
                $node->width ??= $def->width;
1 ✔
346
                $node->height ??= $def->height;
1 ✔
347

348
                // Use modifier from definition if node doesn't have one
349
                if ($def->modifier && !$node->modifier) {
1 ✔
UNCOV
350
                        $node->modifier = clone $def->modifier;
×
351
                }
352
        }
1 ✔
353

354

355
        /**
356
         * Get image definition by name (for LinkReferenceModule to resolve [*img*] links).
357
         */
358
        public function getDefinition(string $name): ?ImageDefinitionNode
359
        {
360
                return $this->definitions[Helpers::toLower($name)] ?? null;
1 ✔
361
        }
362
}
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