Passed
Pull Request — master (#182)
by Arman
06:15 queued 03:14
created

DailyAdapter::report()   A

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
nc 1
nop 3
dl 0
loc 3
rs 10
c 1
b 0
f 0
1
<?php
2
3
/**
4
 * Quantum PHP Framework
5
 *
6
 * An open source software development framework for PHP
7
 *
8
 * @package Quantum
9
 * @author Arman Ag. <[email protected]>
10
 * @copyright Copyright (c) 2018 Softberg LLC (https://softberg.org)
11
 * @link http://quantum.softberg.org/
12
 * @since 2.9.5
13
 */
14
15
namespace Quantum\Logger\Adapters;
16
17
use Quantum\Libraries\Storage\FileSystem;
18
use Quantum\Logger\ReportableInterface;
19
use Quantum\Exceptions\LangException;
20
use Quantum\Exceptions\DiException;
21
use Quantum\Logger\LoggerException;
22
use ReflectionException;
23
use Quantum\Di\Di;
24
25
/**
26
 * Class DailyAdapter
27
 * @package Quantum\Logger
28
 */
29
class DailyAdapter implements ReportableInterface
30
{
31
32
    /**
33
     * @var FileSystem
34
     */
35
    private $fs;
36
37
    /**
38
     * @var string
39
     */
40
    private $logFile;
41
42
    /**
43
     * DailyAdapter constructor.
44
     * @param array $params
45
     * @throws DiException
46
     * @throws LoggerException
47
     * @throws ReflectionException
48
     * @throws LangException
49
     */
50
    public function __construct(array $params)
51
    {
52
        $this->fs = Di::get(FileSystem::class);
53
54
        if(!$this->fs->isDirectory( $params['path'])) {
55
            throw LoggerException::logPathIsNotDirectory($params['path']);   
56
        }
57
        
58
        $this->logFile = $params['path'] . DS . date('Y-m-d') . '.log';
59
    }
60
61
    /**
62
     * @inheritDoc
63
     */
64
    public function report(string $level, $message, ?array $context = [])
65
    {
66
        $this->fs->append($this->logFile, $this->formatMessage($level, $message, $context));
67
    }
68
69
    /**
70
     * @param string $level
71
     * @param $message
72
     * @param array|null $context
73
     * @return string
74
     */
75
    protected function formatMessage(string $level, $message, ?array $context = []): string
76
    {
77
        return sprintf(
78
            "[%s] %s: %s%s",
79
            date('Y-m-d H:i:s'),
80
            ucfirst($level),
81
            is_array($message) ? json_encode($message, JSON_PRETTY_PRINT) : $message,
82
            isset($context['trace']) ? (PHP_EOL . $context['trace'] . PHP_EOL) : PHP_EOL
83
        );
84
    }
85
86
}