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

dg / texy / 18944959976

30 Oct 2025 02:55PM UTC coverage: 92.746%. Remained the same
18944959976

push

github

dg
HtmlElement: removed toHtml() & toText()

18 of 19 new or added lines in 5 files covered. (94.74%)

12 existing lines in 2 files now uncovered.

2391 of 2578 relevant lines covered (92.75%)

0.93 hits per line

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

97.08
/src/Texy/Modules/LinkModule.php
1
<?php
2

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

8
declare(strict_types=1);
9

10
namespace Texy\Modules;
11

12
use Texy;
13
use Texy\HandlerInvocation;
14
use Texy\LineParser;
15
use Texy\Link;
16
use Texy\Patterns;
17
use Texy\Regexp;
18
use function iconv_strlen, iconv_substr, link, preg_match, str_contains, str_replace, strlen, strncasecmp, strpos, substr, trim, urlencode;
19

20

21
/**
22
 * Links module.
23
 */
24
final class LinkModule extends Texy\Module
25
{
26
        /** root of relative links */
27
        public ?string $root = null;
28

29
        /** linked image class */
30
        public ?string $imageClass = null;
31

32
        /** always use rel="nofollow" for absolute links? */
33
        public bool $forceNoFollow = false;
34

35
        /** shorten URLs to more readable form? */
36
        public bool $shorten = true;
37

38
        /** @var array<string, Link> link references */
39
        private array $references = [];
40

41
        /** @var array<string, bool> */
42
        private static array $livelock;
43

44
        private static string $EMAIL;
45

46

47
        public function __construct(Texy\Texy $texy)
1✔
48
        {
49
                $this->texy = $texy;
1✔
50

51
                $texy->allowed['link/definition'] = true;
1✔
52
                $texy->addHandler('newReference', $this->newReferenceToElement(...));
1✔
53
                $texy->addHandler('linkReference', $this->linkToElement(...));
1✔
54
                $texy->addHandler('linkEmail', $this->urlEmailToElement(...));
1✔
55
                $texy->addHandler('linkURL', $this->urlEmailToElement(...));
1✔
56
                $texy->addHandler('beforeParse', $this->beforeParse(...));
1✔
57

58
                // [reference]
59
                $texy->registerLinePattern(
1✔
60
                        $this->parseReference(...),
1✔
61
                        '~(
62
                                \[
63
                                [^\[\]*\n' . Patterns::MARK . ']++  # reference
1✔
64
                                ]
65
                        )~U',
66
                        'link/reference',
1✔
67
                );
68

69
                // direct url; characters not allowed in URL <>[\]^`{|}
70
                $texy->registerLinePattern(
1✔
71
                        $this->parseUrlEmail(...),
1✔
72
                        '~
73
                                (?<= ^ | [\s([<:\x17] )            # must be preceded by these chars
74
                                (?: https?:// | www\. | ftp:// )   # protocol or www
75
                                [0-9.' . Patterns::CHAR . '-]      # first char
76
                                [/\d' . Patterns::CHAR . '+.\~%&?@=_:;#$!,*()\x{ad}-]{1,1000}  # URL body
77
                                [/\d' . Patterns::CHAR . '+\~?@=_#$*]  # last char
1✔
78
                        ~',
79
                        'link/url',
1✔
80
                        '~(?: https?:// | www\. | ftp://)~',
1✔
81
                );
82

83
                // direct email
84
                self::$EMAIL = '
1✔
85
                        [' . Patterns::CHAR . ']                 # first char
86
                        [0-9.+_' . Patterns::CHAR . '-]{0,63}    # local part
87
                        @
88
                        [0-9.+_' . Patterns::CHAR . '\x{ad}-]{1,252} # domain
89
                        \.
90
                        [' . Patterns::CHAR . '\x{ad}]{2,19}     # TLD
91
                ';
92
                $texy->registerLinePattern(
1✔
93
                        $this->parseUrlEmail(...),
1✔
94
                        '~
95
                                (?<= ^ | [\s([<\x17] )             # must be preceded by these chars
96
                                ' . self::$EMAIL . '
1✔
97
                        ~',
98
                        'link/email',
1✔
99
                        '~' . self::$EMAIL . '~',
1✔
100
                );
101
        }
1✔
102

103

104
        /**
105
         * Text pre-processing.
106
         */
107
        private function beforeParse(Texy\Texy $texy, &$text): void
1✔
108
        {
109
                self::$livelock = [];
1✔
110

111
                // [la trine]: http://www.latrine.cz/ text odkazu .(title)[class]{style}
112
                if (!empty($texy->allowed['link/definition'])) {
1✔
113
                        $text = Texy\Regexp::replace(
1✔
114
                                $text,
1✔
115
                                '~^
116
                                        \[
117
                                        ( [^\[\]#?*\n]{1,100} )           # reference (1)
118
                                        ] : \ ++
119
                                        ( \S{1,1000} )                    # URL (2)
120
                                        ( [ \t] .{1,1000} )?              # optional description (3)
121
                                        ' . Patterns::MODIFIER . '?       # modifier (4)
1✔
122
                                        \s*
123
                                $~mU',
124
                                $this->parseReferenceDef(...),
1✔
125
                        );
126
                }
127
        }
1✔
128

129

130
        /**
131
         * Callback for: [la trine]: http://www.latrine.cz/ text odkazu .(title)[class]{style}.
132
         */
133
        private function parseReferenceDef(array $matches): string
1✔
134
        {
135
                [, $mRef, $mLink, $mLabel, $mMod] = $matches;
1✔
136
                // [1] => [ (reference) ]
137
                // [2] => link
138
                // [3] => ...
139
                // [4] => .(title)[class]{style}
140

141
                $link = new Link($mLink);
1✔
142
                $link->label = trim($mLabel ?? '');
1✔
143
                $link->modifier->setProperties($mMod);
1✔
144
                $this->checkLink($link);
1✔
145
                $this->addReference($mRef, $link);
1✔
146
                return '';
1✔
147
        }
148

149

150
        /**
151
         * Callback for: [ref].
152
         */
153
        public function parseReference(LineParser $parser, array $matches): Texy\HtmlElement|string|null
1✔
154
        {
155
                [, $mRef] = $matches;
1✔
156
                // [1] => [ref]
157

158
                $texy = $this->texy;
1✔
159
                $name = substr($mRef, 1, -1);
1✔
160
                $link = $this->getReference($name);
1✔
161

162
                if (!$link) {
1✔
163
                        return $texy->invokeAroundHandlers('newReference', $parser, [$name]);
1✔
164
                }
165

166
                $link->type = $link::BRACKET;
1✔
167

168
                if ($link->label != '') { // null or ''
1✔
169
                        // prevent circular references
170
                        if (isset(self::$livelock[$link->name])) {
1✔
171
                                $content = $link->label;
×
172
                        } else {
173
                                self::$livelock[$link->name] = true;
1✔
174
                                $el = new Texy\HtmlElement;
1✔
175
                                $lineParser = new LineParser($texy);
1✔
176
                                $el->inject($lineParser->parse($link->label));
1✔
177
                                $content = $texy->elemToMaskedString($el);
1✔
178
                                unset(self::$livelock[$link->name]);
1✔
179
                        }
180
                } else {
181
                        $content = $this->textualUrl($link);
1✔
182
                        $content = $this->texy->protect($content, $texy::CONTENT_TEXTUAL);
1✔
183
                }
184

185
                return $texy->invokeAroundHandlers('linkReference', $parser, [$link, $content]);
1✔
186
        }
187

188

189
        /**
190
         * Callback for: http://davidgrudl.com david@grudl.com.
191
         */
192
        public function parseUrlEmail(LineParser $parser, array $matches, string $name): Texy\HtmlElement|string|null
1✔
193
        {
194
                [$mURL] = $matches;
1✔
195
                // [0] => URL
196

197
                $link = new Link($mURL);
1✔
198
                $this->checkLink($link);
1✔
199

200
                return $this->texy->invokeAroundHandlers(
1✔
201
                        $name === 'link/email' ? 'linkEmail' : 'linkURL',
1✔
202
                        $parser,
203
                        [$link],
1✔
204
                );
205
        }
206

207

208
        /**
209
         * Adds new named reference.
210
         */
211
        public function addReference(string $name, Link $link): void
1✔
212
        {
213
                $link->name = Texy\Helpers::toLower($name);
1✔
214
                $this->references[$link->name] = $link;
1✔
215
        }
1✔
216

217

218
        /**
219
         * Returns named reference.
220
         */
221
        public function getReference(string $name): ?Link
1✔
222
        {
223
                $name = Texy\Helpers::toLower($name);
1✔
224
                if (isset($this->references[$name])) {
1✔
225
                        return clone $this->references[$name];
1✔
226

227
                } else {
228
                        $pos = strpos($name, '?');
1✔
229
                        if ($pos === false) {
1✔
230
                                $pos = strpos($name, '#');
1✔
231
                        }
232

233
                        if ($pos !== false) { // try to extract ?... #... part
1✔
234
                                $name2 = substr($name, 0, $pos);
1✔
235
                                if (isset($this->references[$name2])) {
1✔
236
                                        $link = clone $this->references[$name2];
1✔
237
                                        $link->URL .= substr($name, $pos);
1✔
238
                                        return $link;
1✔
239
                                }
240
                        }
241
                }
242

243
                return null;
1✔
244
        }
245

246

247
        public function factoryLink(string $dest, ?string $mMod, ?string $label): Link
1✔
248
        {
249
                $texy = $this->texy;
1✔
250
                $type = Link::COMMON;
1✔
251

252
                // [ref]
253
                if (strlen($dest) > 1 && $dest[0] === '[' && $dest[1] !== '*') {
1✔
254
                        $type = Link::BRACKET;
1✔
255
                        $dest = substr($dest, 1, -1);
1✔
256
                        $link = $this->getReference($dest);
1✔
257

258
                // [* image *]
259
                } elseif (strlen($dest) > 1 && $dest[0] === '[' && $dest[1] === '*') {
1✔
260
                        $type = Link::IMAGE;
1✔
261
                        $dest = trim(substr($dest, 2, -2));
1✔
262
                        $image = $texy->imageModule->getReference($dest);
1✔
263
                        if ($image) {
1✔
264
                                $link = new Link($image->linkedURL ?? $image->URL);
1✔
265
                                $link->modifier = $image->modifier;
1✔
266
                        }
267
                }
268

269
                if (empty($link)) {
1✔
270
                        $link = new Link(trim($dest));
1✔
271
                        $this->checkLink($link);
1✔
272
                }
273

274
                if (str_contains((string) $link->URL, '%s')) {
1✔
NEW
275
                        $link->URL = str_replace('%s', urlencode($texy->maskedStringToText($label)), $link->URL);
×
276
                }
277

278
                $link->modifier->setProperties($mMod);
1✔
279
                $link->type = $type;
1✔
280
                return $link;
1✔
281
        }
282

283

284
        public function linkToElement(
1✔
285
                ?HandlerInvocation $invocation,
286
                Link $link,
287
                Texy\HtmlElement|string|null $content = null,
288
        ): Texy\HtmlElement|string
289
        {
290
                if ($link->URL == null) {
1✔
291
                        return $content;
1✔
292
                }
293

294
                $texy = $this->texy;
1✔
295

296
                $el = new Texy\HtmlElement('a');
1✔
297

298
                if (empty($link->modifier)) {
1✔
299
                        $nofollow = false;
×
300
                } else {
301
                        $nofollow = isset($link->modifier->classes['nofollow']);
1✔
302
                        unset($link->modifier->classes['nofollow']);
1✔
303
                        $el->attrs['href'] = null; // trick - move to front
1✔
304
                        $link->modifier->decorate($texy, $el);
1✔
305
                }
306

307
                if ($link->type === Link::IMAGE) {
1✔
308
                        // image
309
                        $el->attrs['href'] = Texy\Helpers::prependRoot($link->URL, $texy->imageModule->linkedRoot);
1✔
310
                        if ($this->imageClass) {
1✔
311
                                $el->attrs['class'][] = $this->imageClass;
1✔
312
                        }
313
                } else {
314
                        $el->attrs['href'] = Texy\Helpers::prependRoot($link->URL, $this->root);
1✔
315

316
                        // rel="nofollow"
317
                        if ($nofollow || ($this->forceNoFollow && str_contains($el->attrs['href'], '//'))) {
1✔
318
                                $el->attrs['rel'] = 'nofollow';
1✔
319
                        }
320
                }
321

322
                if ($content !== null) {
1✔
323
                        $el->add($content);
1✔
324
                }
325

326
                $texy->summary['links'][] = $el->attrs['href'];
1✔
327

328
                return $el;
1✔
329
        }
330

331

332
        public function urlEmailToElement(HandlerInvocation $invocation, Link $link): Texy\HtmlElement|string
1✔
333
        {
334
                $content = $this->textualUrl($link);
1✔
335
                $content = $this->texy->protect($content, Texy\Texy::CONTENT_TEXTUAL);
1✔
336
                return $this->linkToElement(null, $link, $content);
1✔
337
        }
338

339

340
        public function newReferenceToElement(HandlerInvocation $invocation, string $name)
1✔
341
        {
342
                // no change
343
        }
1✔
344

345

346
        /**
347
         * Checks and corrects $URL.
348
         */
349
        private function checkLink(Link $link): void
1✔
350
        {
351
                // remove soft hyphens; if not removed by Texy\Texy::process()
352
                $link->URL = str_replace("\u{AD}", '', $link->URL);
1✔
353

354
                if (strncasecmp($link->URL, 'www.', 4) === 0) {
1✔
355
                        // special supported case
356
                        $link->URL = 'http://' . $link->URL;
1✔
357

358
                } elseif (Regexp::match($link->URL, '~' . self::$EMAIL . '$~A')) {
1✔
359
                        // email
360
                        $link->URL = 'mailto:' . $link->URL;
1✔
361

362
                } elseif (!$this->texy->checkURL($link->URL, Texy\Texy::FILTER_ANCHOR)) {
1✔
363
                        $link->URL = null;
1✔
364

365
                } else {
366
                        $link->URL = str_replace('&amp;', '&', $link->URL); // replace unwanted &amp;
1✔
367
                }
368
        }
1✔
369

370

371
        /**
372
         * Returns textual representation of URL.
373
         */
374
        private function textualUrl(Link $link): string
1✔
375
        {
376
                if ($this->texy->obfuscateEmail && Regexp::match($link->raw, '~^' . self::$EMAIL . '$~')) { // email
1✔
377
                        return str_replace('@', '&#64;<!-- -->', $link->raw);
1✔
378
                }
379

380
                if ($this->shorten && Regexp::match($link->raw, '~^(https?://|ftp://|www\.|/)~i')) {
1✔
381
                        $raw = strncasecmp($link->raw, 'www.', 4) === 0
1✔
382
                                ? 'none://' . $link->raw
1✔
383
                                : $link->raw;
1✔
384

385
                        // parse_url() in PHP damages UTF-8 - use regular expression
386
                        if (!($parts = Regexp::match($raw, '~^
1✔
387
                                (?: (?P<scheme> [a-z]+ ) : )?
388
                                (?: // (?P<host> [^/?#]+ ) )?
389
                                (?P<path> (?: / | ^ ) (?! / ) [^?#]* )?
390
                                (?: \? (?P<query> [^#]* ) )?
391
                                (?: \# (?P<fragment> .* ) )?
392
                                $
393
                        ~'))) {
394
                                return $link->raw;
×
395
                        }
396

397
                        $res = '';
1✔
398
                        if ($parts['scheme'] !== null && $parts['scheme'] !== 'none') {
1✔
399
                                $res .= $parts['scheme'] . '://';
1✔
400
                        }
401

402
                        if ($parts['host'] !== null) {
1✔
403
                                $res .= $parts['host'];
1✔
404
                        }
405

406
                        if ($parts['path'] !== null) {
1✔
407
                                $res .= (iconv_strlen($parts['path'], 'UTF-8') > 16 ? ("/\u{2026}" . iconv_substr($parts['path'], -12, 12, 'UTF-8')) : $parts['path']);
1✔
408
                        }
409

410
                        if ($parts['query'] > '') {
1✔
411
                                $res .= iconv_strlen($parts['query'], 'UTF-8') > 4
1✔
412
                                        ? "?\u{2026}"
×
413
                                        : ('?' . $parts['query']);
1✔
414
                        } elseif ($parts['fragment'] > '') {
1✔
415
                                $res .= iconv_strlen($parts['fragment'], 'UTF-8') > 4
1✔
416
                                        ? "#\u{2026}"
1✔
417
                                        : ('#' . $parts['fragment']);
1✔
418
                        }
419

420
                        return $res;
1✔
421
                }
422

423
                return $link->raw;
1✔
424
        }
425
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc