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