1<?php
2/**
3 * DokuWiki Plugin stopwatch (Syntax Component)
4 *
5 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
6 * @author  Janez Paternoster <janez.paternoster@siol.net>
7 */
8
9// must be run within Dokuwiki
10if (!defined('DOKU_INC')) {
11    die();
12}
13
14class syntax_plugin_stopwatch extends DokuWiki_Syntax_Plugin
15{
16    /**
17     * @return string Syntax mode type
18     */
19    public function getType()
20    {
21        return 'substition';
22    }
23
24    /**
25     * @return string Paragraph type
26     */
27    public function getPType()
28    {
29        return 'normal';
30    }
31
32    /**
33     * @return int Sort order - Low numbers go before high numbers
34     */
35    public function getSort()
36    {
37        return 200;
38    }
39
40    /**
41     * Connect lookup pattern to lexer.
42     *
43     * @param string $mode Parser mode
44     */
45    public function connectTo($mode)
46    {
47        $this->Lexer->addSpecialPattern('<stopwatch (?:reset|show)>', $mode, 'plugin_stopwatch');
48    }
49
50    /**
51     * Handle matches of the stopwatch syntax
52     *
53     * @param string       $match   The match of the syntax
54     * @param int          $state   The state of the handler
55     * @param int          $pos     The position in the document
56     * @param Doku_Handler $handler The handler
57     *
58     * @return array Data for the renderer
59     */
60    public function handle($match, $state, $pos, Doku_Handler $handler)
61    {
62        return $match;
63    }
64
65    /**
66     * Render xhtml output or metadata
67     *
68     * @param string        $mode     Renderer mode (supported modes: xhtml)
69     * @param Doku_Renderer $renderer The renderer
70     * @param array         $data     The data from the handler() function
71     *
72     * @return bool If rendering was successful.
73     */
74    public function render($mode, Doku_Renderer $renderer, $data)
75    {
76        static $timestamp = 0.0;
77
78        if ($mode !== 'xhtml') {
79            return false;
80        }
81
82        if($data === '<stopwatch reset>') {
83            $timestamp = hrtime(true);
84        }
85        else if($data === '<stopwatch show>') {
86            $diff = hrtime(true) - $timestamp;
87            $renderer->doc .= number_format($diff/1e+9, 3);
88        }
89
90        return true;
91    }
92}
93