Completed
Pull Request — master (#105)
by Mikołaj
04:26 queued 01:11
created

UrlShortener   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 182
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 96.43%

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 182
ccs 54
cts 56
cp 0.9643
rs 10
wmc 15
lcom 1
cbo 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
B urlToShortCode() 0 43 5
A __construct() 0 13 2
A checkUrlExists() 0 10 2
A convertAutoincrementIdToShortCode() 0 14 2
B shortCodeToUrl() 0 26 4
1
<?php
2
namespace Shlinkio\Shlink\Core\Service;
3
4
use Acelaya\ZsmAnnotatedServices\Annotation\Inject;
5
use Doctrine\Common\Cache\Cache;
6
use Doctrine\ORM\EntityManagerInterface;
7
use Doctrine\ORM\ORMException;
8
use GuzzleHttp\ClientInterface;
9
use GuzzleHttp\Exception\GuzzleException;
10
use Psr\Http\Message\UriInterface;
11
use Shlinkio\Shlink\Common\Exception\RuntimeException;
12
use Shlinkio\Shlink\Core\Entity\ShortUrl;
13
use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException;
14
use Shlinkio\Shlink\Core\Exception\InvalidUrlException;
15
use Shlinkio\Shlink\Core\Util\TagManagerTrait;
16
17
class UrlShortener implements UrlShortenerInterface
18
{
19
    use TagManagerTrait;
20
21
    const DEFAULT_CHARS = '123456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ';
22
23
    /**
24
     * @var ClientInterface
25
     */
26
    private $httpClient;
27
    /**
28
     * @var EntityManagerInterface
29
     */
30
    private $em;
31
    /**
32
     * @var string
33
     */
34
    private $chars;
35
    /**
36
     * @var Cache
37
     */
38
    private $cache;
39
    /**
40
     * @var bool
41
     */
42
    private $isUrlExistsValidation;
43
44
    /**
45
     * UrlShortener constructor.
46
     * @param ClientInterface $httpClient
47
     * @param EntityManagerInterface $em
48
     * @param Cache $cache
49
     * @param bool $isUrlExistsValidation
50
     * @param string $chars
51
     *
52
     * @Inject({
53
     *     "httpClient",
54
     *      "em",
55
     *      Cache::class,
56
     *      "config.url_shortener.validate_url",
57
     *      "config.url_shortener.shortcode_chars"
58
     * })
59
     */
60 7
    public function __construct(
61
        ClientInterface $httpClient,
62
        EntityManagerInterface $em,
63
        Cache $cache,
64
        $isUrlExistsValidation,
65
        $chars = self::DEFAULT_CHARS
66
    ) {
67 7
        $this->httpClient = $httpClient;
68 7
        $this->em = $em;
69 7
        $this->chars = empty($chars) ? self::DEFAULT_CHARS : $chars;
70 7
        $this->cache = $cache;
71 7
        $this->isUrlExistsValidation = $isUrlExistsValidation;
72 7
    }
73
74
    /**
75
     * Creates and persists a unique shortcode generated for provided url
76
     *
77
     * @param UriInterface $url
78
     * @param string[] $tags
79
     * @return string
80
     * @throws InvalidUrlException
81
     * @throws RuntimeException
82
     */
83 4
    public function urlToShortCode(UriInterface $url, array $tags = [])
84
    {
85
        // If the url already exists in the database, just return its short code
86 4
        $shortUrl = $this->em->getRepository(ShortUrl::class)->findOneBy([
87 4
            'originalUrl' => $url,
88
        ]);
89 4
        if (isset($shortUrl)) {
90 1
            return $shortUrl->getShortCode();
91
        }
92
93
        // Check if the validation of url is enabled in the config
94 3
        if (true === $this->isUrlExistsValidation) {
95
            // Check that the URL exists
96 1
            $this->checkUrlExists($url);
97
        }
98
99
        // Transactionally insert the short url, then generate the short code and finally update the short code
100
        try {
101 2
            $this->em->beginTransaction();
102
103
            // First, create the short URL with an empty short code
104 2
            $shortUrl = new ShortUrl();
105 2
            $shortUrl->setOriginalUrl($url);
106 2
            $this->em->persist($shortUrl);
107 2
            $this->em->flush();
108
109
            // Generate the short code and persist it
110 1
            $shortCode = $this->convertAutoincrementIdToShortCode($shortUrl->getId());
111 1
            $shortUrl->setShortCode($shortCode)
112 1
                     ->setTags($this->tagNamesToEntities($this->em, $tags));
113 1
            $this->em->flush();
114
115 1
            $this->em->commit();
116 1
            return $shortCode;
117 1
        } catch (ORMException $e) {
118 1
            if ($this->em->getConnection()->isTransactionActive()) {
119 1
                $this->em->rollback();
120 1
                $this->em->close();
121
            }
122
123 1
            throw new RuntimeException('An error occurred while persisting the short URL', -1, $e);
124
        }
125
    }
126
127
    /**
128
     * Tries to perform a GET request to provided url, returning true on success and false on failure
129
     *
130
     * @param UriInterface $url
131
     * @return bool
132
     */
133 1
    protected function checkUrlExists(UriInterface $url)
134
    {
135
        try {
136 1
            $this->httpClient->request('GET', $url, ['allow_redirects' => [
137
                'max' => 15,
138
            ]]);
139 1
        } catch (GuzzleException $e) {
140 1
            throw InvalidUrlException::fromUrl($url, $e);
0 ignored issues
show
Documentation introduced by
$e is of type object<GuzzleHttp\Exception\GuzzleException>, but the function expects a null|object<Exception>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
141
        }
142
    }
143
144
    /**
145
     * Generates the unique shortcode for an autoincrement ID
146
     *
147
     * @param int $id
148
     * @return string
149
     */
150 1
    protected function convertAutoincrementIdToShortCode($id)
151
    {
152 1
        $id = intval($id) + 200000; // Increment the Id so that the generated shortcode is not too short
153 1
        $length = strlen($this->chars);
154 1
        $code = '';
155
156 1
        while ($id > 0) {
157
            // Determine the value of the next higher character in the short code and prepend it
158 1
            $code = $this->chars[intval(fmod($id, $length))] . $code;
159 1
            $id = floor($id / $length);
160
        }
161
162 1
        return $this->chars[intval($id)] . $code;
163
    }
164
165
    /**
166
     * Tries to find the mapped URL for provided short code. Returns null if not found
167
     *
168
     * @param string $shortCode
169
     * @return string|null
170
     * @throws InvalidShortCodeException
171
     */
172 3
    public function shortCodeToUrl($shortCode)
173
    {
174 3
        $cacheKey = sprintf('%s_longUrl', $shortCode);
175
        // Check if the short code => URL map is already cached
176 3
        if ($this->cache->contains($cacheKey)) {
177 1
            return $this->cache->fetch($cacheKey);
178
        }
179
180
        // Validate short code format
181 2
        if (! preg_match('|[' . $this->chars . "]+|", $shortCode)) {
182 1
            throw InvalidShortCodeException::fromCharset($shortCode, $this->chars);
183
        }
184
185
        /** @var ShortUrl $shortUrl */
186 1
        $shortUrl = $this->em->getRepository(ShortUrl::class)->findOneBy([
187 1
            'shortCode' => $shortCode,
188
        ]);
189
        // Cache the shortcode
190 1
        if (isset($shortUrl)) {
191 1
            $url = $shortUrl->getOriginalUrl();
192 1
            $this->cache->save($cacheKey, $url);
193 1
            return $url;
194
        }
195
196
        return null;
197
    }
198
}
199