Completed
Push — master ( 06c1ce...67d37c )
by Jeroen
06:20
created

src/Kunstmaan/NodeBundle/Helper/URLHelper.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
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) {
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) {
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) {
124
                    $mediaFound = false;
125
                    $fullTag = $match[0];
126
                    $mediaId = $match[3];
127
128
                    foreach ($map as $mediaItem) {
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()
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()
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