Passed
Push — master ( fc83aa...c68055 )
by Radu
01:36
created

FileLogger   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 22
dl 0
loc 40
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A clear() 0 3 1
A log() 0 14 2
A __construct() 0 13 3
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\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
        $this->requestInterface = $requestInterface;
26
    }
27
28
    public function log($level, $message, $context = [])
29
    {
30
        $data = sprintf(
31
            '[%s] [%s] [%s] %s%s',
32
            date('Y-m-d H:i:s'),
33
            $this->requestInterface->getRemoteAddress(),
34
            $level,
35
            $message,
36
            PHP_EOL
37
        );
38
        if (!empty($context)) {
39
            $data .= sprintf('%s%s', var_export($context, true), PHP_EOL);
40
        }
41
        return file_put_contents($this->logPath, $data, FILE_APPEND);
42
    }
43
44
    public function clear()
45
    {
46
        return file_put_contents($this->logPath, null);
47
    }
48
}
49