LogContextFormatter::validate()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
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
}