Completed
Pull Request — 2.x (#2253)
by Christian
04:19
created

FlattenExceptionHandler::convertToArray()   B

Complexity

Conditions 8
Paths 30

Size

Total Lines 30

Duplication

Lines 10
Ratio 33.33 %

Code Coverage

Tests 14
CRAP Score 8.125

Importance

Changes 0
Metric Value
dl 10
loc 30
ccs 14
cts 16
cp 0.875
rs 8.1954
c 0
b 0
f 0
cc 8
nc 30
nop 2
crap 8.125
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 $statusCodeMap;
22
    private $messagesMap;
23
    private $debug;
24
    private $rfc7807;
25
26 6 View Code Duplication
    public function __construct(ExceptionValueMap $statusCodeMap, ExceptionValueMap $messagesMap, bool $debug, bool $rfc7807)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
27
    {
28 6
        $this->statusCodeMap = $statusCodeMap;
29 6
        $this->messagesMap = $messagesMap;
30 6
        $this->debug = $debug;
31 6
        $this->rfc7807 = $rfc7807;
32 6
    }
33
34 6
    public static function getSubscribingMethods(): array
35
    {
36
        return [
37
            [
38 6
                'direction' => GraphNavigatorInterface::DIRECTION_SERIALIZATION,
39 6
                'format' => 'json',
40
                'type' => FlattenException::class,
41 6
                'method' => 'serializeToJson',
42
            ],
43
            [
44 6
                'direction' => GraphNavigatorInterface::DIRECTION_SERIALIZATION,
45 6
                'format' => 'xml',
46
                'type' => FlattenException::class,
47 6
                'method' => 'serializeToXml',
48
            ],
49
        ];
50
    }
51
52 4
    public function serializeToJson(JsonSerializationVisitor $visitor, FlattenException $exception, array $type, Context $context)
53
    {
54 4
        if ($this->rfc7807) {
55 2
            $exception->setHeaders($exception->getHeaders() + ['Content-Type' => 'application/problem+json']);
56
        }
57
58 4
        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...
59
    }
60
61 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...
62
    {
63 2
        if ($this->rfc7807) {
64 1
            $exception->setHeaders($exception->getHeaders() + ['Content-Type' => 'application/problem+xml']);
65
        }
66
67 2
        $rootName = $this->rfc7807 ? 'response' : 'result';
68
69 2
        $data = $this->convertToArray($exception, $context);
70
71 2
        if (method_exists($visitor, 'setDefaultRootName')) {
72
            $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...
73
        }
74
75 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...
76
77 2
        if (!$visitor->getCurrentNode()) {
78 2
            $visitor->createRoot(null, $rootName);
79
        }
80
81 2
        foreach ($data as $key => $value) {
82 2
            $entryNode = $document->createElement($key);
83 2
            $visitor->getCurrentNode()->appendChild($entryNode);
84 2
            $visitor->setCurrentNode($entryNode);
85
86 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...
87 2
            if (null !== $node) {
88 2
                $visitor->getCurrentNode()->appendChild($node);
89
            }
90
91 2
            $visitor->revertCurrentNode();
92
        }
93 2
    }
94
95 6
    private function convertToArray(FlattenException $exception, Context $context): array
96
    {
97 6 View Code Duplication
        if ($context->hasAttribute('status_code')) {
98
            $statusCode = $context->getAttribute('status_code');
99 6
        } elseif (false === $statusCode = $this->statusCodeMap->resolveFromClassName($exception->getClass())) {
100 4
            $statusCode = $exception->getStatusCode();
101
        }
102
103 6
        $showMessage = $this->messagesMap->resolveFromClassName($exception->getClass());
104
105 6 View Code Duplication
        if ($showMessage || $this->debug) {
106 6
            $message = $exception->getMessage();
107
        } else {
108
            $message = Response::$statusTexts[$statusCode] ?? 'error';
109
        }
110
111 6
        if ($this->rfc7807) {
112
            return [
113 3
                'type' => $context->hasAttribute('type') ? $context->getAttribute('type') : 'https://tools.ietf.org/html/rfc2616#section-10',
114 3
                'title' => $context->hasAttribute('title') ? $context->getAttribute('title') : 'An error occurred',
115 3
                'status' => $statusCode,
116 3
                'detail' => $message,
117
            ];
118
        } else {
119
            return [
120 3
                'code' => $statusCode,
121 3
                'message' => $message,
122
            ];
123
        }
124
    }
125
}
126