Passed
Push — master ( 673228...3ba445 )
by yuuki
02:09
created

FluentHandler   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 119
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 15
lcom 1
cbo 1
dl 0
loc 119
ccs 0
cts 63
cp 0
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 2
A write() 0 12 1
A populateTag() 0 4 1
A processFormat() 0 13 4
A getContext() 0 7 2
A contextHasException() 0 8 3
A getContextExceptionTrace() 0 4 1
A getLogger() 0 4 1
1
<?php
2
declare(strict_types=1);
3
4
/**
5
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
6
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
7
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
8
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
9
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
10
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
11
 * THE SOFTWARE.
12
 *
13
 * This software consists of voluntary contributions made by many individuals
14
 * and is licensed under the MIT license.
15
 *
16
 * Copyright (c) 2015-2017 Yuuki Takezawa
17
 *
18
 */
19
20
namespace Ytake\LaravelFluent;
21
22
use Fluent\Logger\LoggerInterface;
23
use Monolog\Handler\AbstractProcessingHandler;
24
use Monolog\Logger;
25
26
/**
27
 * Class FluentHandler
28
 */
29
class FluentHandler extends AbstractProcessingHandler
30
{
31
    /** @var LoggerInterface */
32
    protected $logger;
33
34
    /** @var string */
35
    protected $tagFormat = '{{channel}}.{{level_name}}';
36
37
    /**
38
     * FluentHandler constructor.
39
     *
40
     * @param LoggerInterface $logger
41
     * @param null|string     $tagFormat
42
     * @param int             $level
43
     * @param bool            $bubble
44
     */
45
    public function __construct(
46
        LoggerInterface $logger,
47
        string $tagFormat = null,
48
        int $level = Logger::DEBUG,
49
        bool $bubble = true
50
    ) {
51
        $this->logger = $logger;
52
        if ($tagFormat !== null) {
53
            $this->tagFormat = $tagFormat;
54
        }
55
        parent::__construct($level, $bubble);
56
    }
57
58
    /**
59
     * @param array $record
60
     */
61
    protected function write(array $record)
62
    {
63
        $tag = $this->populateTag($record);
64
        $this->logger->post(
65
            $tag,
66
            [
67
                'message' => $record['message'],
68
                'context' => $this->getContext($record['context']),
69
                'extra'   => $record['extra'],
70
            ]
71
        );
72
    }
73
74
    /**
75
     * @param array $record
76
     *
77
     * @return string
78
     */
79
    protected function populateTag(array $record): string
80
    {
81
        return $this->processFormat($record, $this->tagFormat);
82
    }
83
84
    /**
85
     * @param array  $record
86
     * @param string $tag
87
     *
88
     * @return string
89
     */
90
    protected function processFormat(array $record, string $tag): string
91
    {
92
        if (preg_match_all('/\{\{(.*?)\}\}/', $tag, $matches)) {
93
            foreach ($matches[1] as $match) {
94
                if (!isset($record[$match])) {
95
                    throw new \LogicException('No such field in the record');
96
                }
97
                $tag = str_replace(sprintf('{{%s}}', $match), $record[$match], $tag);
98
            }
99
        }
100
101
        return $tag;
102
    }
103
104
    /**
105
     * returns the context
106
     * @return array | string
107
     */
108
    protected function getContext($context)
109
    {
110
        if ($this->contextHasException($context)) {
111
            return $this->getContextExceptionTrace($context);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->getContextExceptionTrace($context); (string) is incompatible with the return type documented by Ytake\LaravelFluent\FluentHandler::getContext of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
112
        }
113
        return $context;
114
    }
115
116
    /**
117
     * Identifies the content type of the given $context
118
     * @param  mixed $context
119
     * @return bool
120
     */
121
    protected function contextHasException($context): bool
122
    {
123
        return (
124
                is_array($context)
125
            && array_key_exists('exception', $context)
126
            && $context['exception'] instanceof \Exception
127
        );
128
    }
129
130
    /**
131
     * Returns the entire exception trace as a string
132
     * @param  array $context
133
     * @return string
134
     */
135
    protected function getContextExceptionTrace(array $context): string
136
    {
137
        return $context['exception']->getTraceAsString();
138
    }
139
    
140
    /**
141
     * @return LoggerInterface
142
     */
143
    public function getLogger(): LoggerInterface
144
    {
145
        return $this->logger;
146
    }
147
}
148