1<?php
2
3declare(strict_types=1);
4
5use dokuwiki\Extension\SyntaxPlugin;
6
7/**
8 * DokuWiki Plugin today (Syntax Component)
9 *
10 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
11 * @author  Michael Große <mic.grosse+dokuwiki@googlemail.com>
12 */
13final class syntax_plugin_today_today extends SyntaxPlugin
14{
15    /**
16     * @return string Syntax mode type
17     */
18    public function getType(): string
19    {
20        return 'substition';
21    }
22
23    /**
24     * @return string Paragraph type
25     */
26    public function getPType(): string
27    {
28        return 'normal';
29    }
30
31    /**
32     * @return int Sort order - Low numbers go before high numbers
33     */
34    public function getSort(): int
35    {
36        return 1000;
37    }
38
39    /**
40     * Connect lookup pattern to lexer.
41     *
42     * @param string $mode Parser mode
43     */
44    public function connectTo($mode): void
45    {
46        $this->Lexer->addSpecialPattern('\{today.*?\}', $mode, 'plugin_today_today');
47    }
48
49    /**
50     * Handle matches of the today syntax
51     *
52     * @param string       $match   The match of the syntax
53     * @param int          $state   The state of the handler
54     * @param int          $pos     The position in the document
55     * @param Doku_Handler $handler The handler
56     *
57     * @return array Data for the renderer
58     */
59    public function handle($match, $state, $pos, Doku_Handler $handler): array
60    {
61        $data = trim(substr($match, strlen('{today'), -1));
62        $parts = explode(' ', $data);
63
64        return [
65            'namespace' => $parts[0] ?? null,
66            'format' => $parts[1] ?? null,
67        ];
68    }
69
70    /**
71     * Render xhtml output or metadata
72     *
73     * @param string        $mode     Renderer mode (supported modes: xhtml)
74     * @param Doku_Renderer $renderer The renderer
75     * @param array         $data     The data from the handler() function
76     *
77     * @return bool If rendering was successful.
78     */
79    public function render($mode, Doku_Renderer $renderer, $data): bool
80    {
81        if ($mode !== 'xhtml') {
82            return false;
83        }
84
85        $namespace = $data['namespace'] ?? '';
86        $format = $data['format'] ?? 'Y-m-d';
87        $today = date($format);
88        $pageId = $namespace . ':' . $today;
89        $renderer->internallink($pageId, 'today');
90
91        return true;
92    }
93}
94