Passed
Branch 3.0.0 (dcfee6)
by Pieter
02:48
created

ExceptionNormalizer   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 13
c 0
b 0
f 0
dl 0
loc 43
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A normalize() 0 15 3
A __construct() 0 3 1
A supportsNormalization() 0 3 1
1
<?php
2
namespace W2w\Lib\Apie\Plugins\Core\Normalizers;
3
4
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
5
use ReflectionClass;
6
use Throwable;
7
use W2w\Lib\Apie\Exceptions\ValidationException;
8
9
/**
10
 * Class that normalizes a throwable class.
11
 */
12
class ExceptionNormalizer implements NormalizerInterface
13
{
14
    private $showStack;
15
16
    /**
17
     * @param bool $showStack If true, outputs a stack trace.
18
     */
19
    public function __construct(bool $showStack)
20
    {
21
        $this->showStack = $showStack;
22
    }
23
24
    /**
25
     * @param Throwable $object
26
     * @param string|null $format
27
     * @param array $context
28
     * @return string[]
29
     */
30
    public function normalize($object, $format = null, array $context = [])
31
    {
32
        $res = [
33
            'type'    => (new ReflectionClass($object))->getShortName(),
34
            'message' => $object->getMessage(),
35
            'code'    => $object->getCode(),
36
        ];
37
        if ($this->showStack) {
38
            $res['trace'] = $object->getTraceAsString();
39
        }
40
        if ($object instanceof ValidationException) {
41
            $res['errors'] = $object->getErrors();
42
        }
43
44
        return $res;
45
    }
46
47
    /**
48
     * @param mixed $data
49
     * @param string|null $format
50
     * @return bool
51
     */
52
    public function supportsNormalization($data, $format = null)
53
    {
54
        return $data instanceof Throwable;
55
    }
56
}
57