resq/src/Command/ImportCMBBatteryTradeInPriceCommand.php
2019-10-11 09:13:30 +00:00

113 lines
2.8 KiB
PHP

<?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 Doctrine\Common\Persistence\ObjectManager;
use App\Entity\BatterySize;
class ImportCMBBatteryTradeInPriceCommand extends Command
{
const F_SIZE_DESC = 2;
const F_TRADEIN_PRICE = 3;
protected $em;
protected $bsize_hash;
public function __construct(ObjectManager $om)
{
$this->em = $om;
// load existing sizes
$this->loadBatterySizes();
parent::__construct();
}
protected function configure()
{
$this->setName('cmbbatterydata:importtradeinprice')
->setDescription('Import a CSV file with trade in prices.')
->setHelp('Adds the battery tradein prices to existing batteries based on imported CSV.')
->addArgument('file', InputArgument::REQUIRED, 'Path to the CSV file.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$csv_file = $input->getArgument('file');
// attempt to open file
try
{
$fh = fopen($csv_file, "r");
}
catch (Exception $e)
{
throw new Exception('The file "' . $csv_file . '" could be read.');
}
// get entity manager
$em = $this->em;
// loop through the rows
$row_num = 0;
error_log('Processing battery tradein price csv file...');
while (($fields = fgetcsv($fh)) !== false)
{
// data starts at row 2
if ($row_num < 2)
{
$row_num++;
continue;
}
// tradein price info
// battery price info
$desc = trim($fields[self::F_SIZE_DESC]);
$price = trim($fields[self::F_TRADEIN_PRICE]);
$clean_price = trim($price, '$');
$size_info = explode(' ', $desc);
$size = $size_info[1];
if (isset($this->bsize_hash[$size]))
{
$battery_size = $this->bsize_hash[$size];
// use TIPriceMotolite
$battery_size->setTIPriceMotolite($clean_price);
$this->em->persist($battery_size);
$this->em->flush();
}
else
{
error_log('Cannot find battery size ' . $size);
}
}
}
protected function loadBatterySizes()
{
$this->bsize_hash = [];
$batt_sizes = $this->em->getRepository(BatterySize::class)->findAll();
foreach ($batt_sizes as $batt_size)
{
$name = $batt_size->getName();
$this->bsize_hash[$name] = $batt_size;
}
}
}