ImportGamesCommand::updateGame()   C
last analyzed

Complexity

Conditions 12
Paths 16

Size

Total Lines 42
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 26
c 1
b 0
f 0
nc 16
nop 2
dl 0
loc 42
rs 6.9666

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace VideoGamesRecords\IgdbBundle\Command;
6
7
use Doctrine\ORM\EntityManagerInterface;
8
use Symfony\Component\Console\Attribute\AsCommand;
9
use Symfony\Component\Console\Command\Command;
10
use Symfony\Component\Console\Input\InputInterface;
11
use Symfony\Component\Console\Output\OutputInterface;
12
use Symfony\Component\Console\Style\SymfonyStyle;
13
use VideoGamesRecords\IgdbBundle\Entity\Game;
14
use VideoGamesRecords\IgdbBundle\Entity\Genre;
15
use VideoGamesRecords\IgdbBundle\Entity\Platform;
16
use VideoGamesRecords\IgdbBundle\Client\IgdbClient;
17
18
#[AsCommand(
19
    name: 'igdb:import:games',
20
    description: 'Import all games from IGDB API into database'
21
)]
22
class ImportGamesCommand extends Command
23
{
24
    public function __construct(
25
        private IgdbClient $igdbClient,
26
        private EntityManagerInterface $entityManager
27
    ) {
28
        parent::__construct();
29
    }
30
31
    protected function execute(InputInterface $input, OutputInterface $output): int
32
    {
33
        $io = new SymfonyStyle($input, $output);
34
35
        $io->title('Importing games from IGDB API');
36
37
        try {
38
            $games = $this->igdbClient->getAllGames();
39
            $io->progressStart(count($games));
40
41
            $insertedCount = 0;
42
            $updatedCount = 0;
43
            $skippedCount = 0;
44
45
            foreach ($games as $gameData) {
46
                $existingGame = $this->entityManager->getRepository(Game::class)->find($gameData['id']);
47
48
                if ($existingGame) {
49
                    // Comparer les updated_at pour savoir si une mise à jour est nécessaire
50
                    $needsUpdate = true;
51
                    if (isset($gameData['updated_at'])) {
52
                        $igdbUpdatedAt = new \DateTimeImmutable('@' . $gameData['updated_at']);
53
                        $needsUpdate = $existingGame->getUpdatedAt() < $igdbUpdatedAt;
54
                    }
55
56
                    if ($needsUpdate) {
57
                        $this->updateGame($existingGame, $gameData);
58
                        $updatedCount++;
59
                    } else {
60
                        $skippedCount++;
61
                    }
62
                } else {
63
                    $game = new Game();
64
                    $this->updateGame($game, $gameData);
65
                    $game->setId($gameData['id']);
66
67
                    if (isset($gameData['created_at'])) {
68
                        $game->setCreatedAt(new \DateTimeImmutable('@' . $gameData['created_at']));
69
                    }
70
71
                    $this->entityManager->persist($game);
72
                    $insertedCount++;
73
                }
74
75
                $io->progressAdvance();
76
            }
77
78
            $this->entityManager->flush();
79
            $io->progressFinish();
80
81
            $io->success([
82
                "Games imported successfully!",
83
                "Inserted: $insertedCount games",
84
                "Updated: $updatedCount games",
85
                "Skipped: $skippedCount games (no changes)",
86
                "Total processed: " . ($insertedCount + $updatedCount + $skippedCount) . " games"
87
            ]);
88
89
            return Command::SUCCESS;
90
        } catch (\Exception $e) {
91
            $io->error('Failed to import games: ' . $e->getMessage());
92
            return Command::FAILURE;
93
        }
94
    }
95
96
    private function updateGame(Game $game, array $gameData): void
97
    {
98
        $game->setName($gameData['name']);
99
        $game->setSlug($gameData['slug'] ?? null);
100
        $game->setStoryline($gameData['storyline'] ?? null);
101
        $game->setSummary($gameData['summary'] ?? null);
102
        $game->setUrl($gameData['url'] ?? null);
103
        $game->setChecksum($gameData['checksum'] ?? null);
104
        $game->setFirstReleaseDate($gameData['first_release_date'] ?? null);
105
106
        // Gérer l'association avec version_parent (auto-référence)
107
        if (isset($gameData['version_parent']) && is_numeric($gameData['version_parent'])) {
108
            $versionParent = $this->entityManager->getRepository(Game::class)->find($gameData['version_parent']);
109
            $game->setVersionParent($versionParent);
110
        }
111
112
        // Gérer les associations ManyToMany avec les genres
113
        $game->getGenres()->clear();
114
        if (isset($gameData['genres']) && is_array($gameData['genres'])) {
115
            foreach ($gameData['genres'] as $genreId) {
116
                $genre = $this->entityManager->getRepository(Genre::class)->find($genreId);
117
                if ($genre) {
118
                    $game->addGenre($genre);
119
                }
120
            }
121
        }
122
123
        // Gérer les associations ManyToMany avec les plateformes
124
        $game->getPlatforms()->clear();
125
        if (isset($gameData['platforms']) && is_array($gameData['platforms'])) {
126
            foreach ($gameData['platforms'] as $platformId) {
127
                $platform = $this->entityManager->getRepository(Platform::class)->find($platformId);
128
                if ($platform) {
129
                    $game->addPlatform($platform);
130
                }
131
            }
132
        }
133
134
        if (isset($gameData['updated_at'])) {
135
            $game->setUpdatedAt(new \DateTimeImmutable('@' . $gameData['updated_at']));
136
        } else {
137
            $game->setUpdatedAt(new \DateTimeImmutable());
138
        }
139
    }
140
}
141