Skip to content

Instantly share code, notes, and snippets.

@iamlucianojr
Created August 22, 2022 15:54
Show Gist options
  • Save iamlucianojr/34bae8142f9b8542041311d49e429445 to your computer and use it in GitHub Desktop.
Save iamlucianojr/34bae8142f9b8542041311d49e429445 to your computer and use it in GitHub Desktop.
CSV
```composer req league/csv```
<?php
declare(strict_types=1);
namespace Miscellaneous\Voucher\UI\Command;
use League\Csv\Reader;
use Miscellaneous\Voucher\Exception\CouldNotLoadFileException;
use Miscellaneous\Voucher\Repository\VoucherRepositoryInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Throwable;
final class InvalidateVoucherInBulkCommand extends Command
{
private const END_DATE_TIME = '2022-08-01 00:00:00';
private const VOUCHER_SPECIFICATION = [
'end' => self::END_DATE_TIME
];
private const CODE = "CODES";
public function __construct(
readonly VoucherRepositoryInterface $repository
) {
parent::__construct('voucher:bulk-create');
}
protected function configure(): void
{
$this->setName('voucher:bulk-invalidate')
->setDescription('Invalidate vouchers using a csv file as source')
->setHelp('This command allows you to invalidate vouchers')
->addArgument('source', InputArgument::REQUIRED, 'Source data to create vouchers')
->addOption('end', 'e', InputOption::VALUE_OPTIONAL, 'End date', self::END_DATE_TIME);
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$output->writeln([
'Voucher bulk Invalidator',
'============',
'',
]);
$pathToSourceFile = (string) $input->getArgument('source');
try {
$csv = $this->loadTheCSVDocumentFromAFilePath($pathToSourceFile);
$this->invalidateVouchersInBulk($csv);
$output->writeln('Vouchers invalidated after ' . self::END_DATE_TIME . ' - ' . $pathToSourceFile);
return self::SUCCESS;
} catch (CouldNotLoadFileException $exception) {
$output->writeln($exception->getMessage());
return self::FAILURE;
}
}
/**
* @throws CouldNotLoadFileException
*/
private function loadTheCSVDocumentFromAFilePath(string $pathToSourceFile): Reader
{
try {
$csv = Reader::createFromPath($pathToSourceFile);
$csv->setHeaderOffset(0);
} catch (Throwable $e) {
throw new CouldNotLoadFileException(sprintf('Could not found file %s', $pathToSourceFile));
}
return $csv;
}
private function invalidateVouchers(array $record): void
{
$code = $record[self::CODE];
$this->repository->updateExpirationDate($code, self::END_DATE_TIME);
}
/**
* @param Reader $csv
* @return void
*/
private function invalidateVouchersInBulk(Reader $csv): void
{
foreach ($csv->getRecords() as $record) {
$this->invalidateVouchers($record);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment