xref: /plugin/fontello/syntax.php (revision 1776c5c5befa8de3cc97e981444f6918b129ab85)
1<?php
2
3use dokuwiki\Extension\SyntaxPlugin;
4
5/**
6 * Syntax component for inline icon rendering.
7 */
8class syntax_plugin_fontello extends SyntaxPlugin
9{
10    /** @var helper_plugin_fontello */
11    protected $helper;
12
13    public function __construct()
14    {
15        $this->helper = $this->loadHelper('fontello');
16    }
17
18    /**
19     * @return string
20     */
21    public function getType()
22    {
23        return 'substition';
24    }
25
26    /**
27     * @return string
28     */
29    public function getPType()
30    {
31        return 'normal';
32    }
33
34    /**
35     * @return int
36     */
37    public function getSort()
38    {
39        return 190;
40    }
41
42    /**
43     * @param string $mode
44     * @return void
45     */
46    public function connectTo($mode)
47    {
48        $this->Lexer->addSpecialPattern('<icon:[A-Za-z0-9_-]+(?:\|(?:toc|notoc))?>', $mode, 'plugin_fontello');
49    }
50
51    /**
52     * @param string $match
53     * @param int $state
54     * @param int $pos
55     * @param Doku_Handler $handler
56     * @return array
57     */
58    public function handle($match, $state, $pos, Doku_Handler $handler)
59    {
60        $token = $this->helper->parseIconToken($match);
61        if ($token === null) {
62            return [
63                'raw' => $match,
64                'name' => '',
65                'class' => null,
66                'missing_package' => false,
67            ];
68        }
69
70        $name = $token['name'];
71        $hasPackage = $this->helper->hasActivePackage();
72        $class = $hasPackage ? $this->helper->getIconClass($name) : null;
73
74        return [
75            'raw' => $match,
76            'name' => $name,
77            'class' => $class,
78            'missing_package' => !$hasPackage,
79        ];
80    }
81
82    /**
83     * @param string $format
84     * @param Doku_Renderer $renderer
85     * @param array $data
86     * @return bool
87     */
88    public function render($format, Doku_Renderer $renderer, $data)
89    {
90        if ($format !== 'xhtml') return false;
91
92        /** @var Doku_Renderer_xhtml $renderer */
93        if (!empty($data['class'])) {
94            $renderer->doc .= '<span class="fontello-icon ' . hsc($data['class']) . '" aria-hidden="true"></span>';
95        } elseif (!empty($data['missing_package'])) {
96            $renderer->doc .= hsc(sprintf($this->getLang('icon_missing_package'), $data['name']));
97        } else {
98            $renderer->doc .= hsc($data['raw']);
99        }
100
101        return true;
102    }
103}
104