Passed
Push — master ( c01c31...d9cbe6 )
by Radu
01:46
created

FileLogger::debug()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
namespace WebServCo\Framework;
3
4
use WebServCo\Framework\Interfaces\RequestInterface;
5
use WebServCo\Framework\Exceptions\ApplicationException;
6
7
final class FileLogger implements \WebServCo\Framework\Interfaces\LoggerInterface
8
{
9
    protected $channel;
10
    protected $logPath;
11
    protected $requestInterface;
12
13
    public function __construct($channel, $logDir, RequestInterface $requestInterface)
14
    {
15
        $this->channel = $channel;
16
17
        if (!is_readable($logDir)) {
18
            throw new ApplicationException('Log dir not readable');
19
        }
20
        if (!is_writable($logDir)) {
21
            throw new ApplicationException('Log dir not writeable');
22
        }
23
        $this->logPath = sprintf('%s%s.log', $logDir, $this->channel);
24
25
        if (!($requestInterface instanceof RequestInterface)) {
0 ignored issues
show
introduced by
$requestInterface is always a sub-type of WebServCo\Framework\Interfaces\RequestInterface.
Loading history...
26
            throw new ApplicationException('Missing RequestInterface');
27
        }
28
        $this->requestInterface = $requestInterface;
29
    }
30
31
    public function debug($message, $context = [])
32
    {
33
        return $this->log(\WebServCo\Framework\LogLevel::DEBUG, $message, $context);
34
    }
35
36
    public function log($level, $message, $context = [])
37
    {
38
        $data = sprintf(
39
            '[%s] [%s] [%s] %s%s',
40
            date('Y-m-d H:i:s'),
41
            $this->requestInterface->getRemoteAddress(),
42
            $level,
43
            $message,
44
            PHP_EOL
45
        );
46
        if (!empty($context)) {
47
            $data .= sprintf('%s%s', var_export($context, true), PHP_EOL);
48
        }
49
        return file_put_contents($this->logPath, $data, FILE_APPEND);
50
    }
51
52
    public function clear()
53
    {
54
        return file_put_contents($this->logPath, null);
55
    }
56
}
57