Test Failed
Push — master ( 98e7c7...9809da )
by Vítězslav
04:13
created

ToFile::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
rs 10
1
<?php
2
/**
3
 * Třída pro logování.
4
 *
5
 * @author    Vitex <[email protected]>
6
 * @copyright 2009-2016 [email protected] (G)
7
 */
8
9
namespace Ease\Logger;
10
11
class ToFile extends ToMemory implements Loggingable
12
{
13
    /**
14
     * Předvolená metoda logování.
15
     *
16
     * @var string
17
     */
18
    public $logType = 'file';
19
20
    /**
21
     * Adresář do kterého se zapisují logy.
22
     *
23
     * @var string dirpath
24
     */
25
    public $logPrefix = null;
26
27
    /**
28
     * Soubor s do kterého se zapisuje log.
29
     *
30
     * @var string
31
     */
32
    public $logFileName = 'Ease.log';
33
34
    /**
35
     * úroveň logování.
36
     *
37
     * @var string - silent,debug
38
     */
39
    public $logLevel = 'debug';
40
41
    /**
42
     * Soubor do kterého se lougují pouze zprávy typu Error.
43
     *
44
     * @var string filepath
45
     */
46
    public $errorLogFile = 'EaseErrors.log';
47
48
    /**
49
     * Odkaz na vlastnící objekt.
50
     *
51
     * @var \Ease\Sand
52
     */
53
    public $parentObject = null;
54
55
    /**
56
     * Filedescriptor Logu.
57
     *
58
     * @var resource
59
     */
60
    private $_logFileHandle = null;
61
62
    /**
63
     * Filedescriptor chybového Logu.
64
     *
65
     * @var resource
66
     */
67
    private $_errorLogFileHandle = null;
68
69
    /**
70
     * ID naposledy ulozene zpravy.
71
     *
72
     * @var int unsigned
73
     */
74
    private $messageID = 0;
75
76
    /**
77
     * Obecné konfigurace frameworku.
78
     *
79
     * @var \Ease\Shared
80
     */
81
    public $easeShared = null;
82
83
    /**
84
     * Saves obejct instace (singleton...).
85
     */
86
    private static $instance = null;
87
88
    /**
89
     * Logovací třída.
90
     *
91
     * @param string $baseLogDir
92
     */
93
    public function __construct($baseLogDir = null)
94
    {
95
        $this->setupLogFiles($baseLogDir);
96
    }
97
98
    /**
99
     * Get instanece of File Logger
100
     * 
101
     * @param string $logdir
102
     * 
103
     * @return ToFile
104
     */
105
    public static function singleton($logdir = null)
106
    {
107
        if (!isset(self::$instance)) {
108
            self::$instance = new self($logdir);
109
        }
110
111
        return self::$instance;
112
    }
113
114
    /**
115
     * Nastaví cesty logovacích souborů.
116
     * @param string $baseLogDir
117
     */
118
    public function setupLogFiles($baseLogDir = null)
119
    {
120
        if (is_null($baseLogDir)) {
121
            $baseLogDir = $this->logPrefix;
122
        }
123
124
        if (is_null($baseLogDir) && defined('LOG_DIRECTORY')) {
0 ignored issues
show
introduced by
The condition is_null($baseLogDir) is always false.
Loading history...
125
            $baseLogDir = constant('LOG_DIRECTORY');
126
        }
127
128
        if (!empty($baseLogDir)) {
129
            $this->logPrefix = \Ease\Functions::sysFilename($baseLogDir);
130
            if ($this->testDirectory($this->logPrefix)) {
131
                $this->logFileName  = $this->logPrefix.$this->logFileName;
132
                $this->errorLogFile = $this->logPrefix.$this->errorLogFile;
133
            } else {
134
                $this->logPrefix    = null;
135
                $this->logFileName  = null;
136
                $this->errorLogFile = null;
137
            }
138
        } else {
139
            $this->logType      = 'none';
140
            $this->logPrefix    = null;
141
            $this->logFileName  = null;
142
            $this->errorLogFile = null;
143
        }
144
    }
145
146
    /**
147
     * Zapise zapravu do logu.
148
     *
149
     * @param string $caller  název volajícího objektu
150
     * @param string $message zpráva
151
     * @param string $type    typ zprávy (success|info|error|warning|*)
152
     *
153
     * @return null|boolean byl report zapsán ?
154
     */
155
    public function addToLog($caller, $message, $type = 'message')
156
    {
157
        ++$this->messageID;
158
        if (($this->logLevel == 'silent') && ($type != 'error')) {
159
            return;
160
        }
161
        if (($this->logLevel != 'debug') && ($type == 'debug')) {
162
            return;
163
        }
164
        $this->statusMessages[$type][$this->messageID] = $message;
165
166
        $message = htmlspecialchars_decode(strip_tags(stripslashes($message)));
167
168
        $logLine = date(DATE_ATOM).' ('.$caller.') '.str_replace(['notice', 'message',
169
                'debug', 'error', 'warning', 'success', 'info', 'mail',],
170
                ['**', '##', '@@', '::'], $type).' '.$message."\n";
171
        if (!isset($this->logStyles[$type])) {
172
            $type = 'notice';
173
        }
174
        if ($this->logType == 'console' || $this->logType == 'both') {
175
            if (php_sapi_name() == 'cli') {
176
                echo $logLine;
177
            } else {
178
                echo '<div style="'.$this->logStyles[$type].'">'.$logLine."</div>\n";
179
                flush();
180
            }
181
        }
182
        if (!empty($this->logPrefix)) {
183
            if ($this->logType == 'file' || $this->logType == 'both') {
184
                if (!empty($this->logFileName)) {
185
                    if (!$this->_logFileHandle) {
186
                        $this->_logFileHandle = fopen($this->logFileName, 'a+');
0 ignored issues
show
Documentation Bug introduced by
It seems like fopen($this->logFileName, 'a+') can also be of type false. However, the property $_logFileHandle is declared as type resource. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
187
                    }
188
                    if ($this->_logFileHandle !== null) {
189
                        fwrite($this->_logFileHandle, $logLine);
190
                    }
191
                }
192
            }
193
            if ($type == 'error') {
194
                if (!empty($this->errorLogFile)) {
195
                    if (!$this->_errorLogFileHandle) {
196
                        $this->_errorLogFileHandle = fopen($this->errorLogFile,
0 ignored issues
show
Documentation Bug introduced by
It seems like fopen($this->errorLogFile, 'a+') can also be of type false. However, the property $_errorLogFileHandle is declared as type resource. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
197
                            'a+');
198
                    }
199
                    if ($this->_errorLogFileHandle) {
200
                        fputs($this->_errorLogFileHandle, $logLine);
201
                    }
202
                }
203
            }
204
        }
205
206
        return true;
207
    }
208
209
    /**
210
     * Zkontroluje stav adresáře a upozorní na případné nesnáze.
211
     *
212
     * @param string $directoryPath cesta k adresáři
213
     * @param bool   $isDir         detekovat existenci adresáře
214
     * @param bool   $isReadable    testovat čitelnost
215
     * @param bool   $isWritable    testovat zapisovatelnost
216
     *
217
     * @return bool konečný výsledek testu
218
     */
219
    public static function testDirectory($directoryPath, $isDir = true,
220
                                         $isReadable = true, $isWritable = true)
221
    {
222
        if ($isDir && !is_dir($directoryPath)) {
223
            throw new \Exception($directoryPath._(' is not an folder. Current directory:').' '.getcwd());
224
        }
225
        if ($isReadable && !is_readable($directoryPath)) {
226
            throw new \Exception($directoryPath._(' not an readable folder. Current directory:').' '.getcwd());
227
        }
228
        if ($isWritable && !is_writable($directoryPath)) {
229
            throw new \Exception($directoryPath._(' not an writeable folder. Current directory:').' '.getcwd());
230
        }
231
        return true;
232
    }
233
234
    /**
235
     * Oznamuje chybovou událost.
236
     * 
237
     * @deprecated since version 1.0
238
     *
239
     * @param string $caller     název volající funkce, nebo objektu
240
     * @param string $message    zpráva
241
     * @param mixed  $objectData data k zaznamenání
242
     */
243
    public function error($caller, $message, $objectData = null)
244
    {
245
        if ($this->errorLogFile) {
246
            $logFileHandle = fopen($this->errorLogFile, 'a+');
247
            if ($logFileHandle) {
0 ignored issues
show
introduced by
$logFileHandle is of type false|resource, thus it always evaluated to false.
Loading history...
248
                if (php_sapi_name() == 'clie') {
249
                    fputs($logFileHandle,
250
                        \Ease\Brick::printPreBasic($_ENV)."\n #End of CLI enviroment  <<<<<<<<<<<<<<<<<<<<<<<<<<< # \n\n");
251
                } else {
252
                    fputs($logFileHandle,
253
                        \Ease\Brick::printPreBasic($_SERVER)."\n #End of Server enviroment  <<<<<<<<<<<<<<<<<<<<<<<<<<< # \n\n");
254
                }
255
                if (isset($_POST) && count($_POST)) {
256
                    fputs($logFileHandle,
257
                        \Ease\Brick::printPreBasic($_POST)."\n #End of _POST  <<<<<<<<<<<<<<<<<<<<<<<<<<< # \n\n");
258
                }
259
                if (isset($_GET) && count($_GET)) {
260
                    fputs($logFileHandle,
261
                        \Ease\Brick::printPreBasic($_GET)."\n #End of _GET enviroment  <<<<<<<<<<<<<<<<<<<<<<<<<<< # \n\n");
262
                }
263
                if ($objectData) {
264
                    fputs($logFileHandle,
265
                        \Ease\Brick::printPreBasic($objectData)."\n #End of ObjectData >>>>>>>>>>>>>>>>>>>>>>>>>>>># \n\n");
266
                }
267
                fclose($logFileHandle);
268
            } else {
269
                throw new Exception('Error: Couldn\'t open the '.realpath($this->errorLogFile).' error log file');
0 ignored issues
show
Bug introduced by
The type Ease\Logger\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
270
            }
271
        }
272
        $this->addToLog($caller, $message, 'error');
273
    }
274
275
    /**
276
     * Uzavře chybové soubory.
277
     */
278
    public function __destruct()
279
    {
280
        if ($this->_logFileHandle) {
281
            fclose($this->_logFileHandle);
282
        }
283
        if ($this->_errorLogFileHandle) {
284
            fclose($this->_errorLogFileHandle);
285
        }
286
    }
287
288
    /**
289
     * Vrací styl logování.
290
     *
291
     * @param string $logType typ logu warning|info|success|error|notice|*
292
     *
293
     * @return string
294
     */
295
    public function getLogStyle($logType = 'notice')
296
    {
297
        if (key_exists($logType, $this->logStyles)) {
298
            return $this->logStyles[$logType];
299
        } else {
300
            return '';
301
        }
302
    }
303
}
304