Completed
Push — master ( 530ce9...1b2ae5 )
by Paweł
23:42 queued 20:31
created

LinkRequestListener   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 115
Duplicated Lines 3.48 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 4
Bugs 1 Features 0
Metric Value
wmc 12
c 4
b 1
f 0
lcom 1
cbo 8
dl 4
loc 115
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
C onKernelRequest() 4 89 11

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
/**
4
 * This file is part of the Superdesk Web Publisher Content Bundle.
5
 *
6
 * Copyright 2015 Sourcefabric z.u. and contributors.
7
 *
8
 * For the full copyright and license information, please see the
9
 * AUTHORS and LICENSE files distributed with this source code.
10
 *
11
 * @copyright 2015 Sourcefabric z.ú.
12
 * @license http://www.superdesk.org/license
13
 */
14
namespace SWP\Bundle\ContentBundle\EventListener;
15
16
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
17
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
18
use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
19
use Symfony\Component\HttpFoundation\Request;
20
use Symfony\Component\HttpKernel\HttpKernelInterface;
21
use Symfony\Component\HttpKernel\KernelEvents;
22
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
23
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
24
25
class LinkRequestListener
26
{
27
    /**
28
     * @var ControllerResolverInterface
29
     */
30
    protected $resolver;
31
32
    /**
33
     * @var UrlMatcherInterface
34
     */
35
    protected $urlMatcher;
36
37
    /**
38
     * @param ControllerResolverInterface $controllerResolver The 'controller_resolver' service
39
     * @param UrlMatcherInterface         $urlMatcher         The 'router' service
40
     */
41
    public function __construct(ControllerResolverInterface $controllerResolver, UrlMatcherInterface $urlMatcher)
42
    {
43
        $this->resolver = $controllerResolver;
44
        $this->urlMatcher = $urlMatcher;
45
    }
46
47
    /**
48
     * @param GetResponseEvent $event
49
     */
50
    public function onKernelRequest(GetResponseEvent $event, $eventName, EventDispatcherInterface $dispatcher)
1 ignored issue
show
Unused Code introduced by
The parameter $eventName 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...
51
    {
52
        if (!$event->getRequest()->headers->has('link')) {
53
            return;
54
        }
55
56
        $links = [];
57
        $header = $event->getRequest()->headers->get('link');
58
59
        /*
60
         * Due to limitations, multiple same-name headers are sent as comma
61
         * separated values.
62
         *
63
         * This breaks those headers into Link headers following the format
64
         * http://tools.ietf.org/html/rfc2068#section-19.6.2.4
65
         */
66
        while (preg_match('/^((?:[^"]|"[^"]*")*?),/', $header, $matches)) {
67
            $header = trim(substr($header, strlen($matches[0])));
68
            $links[] = $matches[1];
69
        }
70
71
        if ($header) {
72
            $links[] = $header;
73
        }
74
75
        $requestMethod = $this->urlMatcher->getContext()->getMethod();
76
77
        // The controller resolver needs a request to resolve the controller.
78
        $stubRequest = new Request();
79
80
        foreach ($links as $idx => $link) {
81
            // Force the GET method to avoid the use of the previous method (LINK/UNLINK)
82
            $this->urlMatcher->getContext()->setMethod('GET');
83
84
            $linkParams = explode(';', trim($link));
85
            $resourceType = null;
86 View Code Duplication
            if (count($linkParams) > 1) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
87
                $resourceType = trim(preg_replace('/<|>/', '', $linkParams[1]));
88
                $resourceType = str_replace('"', '', str_replace('rel=', '', $resourceType));
89
            }
90
            $resource = array_shift($linkParams);
91
            $resource = preg_replace('/<|>/', '', $resource);
92
            $tempRequest = Request::create($resource);
93
94
            try {
95
                $route = $this->urlMatcher->match($tempRequest->getRequestUri());
96
            } catch (\Exception $e) {
97
                // If we don't have a matching route we return the original Link header
98
                continue;
99
            }
100
101
            $stubRequest->attributes->replace($route);
102
            $stubRequest->server = $event->getRequest()->server;
103
            if (false === $controller = $this->resolver->getController($stubRequest)) {
104
                continue;
105
            }
106
107
            $subEvent = new FilterControllerEvent($event->getKernel(), $controller, $stubRequest, HttpKernelInterface::SUB_REQUEST);
108
            $kernelSubEvent = new GetResponseEvent($event->getKernel(), $stubRequest, HttpKernelInterface::SUB_REQUEST);
109
            $dispatcher->dispatch(KernelEvents::REQUEST, $kernelSubEvent);
110
            $dispatcher->dispatch(KernelEvents::CONTROLLER, $subEvent);
111
            $controller = $subEvent->getController();
112
113
            $arguments = $this->resolver->getArguments($stubRequest, $controller);
114
            if (!isset($arguments[0])) {
115
                continue;
116
            }
117
118
            $arguments[0]->attributes->set('_link_request', true);
119
            try {
120
                $result = call_user_func_array($controller, $arguments);
0 ignored issues
show
Security Code Execution introduced by
$controller can contain request data and is used in code execution context(s) leading to a potential security vulnerability.

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
121
                // Our api returns objects for single resources
122
                if (!is_object($result)) {
123
                    continue;
124
                }
125
126
                $links[$idx] = ['object' => $result, 'resourceType' => $resourceType];
127
            } catch (\Exception $e) {
128
                $links[$idx] = ['object' => $e, 'resourceType' => 'exception'];
129
130
                continue;
131
            }
132
        }
133
134
        $event->getRequest()->attributes->set('links', $links);
135
        $this->urlMatcher->getContext()->setMethod($requestMethod);
136
137
        return $links;
138
    }
139
}
140