Add command to import SAP battery csv #172

This commit is contained in:
Kendrick Chan 2019-01-20 15:38:38 +08:00
parent 50d3a8e200
commit 081d9cb93c

View file

@ -0,0 +1,118 @@
<?php
namespace App\Command;
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\Validator\Validator\ValidatorInterface;
use Doctrine\Common\Persistence\ObjectManager;
use App\Entity\SAPBattery;
use App\Entity\SAPBatteryBrand;
use App\Entity\SAPBatterySize;
use DateTime;
class ImportSAPBatteryCommand extends Command
{
private $em;
public function __construct(ObjectManager $em)
{
$this->em = $em;
parent::__construct();
}
protected function configure()
{
$this->setName('sap_battery:import')
->setDescription('Import a CSV file with SAP battery data.')
->setHelp('Creates SAP battery data entries off imported CSV.')
->addArgument('file', InputArgument::REQUIRED, 'Path to the CSV file.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$csv_file = $input->getArgument('file');
// CSV column order:
// 0 - brand
// 1 - sku
// 2 - size
// attempt to open file
try
{
$handle = fopen($csv_file, "r");
}
catch (Exception $e)
{
throw new Exception('The file "' . $csv_file . '" could not be read.');
}
// get entity manager
$em = $this->em;
// row counter
$row = 1;
// has error?
$has_error = false;
// hashes
$brand_hash = [];
$size_hash = [];
$battery_hash = [];
// loop through rows and build hashes
while (($fields = fgetcsv($handle)) !== false)
{
// check if blank
if (strlen(trim($fields[0])) == 0)
continue;
// clean up fields
$clean_brand = trim($fields[0]);
$clean_sku = trim($fields[1]);
$clean_size = trim($fields[2]);
$output->writeln("Parsing $clean_sku...");
// brand hash
if (!isset($brand_hash[$clean_brand]))
{
$brand = new SAPBatteryBrand();
$brand->setName($clean_brand);
$em->persist($brand);
$brand_hash[$clean_brand] = $brand;
}
// size hash
if (!isset($size_hash[$clean_size]))
{
$size = new SAPBatterySize();
$size->setName($clean_size);
$em->persist($size);
$size_hash[$clean_size] = $size;
}
// create battery entry
$battery = new SAPBattery();
$battery->setID($clean_sku)
->setSize($size_hash[$clean_size])
->setBrand($brand_hash[$clean_brand]);
$em->persist($battery);
}
$em->flush();
}
}