Completed
Pull Request — master (#199)
by Alejandro
03:59
created

DeleteShortUrlService::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
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