1<?php
2
3namespace dokuwiki\Parsing\ParserMode;
4
5class Acronym extends AbstractMode
6{
7    // A list
8    protected $acronyms = array();
9    protected $pattern = '';
10
11    /**
12     * Acronym constructor.
13     *
14     * @param string[] $acronyms
15     */
16    public function __construct($acronyms)
17    {
18        usort($acronyms, array($this,'compare'));
19        $this->acronyms = $acronyms;
20    }
21
22    /** @inheritdoc */
23    public function preConnect()
24    {
25        if (!count($this->acronyms)) return;
26
27        $bound = '[\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]';
28        $acronyms = array_map(['\\dokuwiki\\Parsing\\Lexer\\Lexer', 'escape'], $this->acronyms);
29        $this->pattern = '(?<=^|'.$bound.')(?:'.join('|', $acronyms).')(?='.$bound.')';
30    }
31
32    /** @inheritdoc */
33    public function connectTo($mode)
34    {
35        if (!count($this->acronyms)) return;
36
37        if (strlen($this->pattern) > 0) {
38            $this->Lexer->addSpecialPattern($this->pattern, $mode, 'acronym');
39        }
40    }
41
42    /** @inheritdoc */
43    public function getSort()
44    {
45        return 240;
46    }
47
48    /**
49     * sort callback to order by string length descending
50     *
51     * @param string $a
52     * @param string $b
53     *
54     * @return int
55     */
56    protected function compare($a, $b)
57    {
58        $a_len = strlen($a);
59        $b_len = strlen($b);
60        if ($a_len > $b_len) {
61            return -1;
62        } elseif ($a_len < $b_len) {
63            return 1;
64        }
65
66        return 0;
67    }
68}
69