You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Flumzi/src/Command/ImportReleasesCommand.php

105 lines
3.4 KiB

<?php
namespace App\Command;
use App\Entity\Artist;
use App\Entity\Release;
use App\Repository\ArtistRepository;
use App\Repository\ReleaseRepository;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'import:releases',
description: 'Import releases from a CSV file.',
)]
class ImportReleasesCommand extends Command
{
public function __construct(
protected EntityManagerInterface $entityManager,
protected ArtistRepository $artistRepository,
protected ReleaseRepository $releaseRepository,
protected UserRepository $userRepository,
)
{
parent::__construct();
}
protected function configure(): void
{
$this
->addArgument('username', InputArgument::REQUIRED, 'Owner username')
->addArgument('csv', InputArgument::REQUIRED, 'CSV file')
;
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$csvFilename = $input->getArgument('csv');
$ownerName = $input->getArgument('username');
$owner = $this->userRepository->findOneBy(['username' => $ownerName]);
if (!$owner) {
$io->error("No user with the username $ownerName.");
return Command::FAILURE;
}
$numNewArtists = 0;
$numNewReleases = 0;
$numSkippedReleases = 0;
$csvFile = fopen($csvFilename, 'r');
while (($row = fgetcsv($csvFile)) !== false) {
$numCols = count($row);
if ($numCols < 2) {
$io->error('Skipping row with less than two columns: ' . json_encode($row));
continue;
}
$artistName = $row[0];
$title = $row[1];
$artist = $this->artistRepository->findOneBy(['name' => $artistName]);
if (!$artist) {
$artist = new Artist();
$artist->setName($artistName);
$this->entityManager->persist($artist);
$this->entityManager->flush();
$numNewArtists++;
}
$releaseExists = false;
foreach ($artist->getReleases() as $artistRelease) {
if ($artistRelease->getTitle() === $title) {
$releaseExists = true;
break;
}
}
if (!$releaseExists) {
$release = new Release();
$release->setTitle($title);
$release->setOwner($owner);
$release->addArtist($artist);
$this->entityManager->persist($release);
$this->entityManager->flush();
$numNewReleases++;
} else {
$numSkippedReleases++;
}
}
fclose($csvFile);
$io->success(
'Import successful:'
. " $numNewArtists new artists,"
. " $numNewReleases new releases ($numSkippedReleases skipped)."
);
return Command::SUCCESS;
}
}