Completed
Push — master ( 5163a0...712d21 )
by Valentyn
06:59
created

TmdbSyncService::updateMovies()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 1
crap 2
1
<?php
2
declare(strict_types=1);
3
4
namespace App\Movies\Service;
5
6
use App\Movies\Entity\Movie;
7
use App\Movies\Event\MovieSyncProcessor;
8
use App\Movies\Repository\MovieRepository;
9
use Psr\Log\LoggerInterface;
10
use Enqueue\Client\ProducerInterface;
11
12
class TmdbSyncService
13
{
14
    private $repository;
15
    private $producer;
16
17 2
    public function __construct(MovieRepository $repository, ProducerInterface $producer)
18
    {
19 2
        $this->repository = $repository;
20 2
        $this->producer = $producer;
21 2
    }
22
23
    /**
24
     * @param array|Movie[] $movies
25
     */
26 1
    public function syncMovies(array $movies): void
27
    {
28 1
        if (false === $this->isSupport(reset($movies))) {
29
            throw new \InvalidArgumentException('Unsupported array of movies provided');
30
        }
31
32 1
        $moviesToSave = $this->getMoviesToSave($movies);
33 1
        $this->addMovies($moviesToSave);
34 1
    }
35
36 1
    private function addMovies(array $movies): void
37
    {
38 1
        $this->producer->sendEvent(MovieSyncProcessor::ADD_MOVIES_TMDB, serialize($movies));
39 1
    }
40
41
    /**
42
     * This method give you array of movies which is not yet loaded to our database
43
     * @param array $movies
44
     * @return array
45
     */
46
    private function getMoviesToSave(array $movies): array
47
    {
48
        $ids = array_map(function (Movie $movie) { return $movie->getTmdb()->getId(); }, $movies);
49 1
        $alreadySavedIds = $this->getAlreadySavedMoviesIdsByTmdbIds($ids);
50
51 1
        return array_filter($movies, function (Movie $movie) use ($alreadySavedIds) {
52 1
            return in_array($movie->getTmdb()->getId(), $alreadySavedIds) === false;
53 1
        });
54
    }
55
56 1
    private function getAlreadySavedMoviesIdsByTmdbIds(array $tmdb_ids)
57
    {
58 1
         return $this->repository->getExistedTmdbIds($tmdb_ids);
59
    }
60
61 1
    private function isSupport($movie)
62
    {
63 1
        return $movie instanceof Movie;
64
    }
65
}