Passed
Push — master ( d2e487...b38026 )
by Tobias
05:31
created

EditInPlaceResponseListener::onKernelResponse()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 51
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 30
c 2
b 0
f 0
nc 6
nop 1
dl 0
loc 51
ccs 0
cts 38
cp 0
crap 30
rs 9.1288

How to fix   Long Method   

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 PHP Translation package.
5
 *
6
 * (c) PHP Translation team <[email protected]>
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 Translation\Bundle\EventListener;
13
14
use Symfony\Component\Asset\Packages;
15
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\HttpKe...ent\FilterResponseEvent was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
16
use Symfony\Component\HttpKernel\Event\ResponseEvent;
17
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
18
use Translation\Bundle\EditInPlace\ActivatorInterface;
19
20
/**
21
 * Adds Javascript/CSS files to the Response if the Activator returns true.
22
 *
23
 * @author Damien Alexandre <[email protected]>
24
 */
25
final class EditInPlaceResponseListener
26
{
27
    const HTML = <<<'HTML'
28
<!-- TranslationBundle -->
29
<link rel="stylesheet" type="text/css" href="%s">
30
31
<script type="text/javascript" src="%s"></script>
32
<script type="text/javascript" src="%s"></script>
33
34
<script type="text/javascript">
35
window.onload = function() {
36
    TranslationBundleEditInPlace("%s");
37
}
38
</script>
39
<!-- /TranslationBundle -->
40
HTML;
41
42
    /**
43
     * @var ActivatorInterface
44
     */
45
    private $activator;
46
47
    /**
48
     * @var UrlGeneratorInterface
49
     */
50
    private $router;
51
52
    /**
53
     * @var Packages
54
     */
55
    private $packages;
56
57
    /**
58
     * @var string
59
     */
60
    private $configName;
61
62
    /**
63
     * Determines whether the message for untranslatable content like placeholders will be rendered.
64
     *
65
     * @var bool
66
     */
67
    private $showUntranslatable;
68
69
    public function __construct(ActivatorInterface $activator, UrlGeneratorInterface $router, Packages $packages, string $configName = 'default', bool $showUntranslatable = true)
70
    {
71
        $this->activator = $activator;
72
        $this->router = $router;
73
        $this->packages = $packages;
74
        $this->configName = $configName;
75
        $this->showUntranslatable = $showUntranslatable;
76
    }
77
78
    public function onKernelResponse(ResponseEvent $event): void
79
    {
80
        $request = $event->getRequest();
81
82
        if (!$this->activator->checkRequest($request)) {
83
            return;
84
        }
85
86
        $content = $event->getResponse()->getContent();
87
88
        if (false === $content) {
0 ignored issues
show
introduced by
The condition false === $content is always false.
Loading history...
89
            return;
90
        }
91
92
        // Clean the content for malformed tags in attributes or encoded tags
93
        $replacement = "\"$1🚫 Can't be translated here. 🚫\"";
94
        $pattern = "@\\s*[\"']\\s*(.[a-zA-Z]+:|)(<x-trans.+data-value=\"([^&\"]+)\".+?(?=<\\/x-trans)<\\/x-trans>)\\s*[\"']@mi";
95
        if (!$this->showUntranslatable) {
96
            $replacement = '"$3"';
97
        }
98
        $content = \preg_replace($pattern, $replacement, $content);
99
100
        // Remove escaped content (e.g. Javascript)
101
        $pattern = '@&lt;x-trans.+data-key=&quot;([^&]+)&quot;.+data-value=&quot;([^&]+)&quot;.+&lt;\\/x-trans&gt;@mi';
102
        $replacement = '🚫 $1 🚫';
103
        if (!$this->showUntranslatable) {
104
            $replacement = '$2';
105
        }
106
        $content = \preg_replace($pattern, $replacement, $content);
107
108
        $html = \sprintf(
109
            self::HTML,
110
            $this->packages->getUrl('bundles/translation/css/content-tools.min.css'),
111
            $this->packages->getUrl('bundles/translation/js/content-tools.min.js'),
112
            $this->packages->getUrl('bundles/translation/js/editInPlace.js'),
113
114
            $this->router->generate('translation_edit_in_place_update', [
115
                'configName' => $this->configName,
116
                'locale' => $event->getRequest()->getLocale(),
117
            ])
118
        );
119
        $content = \str_replace('</body>', $html."\n".'</body>', $content);
120
121
        $response = $event->getResponse();
122
123
        // Remove the cache because we do not want the modified page to be cached
124
        $response->headers->set('cache-control', 'no-cache, no-store, must-revalidate');
125
        $response->headers->set('pragma', 'no-cache');
126
        $response->headers->set('expires', '0');
127
128
        $event->getResponse()->setContent($content);
129
    }
130
}
131
132
// FilterResponseEvent have been renamed into ResponseEvent in sf 4.3
133
// @see https://github.com/symfony/symfony/blob/master/UPGRADE-4.3.md#httpkernel
134
// To be removed once sf ^4.3 become the minimum supported version.
135
if (!\class_exists(ResponseEvent::class) && \class_exists(FilterResponseEvent::class)) {
136
    \class_alias(FilterResponseEvent::class, ResponseEvent::class);
137
}
138