ViewResponseListener::onKernelView()   F
last analyzed

Complexity

Conditions 27
Paths 2046

Size

Total Lines 81

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 56
CRAP Score 27.4019

Importance

Changes 0
Metric Value
dl 0
loc 81
ccs 56
cts 61
cp 0.918
rs 0
c 0
b 0
f 0
cc 27
nc 2046
nop 1
crap 27.4019

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * This file is part of the FOSRestBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace FOS\RestBundle\EventListener;
13
14
use FOS\RestBundle\Controller\Annotations\View as ViewAnnotation;
15
use FOS\RestBundle\FOSRestBundle;
16
use FOS\RestBundle\View\View;
17
use FOS\RestBundle\View\ViewHandlerInterface;
18
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
19
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
20
use Symfony\Component\HttpFoundation\Response;
21
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
22
use Symfony\Component\HttpKernel\KernelEvents;
23
use Symfony\Component\Templating\TemplateReferenceInterface;
24
25
/**
26
 * The ViewResponseListener class handles the View core event as well as the "@extra:Template" annotation.
27
 *
28
 * @author Lukas Kahwe Smith <[email protected]>
29
 *
30
 * @internal
31
 */
32
class ViewResponseListener implements EventSubscriberInterface
33
{
34
    private $viewHandler;
35
    private $forceView;
36
37
    /**
38
     * Constructor.
39
     *
40
     * @param ViewHandlerInterface $viewHandler
41
     * @param bool                 $forceView
42
     */
43 21
    public function __construct(ViewHandlerInterface $viewHandler, $forceView)
44
    {
45 21
        $this->viewHandler = $viewHandler;
46 21
        $this->forceView = $forceView;
47 21
    }
48
49
    /**
50
     * Renders the parameters and template and initializes a new response object with the
51
     * rendered content.
52
     *
53
     * @param GetResponseForControllerResultEvent $event
54
     */
55 21
    public function onKernelView(GetResponseForControllerResultEvent $event)
56
    {
57 21
        $request = $event->getRequest();
58
59 21
        if (!$request->attributes->get(FOSRestBundle::ZONE_ATTRIBUTE, true)) {
60
            return false;
61
        }
62
63 21
        $configuration = $request->attributes->get('_template');
64
65 21
        $view = $event->getControllerResult();
66 21
        if (!$view instanceof View) {
67 11
            if (!$configuration instanceof ViewAnnotation && !$this->forceView) {
68 1
                return;
69
            }
70
71 10
            $view = new View($view);
72 10
        }
73
74 20
        if ($configuration instanceof ViewAnnotation) {
75 16
            if ($configuration->getTemplateVar()) {
76
                $view->setTemplateVar($configuration->getTemplateVar());
77
            }
78 16
            if (null !== $configuration->getStatusCode() && (null === $view->getStatusCode() || Response::HTTP_OK === $view->getStatusCode())) {
79 1
                $view->setStatusCode($configuration->getStatusCode());
80 1
            }
81
82 16
            $context = $view->getContext();
83 16
            if ($configuration->getSerializerGroups()) {
84
                if (null === $context->getGroups()) {
85
                    $context->setGroups($configuration->getSerializerGroups());
86 16
                } else {
87 1
                    $context->setGroups(array_merge($context->getGroups(), $configuration->getSerializerGroups()));
88 1
                }
89 16
            }
90 1
            if ($configuration->getSerializerEnableMaxDepthChecks()) {
91 16
                $context->setMaxDepth(0, false);
0 ignored issues
show
Deprecated Code introduced by Ener-Getick
The method FOS\RestBundle\Context\Context::setMaxDepth() has been deprecated with message: since 2.1, to be removed in 3.0. Use {@link self::enableMaxDepth()} and {@link self::disableMaxDepth()} instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
92 1
            }
93 1
            if (true === $configuration->getSerializerEnableMaxDepthChecks()) {
94
                $context->enableMaxDepth();
95 16
            } elseif (false === $configuration->getSerializerEnableMaxDepthChecks()) {
96 16
                $context->disableMaxDepth();
97 16
            }
98 4
99
            list($controller, $action) = $configuration->getOwner();
100
            $vars = $this->getDefaultVars($configuration, $controller, $action);
101 20
        } else {
102 20
            $vars = null;
103 20
        }
104
105 20
        if (null === $view->getFormat()) {
106 20
            $view->setFormat($request->getRequestFormat());
107 20
        }
108 20
109 11
        if ($this->viewHandler->isFormatTemplating($view->getFormat())
110 7
            && !$view->getRoute()
0 ignored issues
show
Bug Best Practice introduced by Lukas Kahwe Smith
The expression $view->getRoute() of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
111 7
            && !$view->getLocation()
0 ignored issues
show
Bug Best Practice introduced by Lukas Kahwe Smith
The expression $view->getLocation() of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
112 7
        ) {
113 5
            if (null !== $vars && 0 !== count($vars)) {
114 5
                $parameters = (array) $this->viewHandler->prepareTemplateParameters($view);
115 7
                foreach ($vars as $var) {
116 7
                    if (!array_key_exists($var, $parameters)) {
117 7
                        $parameters[$var] = $request->attributes->get($var);
118
                    }
119 11
                }
120 3
                $view->setData($parameters);
121 1
            }
122 1
123
            if ($configuration && ($template = $configuration->getTemplate()) && !$view->getTemplate()) {
124 3
                if ($template instanceof TemplateReferenceInterface) {
125 3
                    $template->set('format', null);
126 11
                }
127
128 20
                $view->setTemplate($template);
129
            }
130 20
        }
131 20
132
        $response = $this->viewHandler->handle($view, $request);
133 21
134
        $event->setResponse($response);
135
    }
136
137 21
    public static function getSubscribedEvents()
138 21
    {
139
        // Must be executed before SensioFrameworkExtraBundle's listener
140
        return array(
141
            KernelEvents::VIEW => array('onKernelView', 30),
142
        );
143
    }
144
145
    /**
146
     * @param Template $template
147
     * @param object   $controller
148
     * @param string   $action
149
     *
150
     * @return array
151 16
     *
152
     * @see \Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener::resolveDefaultParameters()
153 16
     */
154
    private function getDefaultVars(Template $template = null, $controller, $action)
155
    {
156
        if (0 !== count($arguments = $template->getVars())) {
0 ignored issues
show
Bug introduced by Ener-Getick
It seems like $template is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
157 16
            return $arguments;
158 15
        }
159
160 15
        if (!$template instanceof ViewAnnotation || $template->isPopulateDefaultVars()) {
161 15
            $r = new \ReflectionObject($controller);
162 12
163 15
            $arguments = array();
164
            foreach ($r->getMethod($action)->getParameters() as $param) {
165 15
                $arguments[] = $param->getName();
166
            }
167 1
168
            return $arguments;
169
        }
170
    }
171
}
172