Passed
Push — master ( 0fdc9a...dde65f )
by Radu
01:37
created

FileLogger::getLogDirectory()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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