Passed
Pull Request — master (#182)
by Arman
05:01 queued 02:11
created

BaseLogger::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\DiException;
20
use Quantum\Logger\LoggerException;
21
use ReflectionException;
22
use Quantum\Di\Di;
23
24
/**
25
 * Class BaseLogger
26
 * @package Quantum\Logger
27
 */
28
abstract class BaseLogger implements ReportableInterface
29
{
30
    /**
31
     * @var FileSystem
32
     */
33
    protected $fs;
34
35
    /**
36
     * @var string
37
     */
38
    protected $logFile;
39
40
    /**
41
     * @param array $params
42
     * @throws LoggerException
43
     * @throws DiException
44
     * @throws ReflectionException
45
     */
46
    public function __construct(array $params)
47
    {
48
        $this->fs = Di::get(FileSystem::class);
49
        $this->initialize($params);
50
    }
51
52
    /**
53
     * Initialize the adapter
54
     * @param array $params
55
     * @throws LoggerException
56
     */
57
    abstract protected function initialize(array $params): void;
58
59
    /**
60
     * @inheritDoc
61
     */
62
    public function report(string $level, $message, ?array $context = [])
63
    {
64
        $this->fs->append($this->logFile, $this->formatMessage($level, $message, $context));
65
    }
66
67
    /**
68
     * @param string $level
69
     * @param $message
70
     * @param array|null $context
71
     * @return string
72
     */
73
    protected function formatMessage(string $level, $message, ?array $context = []): string
74
    {
75
        return sprintf(
76
            "[%s] %s: %s%s",
77
            date('Y-m-d H:i:s'),
78
            ucfirst($level),
79
            is_array($message) ? json_encode($message, JSON_PRETTY_PRINT) : $message,
80
            isset($context['trace']) ? (PHP_EOL . $context['trace'] . PHP_EOL) : PHP_EOL
81
        );
82
    }
83
84
}