Subversion Repositories ALCASAR

Rev

Details | Last modification | View Log

Rev Author Line No. Line
3241 rexy 1
<?php
2
 
3
namespace mbolli\nfsen_ng\common;
4
 
5
class Debug {
6
    private readonly float $stopwatch;
7
    private bool $debug = true;
8
    private readonly bool $cli;
9
    public static ?self $_instance = null;
10
 
11
    public function __construct() {
12
        $this->stopwatch = microtime(true);
13
        $this->cli = (\PHP_SAPI === 'cli');
14
    }
15
 
16
    public static function getInstance(): self {
17
        if (!(self::$_instance instanceof self)) {
18
            self::$_instance = new self();
19
        }
20
 
21
        return self::$_instance;
22
    }
23
 
24
    /**
25
     * Logs the message if allowed in settings.
26
     */
27
    public function log(string $message, int $priority): void {
28
        if (Config::$cfg['log']['priority'] >= $priority) {
29
            syslog($priority, 'nfsen-ng: ' . $message);
30
 
31
            if ($this->cli === true && $this->debug === true) {
32
                echo date('Y-m-d H:i:s') . ' ' . $message . \PHP_EOL;
33
            }
34
        }
35
    }
36
 
37
    /**
38
     * Returns the time passed from initialization.
39
     */
40
    public function stopWatch(bool $precise = false): float {
41
        $result = microtime(true) - $this->stopwatch;
42
        if ($precise === false) {
43
            $result = round($result, 4);
44
        }
45
 
46
        return $result;
47
    }
48
 
49
    /**
50
     * Debug print. Prints the supplied string with the time passed from initialization.
51
     */
52
    public function dpr(...$mixed): void {
53
        if ($this->debug === false) {
54
            return;
55
        }
56
 
57
        foreach ($mixed as $param) {
58
            echo ($this->cli) ? \PHP_EOL . $this->stopWatch() . 's ' : "<br /><span style='color: green;'>" . $this->stopWatch() . '</span> ';
59
            if (\is_array($param)) {
60
                echo ($this->cli) ? print_r($mixed, true) : '<pre>', var_export($mixed, true), '</pre>';
61
            } else {
62
                echo $param;
63
            }
64
        }
65
    }
66
 
67
    public function setDebug(bool $debug): void {
68
        $this->debug = $debug;
69
    }
70
}