Completed
Push — master ( 9ab4b9...065cdd )
by Alejandro
09:44
created

UrlShortener   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 160
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 98.21%

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 160
ccs 55
cts 56
cp 0.9821
rs 10
wmc 14
lcom 1
cbo 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 2
B urlToShortCode() 0 39 4
A checkUrlExists() 0 8 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
16
class UrlShortener implements UrlShortenerInterface
17
{
18
    const DEFAULT_CHARS = '123456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ';
19
20
    /**
21
     * @var ClientInterface
22
     */
23
    private $httpClient;
24
    /**
25
     * @var EntityManagerInterface
26
     */
27
    private $em;
28
    /**
29
     * @var string
30
     */
31
    private $chars;
32
    /**
33
     * @var Cache
34
     */
35
    private $cache;
36
37
    /**
38
     * UrlShortener constructor.
39
     * @param ClientInterface $httpClient
40
     * @param EntityManagerInterface $em
41
     * @param Cache $cache
42
     * @param string $chars
43
     *
44
     * @Inject({"httpClient", "em", Cache::class, "config.url_shortener.shortcode_chars"})
45
     */
46 7
    public function __construct(
47
        ClientInterface $httpClient,
48
        EntityManagerInterface $em,
49
        Cache $cache,
50
        $chars = self::DEFAULT_CHARS
51
    ) {
52 7
        $this->httpClient = $httpClient;
53 7
        $this->em = $em;
54 7
        $this->chars = empty($chars) ? self::DEFAULT_CHARS : $chars;
55 7
        $this->cache = $cache;
56 7
    }
57
58
    /**
59
     * Creates and persists a unique shortcode generated for provided url
60
     *
61
     * @param UriInterface $url
62
     * @return string
63
     * @throws InvalidUrlException
64
     * @throws RuntimeException
65
     */
66 4
    public function urlToShortCode(UriInterface $url)
67
    {
68
        // If the url already exists in the database, just return its short code
69 4
        $shortUrl = $this->em->getRepository(ShortUrl::class)->findOneBy([
70
            'originalUrl' => $url
71 4
        ]);
72 4
        if (isset($shortUrl)) {
73 1
            return $shortUrl->getShortCode();
74
        }
75
76
        // Check that the URL exists
77 3
        $this->checkUrlExists($url);
78
79
        // Transactionally insert the short url, then generate the short code and finally update the short code
80
        try {
81 2
            $this->em->beginTransaction();
82
83
            // First, create the short URL with an empty short code
84 2
            $shortUrl = new ShortUrl();
85 2
            $shortUrl->setOriginalUrl($url);
86 2
            $this->em->persist($shortUrl);
87 2
            $this->em->flush();
88
89
            // Generate the short code and persist it
90 1
            $shortCode = $this->convertAutoincrementIdToShortCode($shortUrl->getId());
91 1
            $shortUrl->setShortCode($shortCode);
92 1
            $this->em->flush();
93
94 1
            $this->em->commit();
95 1
            return $shortCode;
96 1
        } catch (ORMException $e) {
97 1
            if ($this->em->getConnection()->isTransactionActive()) {
98 1
                $this->em->rollback();
99 1
                $this->em->close();
100 1
            }
101
102 1
            throw new RuntimeException('An error occurred while persisting the short URL', -1, $e);
103
        }
104
    }
105
106
    /**
107
     * Tries to perform a GET request to provided url, returning true on success and false on failure
108
     *
109
     * @param UriInterface $url
110
     * @return bool
111
     */
112 3
    protected function checkUrlExists(UriInterface $url)
113
    {
114
        try {
115 3
            $this->httpClient->request('GET', $url);
116 3
        } catch (GuzzleException $e) {
117 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...
118
        }
119 2
    }
120
121
    /**
122
     * Generates the unique shortcode for an autoincrement ID
123
     *
124
     * @param int $id
125
     * @return string
126
     */
127 1
    protected function convertAutoincrementIdToShortCode($id)
128
    {
129 1
        $id = intval($id) + 200000; // Increment the Id so that the generated shortcode is not too short
130 1
        $length = strlen($this->chars);
131 1
        $code = '';
132
133 1
        while ($id > 0) {
134
            // Determine the value of the next higher character in the short code and prepend it
135 1
            $code = $this->chars[intval(fmod($id, $length))] . $code;
136 1
            $id = floor($id / $length);
137 1
        }
138
139 1
        return $this->chars[intval($id)] . $code;
140
    }
141
142
    /**
143
     * Tries to find the mapped URL for provided short code. Returns null if not found
144
     *
145
     * @param string $shortCode
146
     * @return string|null
147
     * @throws InvalidShortCodeException
148
     */
149 3
    public function shortCodeToUrl($shortCode)
150
    {
151 3
        $cacheKey = sprintf('%s_longUrl', $shortCode);
152
        // Check if the short code => URL map is already cached
153 3
        if ($this->cache->contains($cacheKey)) {
154 1
            return $this->cache->fetch($cacheKey);
155
        }
156
157
        // Validate short code format
158 2
        if (! preg_match('|[' . $this->chars . "]+|", $shortCode)) {
159 1
            throw InvalidShortCodeException::fromShortCode($shortCode, $this->chars);
160
        }
161
162
        /** @var ShortUrl $shortUrl */
163 1
        $shortUrl = $this->em->getRepository(ShortUrl::class)->findOneBy([
164 1
            'shortCode' => $shortCode,
165 1
        ]);
166
        // Cache the shortcode
167 1
        if (isset($shortUrl)) {
168 1
            $url = $shortUrl->getOriginalUrl();
169 1
            $this->cache->save($cacheKey, $url);
170 1
            return $url;
171
        }
172
173
        return null;
174
    }
175
}
176