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

FileLogger   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 7
eloc 25
c 2
b 1
f 0
dl 0
loc 47
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getLogDirectory() 0 3 1
A clear() 0 3 1
A log() 0 14 2
A __construct() 0 14 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\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