FileLogger::getLogfileName()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace DarkMatter\Components\Logger;
6
7
class FileLogger extends AbstractLogger
8
{
9
    /**
10
     * @var string $logsDir
11
     */
12
    private $logsDir;
13
14
    /**
15
     * Sets path to directory containing log files.
16
     *
17
     * @param string $logsDir
18
     * @throws LoggerException()
19
     */
20
    public function setLogsDir(string $logsDir): void
21
    {
22
        if (!file_exists($logsDir) || !is_writable($logsDir)) {
23
            throw new LoggerException('Logs path does not exist or is not writable.');
24
        }
25
        $this->logsDir = rtrim($logsDir, '/') . '/';
26
    }
27
28
    /**
29
     * Logs given event to a file.
30
     *
31
     * @param string $level
32
     * @param string $message
33
     * @param array $context
34
     */
35
    public function log(string $level, string $message, array $context = []): void
36
    {
37
        if ($this->levelIsValid($level) === false) {
38
            throw new \InvalidArgumentException('Invalid log-level provided.');
39
        }
40
41
        // do not log if level is below min level:
42
        if ($this->isHandling($level) === false) {
43
            return;
44
        }
45
46
        $pathToLogfile = $this->openLogfile();
47
        $lineToLog = sprintf('[ %s ] %s: %s', date('Y-m-d H:i:s'), ucfirst($level), $message) . PHP_EOL;
48
        if (!empty($context)) {
49
            $lineToLog .= '--- Context ---' . PHP_EOL;
50
            $lineToLog .= print_r($context, true) . PHP_EOL;
51
        }
52
        file_put_contents($pathToLogfile, $lineToLog, FILE_APPEND);
53
    }
54
55
    /**
56
     * Creates new logfile if not yet existing.
57
     *
58
     * @return string
59
     */
60
    private function openLogfile(): string
61
    {
62
        $logfileName = $this->getLogfileName();
63
        $pathToLogfile = $this->logsDir . $logfileName;
64
        if (!file_exists($pathToLogfile)) {
65
            $openedMsg = sprintf('[ %s ] Logfile opened', date('Y-m-d H:i:s')) . PHP_EOL;
66
            file_put_contents($pathToLogfile, $openedMsg);
67
        }
68
        return $pathToLogfile;
69
    }
70
71
    /**
72
     * Returns logfile name depending on current date.
73
     *
74
     * @return string
75
     */
76
    private function getLogfileName(): string
77
    {
78
        return date('Y-m-d') . '_endocore.log';
79
    }
80
}
81