Completed
Push — master ( ef7008...0b6b98 )
by Jeroen
14:09 queued 06:29
created

URLHelper::replaceUrl()   D

Complexity

Conditions 20
Paths 18

Size

Total Lines 75

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 420

Importance

Changes 0
Metric Value
dl 0
loc 75
ccs 0
cts 58
cp 0
rs 4.1666
c 0
b 0
f 0
cc 20
nc 18
nop 1
crap 420

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
namespace Kunstmaan\NodeBundle\Helper;
4
5
use Doctrine\ORM\EntityManager;
6
use Kunstmaan\AdminBundle\Helper\DomainConfigurationInterface;
7
use Kunstmaan\NodeBundle\Validation\URLValidator;
8
use Psr\Log\LoggerInterface;
9
use Symfony\Component\Routing\RouterInterface;
10
11
/**
12
 * A helper for replacing url's
13
 */
14
class URLHelper
15
{
16
    use URLValidator;
17
18
    /**
19
     * @var EntityManager
20
     */
21
    private $em;
22
23
    /**
24
     * @var RouterInterface
25
     */
26
    private $router;
27
28
    /**
29
     * @var LoggerInterface
30
     */
31
    private $logger;
32
33
    /**
34
     * @var array|null
35
     */
36
    private $nodeTranslationMap;
37
38
    /**
39
     * @var array|null
40
     */
41
    private $mediaMap;
42
43
    /**
44
     * @var DomainConfigurationInterface
45
     */
46
    private $domainConfiguration;
47
48
    /**
49
     * @param EntityManager                $em
50
     * @param RouterInterface              $router
51
     * @param LoggerInterface              $logger
52
     * @param DomainConfigurationInterface $domainConfiguration
53
     */
54
    public function __construct(EntityManager $em, RouterInterface $router, LoggerInterface $logger, DomainConfigurationInterface $domainConfiguration)
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $em. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.

The EntityManager might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:

function someFunction(ManagerRegistry $registry) {
    $em = $registry->getManager();
    $em->getConnection()->beginTransaction();
    try {
        // Do something.
        $em->getConnection()->commit();
    } catch (\Exception $ex) {
        $em->getConnection()->rollback();
        $em->close();

        throw $ex;
    }
}

If that code throws an exception and the EntityManager is closed. Any other code which depends on the same instance of the EntityManager during this request will fail.

On the other hand, if you instead inject the ManagerRegistry, the getManager() method guarantees that you will always get a usable manager instance.

Loading history...
55
    {
56
        $this->em = $em;
57
        $this->router = $router;
58
        $this->logger = $logger;
59
        $this->domainConfiguration = $domainConfiguration;
60
    }
61
62
    /**
63
     * Replace a given text, according to the node translation id and the multidomain site id.
64
     *
65
     * @param $text
66
     *
67
     * @return mixed
68
     */
69
    public function replaceUrl($text)
70
    {
71
        if ($this->isEmailAddress($text)) {
72
            $text = sprintf('%s:%s', 'mailto', $text);
73
        }
74
75
        if ($this->isInternalLink($text)) {
76
            preg_match_all("/\[(([a-z_A-Z\.]+):)?NT([0-9]+)\]/", $text, $matches, PREG_SET_ORDER);
77
78
            if (\count($matches) > 0) {
79
                $map = $this->getNodeTranslationMap();
80
                foreach ($matches as $match) {
0 ignored issues
show
Bug introduced by
The expression $matches of type null|array<integer,array<integer,string>> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
81
                    $nodeTranslationFound = false;
82
                    $fullTag = $match[0];
83
                    $hostId = $match[2];
84
85
                    $hostConfig = !empty($hostId) ? $this->domainConfiguration->getFullHostById((int) $hostId) : null;
86
                    $host = null !== $hostConfig && array_key_exists('host', $hostConfig) ? $hostConfig['host'] : null;
87
                    $hostBaseUrl = $this->domainConfiguration->getHostBaseUrl($host);
88
89
                    $nodeTranslationId = $match[3];
90
91
                    foreach ($map as $nodeTranslation) {
0 ignored issues
show
Bug introduced by
The expression $map of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
92
                        if ($nodeTranslation['id'] == $nodeTranslationId) {
93
                            $urlParams = ['url' => $nodeTranslation['url']];
94
                            $nodeTranslationFound = true;
95
                            // Only add locale if multilingual site
96
                            if ($this->domainConfiguration->isMultiLanguage($host)) {
97
                                $urlParams['_locale'] = $nodeTranslation['lang'];
98
                            }
99
100
                            // Only add other site, when having this.
101
                            if ($hostId) {
102
                                $urlParams['otherSite'] = $hostId;
103
                            }
104
105
                            $url = $this->router->generate('_slug', $urlParams);
106
107
                            $text = str_replace($fullTag, $hostId ? $hostBaseUrl . $url : $url, $text);
108
                        }
109
                    }
110
111
                    if (!$nodeTranslationFound) {
112
                        $this->logger->error('No NodeTranslation found in the database when replacing url tag ' . $fullTag);
113
                    }
114
                }
115
            }
116
        }
117
118
        if ($this->isInternalMediaLink($text)) {
119
            preg_match_all("/\[(([a-z_A-Z]+):)?M([0-9]+)\]/", $text, $matches, PREG_SET_ORDER);
120
121
            if (\count($matches) > 0) {
122
                $map = $this->getMediaMap();
123
                foreach ($matches as $match) {
0 ignored issues
show
Bug introduced by
The expression $matches of type null|array<integer,array<integer,string>> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
124
                    $mediaFound = false;
125
                    $fullTag = $match[0];
126
                    $mediaId = $match[3];
127
128
                    foreach ($map as $mediaItem) {
0 ignored issues
show
Bug introduced by
The expression $map of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
129
                        if ($mediaItem['id'] == $mediaId) {
130
                            $mediaFound = true;
131
                            $text = str_replace($fullTag, $mediaItem['url'], $text);
132
                        }
133
                    }
134
135
                    if (!$mediaFound) {
136
                        $this->logger->error('No Media found in the database when replacing url tag ' . $fullTag);
137
                    }
138
                }
139
            }
140
        }
141
142
        return $text;
143
    }
144
145
    /**
146
     * Get a map of all node translations. Only called once for caching.
147
     *
148
     * @return array|null
149
     *
150
     * @throws \Doctrine\DBAL\DBALException
151
     */
152 View Code Duplication
    private function getNodeTranslationMap()
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...
153
    {
154
        if (\is_null($this->nodeTranslationMap)) {
155
            $sql = 'SELECT id, url, lang FROM kuma_node_translations';
156
            $stmt = $this->em->getConnection()->prepare($sql);
157
            $stmt->execute();
158
            $this->nodeTranslationMap = $stmt->fetchAll();
159
        }
160
161
        return $this->nodeTranslationMap;
162
    }
163
164
    /**
165
     * Get a map of all media items. Only called once for caching.
166
     *
167
     * @return array|null
168
     *
169
     * @throws \Doctrine\DBAL\DBALException
170
     */
171 View Code Duplication
    private function getMediaMap()
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...
172
    {
173
        if (\is_null($this->mediaMap)) {
174
            $sql = 'SELECT id, url FROM kuma_media';
175
            $stmt = $this->em->getConnection()->prepare($sql);
176
            $stmt->execute();
177
            $this->mediaMap = $stmt->fetchAll();
178
        }
179
180
        return $this->mediaMap;
181
    }
182
}
183