Completed
Push — master ( c5110b...a167e6 )
by Valentyn
13:46
created

ImdbReleaseDateService   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 4
dl 0
loc 59
ccs 0
cts 23
cp 0
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A getReleaseDate() 0 13 3
A getCacheKeyForDate() 0 4 1
A getCacheKeyForIsParsedFlag() 0 4 1
A parseReleaseDates() 0 15 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Movies\Service;
6
7
use App\Countries\Entity\Country;
8
use App\Movies\Entity\Movie;
9
use App\Movies\Repository\MovieReleaseDateRepository;
10
use Psr\SimpleCache\CacheInterface;
11
12
class ImdbReleaseDateService
13
{
14
    private $repository;
15
    private $cache;
16
    private $parser;
17
18
    public function __construct(MovieReleaseDateRepository $repository, CacheInterface $cache, ImdbReleaseDateParserService $parser)
19
    {
20
        $this->repository = $repository;
21
        $this->cache = $cache;
22
        $this->parser = $parser;
23
    }
24
25
    /**
26
     * @throws
27
     */
28
    public function getReleaseDate(Movie $movie, Country $country): ?\DateTimeInterface
29
    {
30
        if ($this->cache->get($this->getCacheKeyForIsParsedFlag($movie), false) === false) {
31
            $this->parseReleaseDates($movie);
32
        }
33
34
        $timestamp = $this->cache->get($this->getCacheKeyForDate($movie, $country));
35
        if ($timestamp === null) {
36
            return null;
37
        }
38
39
        return (new \DateTimeImmutable())->setTimestamp($timestamp);
40
    }
41
42
    private function getCacheKeyForDate(Movie $movie, Country $country): string
43
    {
44
        return sprintf('%s_%s', $movie->getId(), $country->getCode());
45
    }
46
47
    private function getCacheKeyForIsParsedFlag(Movie $movie): string
48
    {
49
        return 'is_parsed'.$movie->getId();
50
    }
51
52
    /**
53
     * @throws
54
     */
55
    private function parseReleaseDates(Movie $movie): void
56
    {
57
        $result = $this->parser->getReleaseDates($movie);
58
59
        /**
60
         * @var string
61
         * @var $date  \DateTimeInterface
62
         */
63
        foreach ($result as $countryCode => $date) {
64
            $country = new Country('', $countryCode);
65
            $this->cache->set($this->getCacheKeyForDate($movie, $country), $date->getTimestamp(), 3600);
66
        }
67
68
        $this->cache->set($this->getCacheKeyForIsParsedFlag($movie), true, 3600);
69
    }
70
}
71