LogContextFormatter   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 66
rs 10
c 0
b 0
f 0
wmc 6

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A name() 0 3 1
A format() 0 9 1
A addContextFormatter() 0 4 1
A validate() 0 8 2
1
<?php
2
3
namespace San4io\RequestLogger\Logger;
4
5
use Illuminate\Support\Collection;
6
use San4io\RequestLogger\Contracts\ContextFormatterContract;
7
use Symfony\Component\HttpFoundation\Request;
8
use Symfony\Component\HttpFoundation\Response;
9
10
class LogContextFormatter implements ContextFormatterContract
11
{
12
    /**
13
     * @var array
14
     */
15
    protected $context = [];
16
17
    /**
18
     * @var Collection
19
     */
20
    protected $collection;
21
22
    /**
23
     * LogContextFormatter constructor.
24
     */
25
    public function __construct()
26
    {
27
        $this->collection = new Collection();
28
    }
29
30
    /**
31
     * @param Request $request
32
     * @param Response $response
33
     * @return array
34
     */
35
    public function format(Request $request, Response $response)
36
    {
37
        $this->collection->each(
38
            function (ContextFormatterContract $contextFormatterContract) use ($request, $response) {
39
                $this->context[$contextFormatterContract->name()] = $contextFormatterContract->format($request, $response);
40
            }
41
        );
42
43
        return $this->context;
44
    }
45
46
    /**
47
     * @param ContextFormatterContract $newFormatter
48
     */
49
    public function addContextFormatter(ContextFormatterContract $newFormatter)
50
    {
51
        $this->validate($newFormatter);
52
        $this->collection->push($newFormatter);
53
    }
54
55
    /**
56
     * @param ContextFormatterContract $newFormatter
57
     * @throws \Exception
58
     */
59
    protected function validate(ContextFormatterContract $newFormatter): void
60
    {
61
        $exists = $this->collection->first(function (ContextFormatterContract $formatter) use ($newFormatter) {
62
            return $formatter->name() == $newFormatter->name();
63
        });
64
65
        if ($exists) {
66
            throw new \Exception('Context formatter with name "' . $exists->name() . '" already exits');
67
        }
68
    }
69
70
    /**
71
     * @return string
72
     */
73
    public function name(): string
74
    {
75
        return 'log-context-formatter';
76
    }
77
78
}