Completed
Push — master ( 91fdab...75a7b9 )
by
unknown
13:37
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\HttpFoundation\RequestStack;
10
use Symfony\Component\Routing\RouterInterface;
11
12
/**
13
 * A helper for replacing url's
14
 */
15
class URLHelper
16
{
17
    use URLValidator;
18
19
    /**
20
     * @var EntityManager
21
     */
22
    private $em;
23
24
    /**
25
     * @var RouterInterface
26
     */
27
    private $router;
28
29
    /**
30
     * @var LoggerInterface
31
     */
32
    private $logger;
33
34
    /**
35
     * @var array|null
36
     */
37
    private $nodeTranslationMap = null;
38
39
    /**
40
     * @var array|null
41
     */
42
    private $mediaMap = null;
43
44
    /**
45
     * @var DomainConfigurationInterface
46
     */
47
    private $domainConfiguration;
48
49
    /**
50
     * @param EntityManager $em
51
     * @param RouterInterface $router
52
     * @param LoggerInterface $logger
53
     * @param DomainConfigurationInterface $domainConfiguration
54
     */
55
    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...
56
    {
57
        $this->em = $em;
58
        $this->router = $router;
59
        $this->logger = $logger;
60
        $this->domainConfiguration = $domainConfiguration;
61
    }
62
63
    /**
64
     * Replace a given text, according to the node translation id and the multidomain site id.
65
     *
66
     * @param $text
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
                    $hostConfig = $this->domainConfiguration->getFullHostById($hostId);
85
                    $hostBaseUrl = $this->domainConfiguration->getHostBaseUrl($hostConfig['host']);
86
87
                    $nodeTranslationId = $match[3];
88
89
                    foreach ($map as $nodeTranslation) {
90
                        if ($nodeTranslation['id'] == $nodeTranslationId) {
91
                            $urlParams = ['url' => $nodeTranslation['url']];
92
                            $nodeTranslationFound = true;
93
                            // Only add locale if multilingual site
94
                            if ($this->domainConfiguration->isMultiLanguage($hostConfig['host'])) {
95
                                $urlParams['_locale'] = $nodeTranslation['lang'];
96
                            }
97
98
                            // Only add other site, when having this.
99
                            if ($hostId) {
100
                                $urlParams['otherSite'] = $hostId;
101
                            }
102
103
                            $url = $this->router->generate('_slug', $urlParams);
104
105
                            $text = str_replace($fullTag, $hostId ? $hostBaseUrl . $url : $url, $text);
106
                        }
107
                    }
108
109
                    if (!$nodeTranslationFound) {
110
                        $this->logger->error('No NodeTranslation found in the database when replacing url tag ' . $fullTag);
111
                    }
112
                }
113
            }
114
        }
115
116
        if ($this->isInternalMediaLink($text)) {
117
            preg_match_all("/\[(([a-z_A-Z]+):)?M([0-9]+)\]/", $text, $matches, PREG_SET_ORDER);
118
119
            if (count($matches) > 0) {
120
                $map = $this->getMediaMap();
121
                foreach ($matches as $match) {
122
                    $mediaFound = false;
123
                    $fullTag = $match[0];
124
                    $mediaId = $match[3];
125
126
                    foreach ($map as $mediaItem) {
127
                        if ($mediaItem['id'] == $mediaId) {
128
                            $mediaFound = true;
129
                            $text = str_replace($fullTag, $mediaItem['url'], $text);
130
                        }
131
                    }
132
133
                    if (!$mediaFound) {
134
                        $this->logger->error('No Media found in the database when replacing url tag ' . $fullTag);
135
                    }
136
                }
137
            }
138
        }
139
140
        return $text;
141
    }
142
143
    /**
144
     * Get a map of all node translations. Only called once for caching.
145
     *
146
     * @return array|null
147
     * @throws \Doctrine\DBAL\DBALException
148
     */
149 View Code Duplication
    private function getNodeTranslationMap()
150
    {
151
        if (is_null($this->nodeTranslationMap)) {
152
            $sql = "SELECT id, url, lang FROM kuma_node_translations";
153
            $stmt = $this->em->getConnection()->prepare($sql);
154
            $stmt->execute();
155
            $this->nodeTranslationMap = $stmt->fetchAll();
156
        }
157
158
        return $this->nodeTranslationMap;
159
    }
160
161
    /**
162
     * Get a map of all media items. Only called once for caching.
163
     *
164
     * @return array|null
165
     * @throws \Doctrine\DBAL\DBALException
166
     */
167 View Code Duplication
    private function getMediaMap()
168
    {
169
        if (is_null($this->mediaMap)) {
170
            $sql = "SELECT id, url FROM kuma_media";
171
            $stmt = $this->em->getConnection()->prepare($sql);
172
            $stmt->execute();
173
            $this->mediaMap = $stmt->fetchAll();
174
        }
175
176
        return $this->mediaMap;
177
    }
178
}
179