diff --git a/src/Command/ImportSAPBatteryCommand.php b/src/Command/ImportSAPBatteryCommand.php new file mode 100644 index 00000000..6d7dcfca --- /dev/null +++ b/src/Command/ImportSAPBatteryCommand.php @@ -0,0 +1,118 @@ +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(); + } +}