Completed
Push — master ( 96faaf...c1c325 )
by Alejandro
03:51
created

UrlShortener   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 164
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 98.28%

Importance

Changes 4
Bugs 0 Features 2
Metric Value
dl 0
loc 164
ccs 57
cts 58
cp 0.9828
rs 10
c 4
b 0
f 2
wmc 14
lcom 1
cbo 10

5 Methods

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