summaryrefslogtreecommitdiff
path: root/platform/www/inc/Parsing/ParserMode/Acronym.php
blob: b42a7b573af67423e6b248b8c2cc63ea148a2608 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php

namespace dokuwiki\Parsing\ParserMode;

class Acronym extends AbstractMode
{
    // A list
    protected $acronyms = array();
    protected $pattern = '';

    /**
     * Acronym constructor.
     *
     * @param string[] $acronyms
     */
    public function __construct($acronyms)
    {
        usort($acronyms, array($this,'compare'));
        $this->acronyms = $acronyms;
    }

    /** @inheritdoc */
    public function preConnect()
    {
        if (!count($this->acronyms)) return;

        $bound = '[\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]';
        $acronyms = array_map(['\\dokuwiki\\Parsing\\Lexer\\Lexer', 'escape'], $this->acronyms);
        $this->pattern = '(?<=^|'.$bound.')(?:'.join('|', $acronyms).')(?='.$bound.')';
    }

    /** @inheritdoc */
    public function connectTo($mode)
    {
        if (!count($this->acronyms)) return;

        if (strlen($this->pattern) > 0) {
            $this->Lexer->addSpecialPattern($this->pattern, $mode, 'acronym');
        }
    }

    /** @inheritdoc */
    public function getSort()
    {
        return 240;
    }

    /**
     * sort callback to order by string length descending
     *
     * @param string $a
     * @param string $b
     *
     * @return int
     */
    protected function compare($a, $b)
    {
        $a_len = strlen($a);
        $b_len = strlen($b);
        if ($a_len > $b_len) {
            return -1;
        } elseif ($a_len < $b_len) {
            return 1;
        }

        return 0;
    }
}