Completed
Push — master ( eefa71...7d5e7c )
by Christian
02:51 queued 10s
created

FlattenExceptionHandler   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 105
Duplicated Lines 4.76 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 93.33%

Importance

Changes 0
Metric Value
wmc 18
lcom 1
cbo 7
dl 5
loc 105
ccs 42
cts 45
cp 0.9333
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A getSubscribingMethods() 0 17 1
A serializeToJson() 0 8 2
B serializeToXml() 0 33 7
B convertToArray() 5 30 7

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace FOS\RestBundle\Serializer\Normalizer;
4
5
use FOS\RestBundle\Util\ExceptionValueMap;
6
use JMS\Serializer\Context;
7
use JMS\Serializer\GraphNavigatorInterface;
8
use JMS\Serializer\Handler\SubscribingHandlerInterface;
9
use JMS\Serializer\JsonSerializationVisitor;
10
use JMS\Serializer\XmlSerializationVisitor;
11
use Symfony\Component\ErrorHandler\Exception\FlattenException;
12
use Symfony\Component\HttpFoundation\Response;
13
14
/**
15
 * @author Christian Flothmann <[email protected]>
16
 *
17
 * @internal
18
 */
19
class FlattenExceptionHandler implements SubscribingHandlerInterface
20
{
21
    private $messagesMap;
22
    private $debug;
23
    private $rfc7807;
24
25 4
    public function __construct(ExceptionValueMap $messagesMap, bool $debug, bool $rfc7807)
26
    {
27 4
        $this->messagesMap = $messagesMap;
28 4
        $this->debug = $debug;
29 4
        $this->rfc7807 = $rfc7807;
30 4
    }
31
32 3
    public static function getSubscribingMethods(): array
33
    {
34
        return [
35
            [
36 3
                'direction' => GraphNavigatorInterface::DIRECTION_SERIALIZATION,
37
                'format' => 'json',
38
                'type' => FlattenException::class,
39
                'method' => 'serializeToJson',
40
            ],
41
            [
42
                'direction' => GraphNavigatorInterface::DIRECTION_SERIALIZATION,
43
                'format' => 'xml',
44
                'type' => FlattenException::class,
45
                'method' => 'serializeToXml',
46
            ],
47
        ];
48
    }
49
50 2
    public function serializeToJson(JsonSerializationVisitor $visitor, FlattenException $exception, array $type, Context $context)
51
    {
52 2
        if ($this->rfc7807) {
53 1
            $exception->setHeaders($exception->getHeaders() + ['Content-Type' => 'application/problem+json']);
54
        }
55
56 2
        return $visitor->visitArray($this->convertToArray($exception, $context), $type, $context);
0 ignored issues
show
Unused Code introduced by
The call to JsonSerializationVisitor::visitArray() has too many arguments starting with $context.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
57
    }
58
59 2
    public function serializeToXml(XmlSerializationVisitor $visitor, FlattenException $exception, array $type, Context $context)
0 ignored issues
show
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
60
    {
61 2
        if ($this->rfc7807) {
62 1
            $exception->setHeaders($exception->getHeaders() + ['Content-Type' => 'application/problem+xml']);
63
        }
64
65 2
        $rootName = $this->rfc7807 ? 'response' : 'result';
66
67 2
        $data = $this->convertToArray($exception, $context);
68
69 2
        if (method_exists($visitor, 'setDefaultRootName')) {
70
            $visitor->setDefaultRootName($rootName);
0 ignored issues
show
Bug introduced by
The method setDefaultRootName() does not seem to exist on object<JMS\Serializer\XmlSerializationVisitor>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
71
        }
72
73 2
        $document = $visitor->getDocument(true);
0 ignored issues
show
Unused Code introduced by
The call to XmlSerializationVisitor::getDocument() has too many arguments starting with true.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
74
75 2
        if (!$visitor->getCurrentNode()) {
76 2
            $visitor->createRoot(null, $rootName);
77
        }
78
79 2
        foreach ($data as $key => $value) {
80 2
            $entryNode = $document->createElement($key);
81 2
            $visitor->getCurrentNode()->appendChild($entryNode);
82 2
            $visitor->setCurrentNode($entryNode);
83
84 2
            $node = $context->getNavigator()->accept($value, null, $context);
0 ignored issues
show
Unused Code introduced by
The call to GraphNavigatorInterface::accept() has too many arguments starting with $context.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
85 2
            if (null !== $node) {
86 2
                $visitor->getCurrentNode()->appendChild($node);
87
            }
88
89 2
            $visitor->revertCurrentNode();
90
        }
91 2
    }
92
93 4
    private function convertToArray(FlattenException $exception, Context $context): array
94
    {
95 4
        if ($context->hasAttribute('status_code')) {
96
            $statusCode = $context->getAttribute('status_code');
97
        } else {
98 4
            $statusCode = $exception->getStatusCode();
99
        }
100
101 4
        $showMessage = $this->messagesMap->resolveFromClassName($exception->getClass());
102
103 4 View Code Duplication
        if ($showMessage || $this->debug) {
104 4
            $message = $exception->getMessage();
105
        } else {
106
            $message = Response::$statusTexts[$statusCode] ?? 'error';
107
        }
108
109 4
        if ($this->rfc7807) {
110
            return [
111 2
                'type' => $context->hasAttribute('type') ? $context->getAttribute('type') : 'https://tools.ietf.org/html/rfc2616#section-10',
112 2
                'title' => $context->hasAttribute('title') ? $context->getAttribute('title') : 'An error occurred',
113 2
                'status' => $statusCode,
114 2
                'detail' => $message,
115
            ];
116
        } else {
117
            return [
118 2
                'code' => $statusCode,
119 2
                'message' => $message,
120
            ];
121
        }
122
    }
123
}
124