1<?php
2
3namespace dokuwiki\Parsing\Handler;
4
5class Quote extends AbstractRewriter
6{
7    protected $quoteCalls = array();
8
9    /** @inheritdoc */
10    public function finalise()
11    {
12        $last_call = end($this->calls);
13        $this->writeCall(array('quote_end',array(), $last_call[2]));
14
15        $this->process();
16        $this->callWriter->finalise();
17        unset($this->callWriter);
18    }
19
20    /** @inheritdoc */
21    public function process()
22    {
23
24        $quoteDepth = 1;
25
26        foreach ($this->calls as $call) {
27            switch ($call[0]) {
28
29                /** @noinspection PhpMissingBreakStatementInspection */
30                case 'quote_start':
31                    $this->quoteCalls[] = array('quote_open',array(),$call[2]);
32                    // fallthrough
33                case 'quote_newline':
34                    $quoteLength = $this->getDepth($call[1][0]);
35
36                    if ($quoteLength > $quoteDepth) {
37                        $quoteDiff = $quoteLength - $quoteDepth;
38                        for ($i = 1; $i <= $quoteDiff; $i++) {
39                            $this->quoteCalls[] = array('quote_open',array(),$call[2]);
40                        }
41                    } elseif ($quoteLength < $quoteDepth) {
42                        $quoteDiff = $quoteDepth - $quoteLength;
43                        for ($i = 1; $i <= $quoteDiff; $i++) {
44                            $this->quoteCalls[] = array('quote_close',array(),$call[2]);
45                        }
46                    } else {
47                        if ($call[0] != 'quote_start') $this->quoteCalls[] = array('linebreak',array(),$call[2]);
48                    }
49
50                    $quoteDepth = $quoteLength;
51
52                    break;
53
54                case 'quote_end':
55                    if ($quoteDepth > 1) {
56                        $quoteDiff = $quoteDepth - 1;
57                        for ($i = 1; $i <= $quoteDiff; $i++) {
58                            $this->quoteCalls[] = array('quote_close',array(),$call[2]);
59                        }
60                    }
61
62                    $this->quoteCalls[] = array('quote_close',array(),$call[2]);
63
64                    $this->callWriter->writeCalls($this->quoteCalls);
65                    break;
66
67                default:
68                    $this->quoteCalls[] = $call;
69                    break;
70            }
71        }
72
73        return $this->callWriter;
74    }
75
76    /**
77     * @param string $marker
78     * @return int
79     */
80    protected function getDepth($marker)
81    {
82        preg_match('/>{1,}/', $marker, $matches);
83        $quoteLength = strlen($matches[0]);
84        return $quoteLength;
85    }
86}
87