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\Log\LoggerInterface; |
11
|
|
|
use Psr\SimpleCache\CacheInterface; |
12
|
|
|
|
13
|
|
|
class ImdbReleaseDateService |
14
|
|
|
{ |
15
|
|
|
private $repository; |
16
|
|
|
private $cache; |
17
|
|
|
private $parser; |
18
|
|
|
private $logger; |
19
|
|
|
|
20
|
|
|
public function __construct(MovieReleaseDateRepository $repository, CacheInterface $cache, ImdbReleaseDateParserService $parser, LoggerInterface $logger) |
21
|
|
|
{ |
22
|
|
|
$this->repository = $repository; |
23
|
|
|
$this->cache = $cache; |
24
|
|
|
$this->parser = $parser; |
25
|
|
|
$this->logger = $logger; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @throws |
30
|
|
|
*/ |
31
|
|
|
public function getReleaseDate(Movie $movie, Country $country): ?\DateTimeInterface |
32
|
|
|
{ |
33
|
|
|
if ($this->cache->get($this->getCacheKeyForIsParsedFlag($movie), false) === false) { |
34
|
|
|
$this->logger->debug("[ImdbReleaseDateService] Cache for key {$this->getCacheKeyForIsParsedFlag($movie)} not found, so lets parse imdb"); |
35
|
|
|
$this->parseReleaseDates($movie); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
$timestamp = $this->cache->get($this->getCacheKeyForDate($movie, $country)); |
39
|
|
|
$this->logger->debug("[ImdbReleaseDateService] Trying to get releaseDate for movie {$movie->getOriginalTitle()} in {$country->getCode()}, result is: {$timestamp}"); |
40
|
|
|
if ($timestamp === null) { |
41
|
|
|
return null; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
return (new \DateTimeImmutable())->setTimestamp($timestamp); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
private function getCacheKeyForDate(Movie $movie, Country $country): string |
48
|
|
|
{ |
49
|
|
|
return sprintf('%s_%s', $movie->getId(), $country->getCode()); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
private function getCacheKeyForIsParsedFlag(Movie $movie): string |
53
|
|
|
{ |
54
|
|
|
return 'is_parsed'.$movie->getId(); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @throws |
59
|
|
|
*/ |
60
|
|
|
private function parseReleaseDates(Movie $movie): void |
61
|
|
|
{ |
62
|
|
|
$result = $this->parser->getReleaseDates($movie); |
63
|
|
|
$this->logger->debug('[ImdbReleaseDateService] parseReleaseDates result: ', $result); |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @var string |
67
|
|
|
* @var $date \DateTimeInterface |
68
|
|
|
*/ |
69
|
|
|
foreach ($result as $countryCode => $date) { |
70
|
|
|
$country = new Country('', $countryCode); |
71
|
|
|
$this->cache->set($this->getCacheKeyForDate($movie, $country), $date->getTimestamp(), 35); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
$this->cache->set($this->getCacheKeyForIsParsedFlag($movie), true, 30); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|