comments and formatting
[plcapi.git] / src / Helper / Logger.php
1 <?php
2
3 namespace PhpXmlRpc\Helper;
4
5 /**
6  * @todo implement an interface
7  * @todo make constructor private to force users to go through `instance()` ?
8  */
9 class Logger
10 {
11     protected static $instance = null;
12
13     /**
14      * This class can be used as singleton, so that later we can move to DI patterns.
15      *
16      * @return Logger
17      */
18     public static function instance()
19     {
20         if (self::$instance === null) {
21             self::$instance = new self();
22         }
23
24         return self::$instance;
25     }
26
27     /**
28      * Echoes a debug message, taking care of escaping it when not in console mode.
29      * NB: if the encoding of the message is not known or wrong, and we are working in web mode, there is no guarantee
30      *     of 100% accuracy, which kind of defeats the purpose of debugging
31      *
32      * @param string $message
33      * @param string $encoding
34      */
35     public function debugMessage($message, $encoding = null)
36     {
37         // US-ASCII is a warning for PHP and a fatal for HHVM
38         if ($encoding == 'US-ASCII') {
39             $encoding = 'UTF-8';
40         }
41
42         if (PHP_SAPI != 'cli') {
43             $flags = ENT_COMPAT;
44             // avoid warnings on php < 5.4...
45             if (defined('ENT_HTML401')) {
46                 $flags =  $flags | ENT_HTML401;
47             }
48             if (defined('ENT_SUBSTITUTE')) {
49                 $flags =  $flags | ENT_SUBSTITUTE;
50             }
51             if ($encoding != null) {
52                 print "<PRE>\n".htmlentities($message, $flags, $encoding)."\n</PRE>";
53             } else {
54                 print "<PRE>\n".htmlentities($message, $flags)."\n</PRE>";
55             }
56         } else {
57             print "\n$message\n";
58         }
59
60         // let the user see this now in case there's a time out later...
61         flush();
62     }
63
64     /**
65      * Writes a message to the error log
66      * @param string $message
67      */
68     public function errorLog($message)
69     {
70         error_log($message);
71     }
72 }