Completed
Push — develop ( 0686ac...7ecc3a )
by Alejandro
18s queued 11s
created

ShortCodeHelper   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 14
c 1
b 0
f 0
dl 0
loc 29
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A ensureShortCodeUniqueness() 0 20 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Shlinkio\Shlink\Core\Service\ShortUrl;
6
7
use Doctrine\ORM\EntityManagerInterface;
8
use Shlinkio\Shlink\Core\Entity\ShortUrl;
9
use Shlinkio\Shlink\Core\Repository\ShortUrlRepository;
10
11
class ShortCodeHelper implements ShortCodeHelperInterface
12
{
13
    private EntityManagerInterface $em;
14
15
    public function __construct(EntityManagerInterface $em)
16
    {
17
        $this->em = $em;
18
    }
19
20
    public function ensureShortCodeUniqueness(ShortUrl $shortUrlToBeCreated, bool $hasCustomSlug): bool
21
    {
22
        $shortCode = $shortUrlToBeCreated->getShortCode();
23
        $domain = $shortUrlToBeCreated->getDomain();
24
        $domainAuthority = $domain !== null ? $domain->getAuthority() : null;
25
26
        /** @var ShortUrlRepository $repo */
27
        $repo = $this->em->getRepository(ShortUrl::class);
28
        $otherShortUrlsExist = $repo->shortCodeIsInUse($shortCode, $domainAuthority);
29
30
        if (! $otherShortUrlsExist) {
31
            return true;
32
        }
33
34
        if ($hasCustomSlug) {
35
            return false;
36
        }
37
38
        $shortUrlToBeCreated->regenerateShortCode();
39
        return $this->ensureShortCodeUniqueness($shortUrlToBeCreated, $hasCustomSlug);
40
    }
41
}
42