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
|
|
|
|