Completed
Push — master ( 5b9784...ff8441 )
by Alejandro
12s
created

DeleteShortUrlService   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 46
rs 10
c 0
b 0
f 0
ccs 17
cts 17
cp 1
wmc 6
lcom 1
cbo 3

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A isThresholdReached() 0 8 2
A deleteByShortCode() 0 13 3
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Core\Service\ShortUrl;
5
6
use Doctrine\ORM\EntityManagerInterface;
7
use Shlinkio\Shlink\Core\Entity\ShortUrl;
8
use Shlinkio\Shlink\Core\Exception;
9
use Shlinkio\Shlink\Core\Options\DeleteShortUrlsOptions;
10
11
class DeleteShortUrlService implements DeleteShortUrlServiceInterface
12
{
13
    use FindShortCodeTrait;
14
15
    /**
16
     * @var EntityManagerInterface
17
     */
18
    private $em;
19
    /**
20
     * @var DeleteShortUrlsOptions
21
     */
22
    private $deleteShortUrlsOptions;
23
24 4
    public function __construct(EntityManagerInterface $em, DeleteShortUrlsOptions $deleteShortUrlsOptions)
25
    {
26 4
        $this->em = $em;
27 4
        $this->deleteShortUrlsOptions = $deleteShortUrlsOptions;
28 4
    }
29
30
    /**
31
     * @throws Exception\InvalidShortCodeException
32
     * @throws Exception\DeleteShortUrlException
33
     */
34 4
    public function deleteByShortCode(string $shortCode, bool $ignoreThreshold = false): void
35
    {
36 4
        $shortUrl = $this->findByShortCode($this->em, $shortCode);
37 4
        if (! $ignoreThreshold && $this->isThresholdReached($shortUrl)) {
38 1
            throw Exception\DeleteShortUrlException::fromVisitsThreshold(
39 1
                $this->deleteShortUrlsOptions->getVisitsThreshold(),
40 1
                $shortUrl->getShortCode()
41
            );
42
        }
43
44 3
        $this->em->remove($shortUrl);
45 3
        $this->em->flush();
46 3
    }
47
48 3
    private function isThresholdReached(ShortUrl $shortUrl): bool
49
    {
50 3
        if (! $this->deleteShortUrlsOptions->doCheckVisitsThreshold()) {
51 1
            return false;
52
        }
53
54 2
        return $shortUrl->getVisitsCount() >= $this->deleteShortUrlsOptions->getVisitsThreshold();
55
    }
56
}
57