xref: /plugin/dw2pdf/_test/WriterInternalLinksTest.php (revision 943936c78d9f28b06f573833b34fc58e43956f32)
1<?php
2
3namespace dokuwiki\plugin\dw2pdf\test;
4
5use dokuwiki\plugin\dw2pdf\src\AbstractCollector;
6use dokuwiki\plugin\dw2pdf\src\Config;
7use dokuwiki\plugin\dw2pdf\src\Writer;
8use DokuWikiTest;
9
10/**
11 * @group plugin_dw2pdf
12 * @group plugins
13 */
14class WriterInternalLinksTest extends DokuWikiTest
15{
16    public function setUp(): void
17    {
18        parent::setUp();
19        $_REQUEST = [];
20    }
21
22    /**
23     * Internal anchors must be rewritten to section IDs while untouched links remain unchanged.
24     */
25    public function testFixInternalLinksUpdatesKnownTargets(): void
26    {
27        $config = new Config();
28        $collector = new WriterInternalLinksCollectorStub(
29            ['playground:fixlinks', 'playground:other'],
30            $config
31        );
32
33        $html = '<p>'
34            . '<a href="doku.php?id=original" data-dw2pdf-target="playground:fixlinks" data-dw2pdf-hash="abc">First</a>'
35            // missing:id must keep its original href because the collector will not output that page
36            . '<a href="doku.php?id=missing" data-dw2pdf-target="missing:id" data-dw2pdf-hash="def">Second</a>'
37            . '</p>';
38
39        $writer = (new \ReflectionClass(Writer::class))->newInstanceWithoutConstructor();
40        $method = (new \ReflectionClass(Writer::class))->getMethod('fixInternalLinks');
41        $result = $method->invoke($writer, $collector, $html);
42
43        $check = false;
44        $section = sectionID('playground:fixlinks', $check);
45        $this->assertStringContainsString('href="#' . $section . '__abc"', $result);
46        $this->assertStringNotContainsString('data-dw2pdf-target', $result);
47        $this->assertStringContainsString('href="doku.php?id=missing"', $result);
48    }
49}
50
51class WriterInternalLinksCollectorStub extends AbstractCollector
52{
53    /** @var string[] */
54    private array $collectedPages;
55
56    public function __construct(array $pages, Config $config)
57    {
58        $this->collectedPages = $pages;
59        $this->config = $config;
60        $this->pages = $pages;
61        $this->title = 'stub';
62        $this->rev = null;
63        $this->at = null;
64    }
65
66    protected function collect(): array
67    {
68        return $this->collectedPages;
69    }
70}
71