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

ShortCodeHelper::ensureShortCodeUniqueness()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 20
rs 9.9
cc 4
nc 6
nop 2
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