em = $om; $this->size_index = []; parent::__construct(); } protected function configure() { $this->setName('battery:import') ->setDescription('Import a CSV file with batteries and prices.') ->setHelp('Creates battery sizes and models based on imported CSV.') ->addArgument('file', InputArgument::REQUIRED, 'Path to the CSV file.') ->addArgument('model', InputArgument::REQUIRED, 'Model to match to CSV contents.'); } protected function populateSizeIndex() { $this->size_index = []; $sizes = $this->em->getRepository(BatterySize::class)->findAll(); foreach ($sizes as $size) { $key = trim(strtolower($size->getName())); $this->size_index[$key] = $size; } } protected function getWarrantyPrivate($model_name) { switch (strtolower($model_name)) { case 'excel': return 24; case 'gold': return 21; case 'enduro': return 15; } return 15; } protected function getWarrantyCommercial($model_name) { switch (strtolower($model_name)) { case 'excel': return 8; case 'gold': return 6; case 'enduro': return 6; } return 6; } protected function execute(InputInterface $input, OutputInterface $output) { $csv_file = $input->getArgument('file'); $this->populateSizeIndex(); /* CSV column order: 0 - size 1 - sap code 2 - price 3 - trade in price other 4 - trade in price motolite 5 - trade in price premium */ // 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; // manufacturer $bmfg = $em->getRepository(BatteryManufacturer::class)->find(1); // model $model_name = $input->getArgument('model'); $model = new BatteryModel(); $model->setName($model_name); $em->persist($model); $row_num = 1; while (($fields = fgetcsv($fh)) !== false) { $output->writeln("Parsing row " . $row_num . "..."); $size_name = $fields[self::F_SIZE]; // check if in size index $size_key = trim(strtolower($size_name)); if (isset($this->size_index[$size_key])) $size = $this->size_index[$size_key]; else { // create new size $size = new BatterySize(); $size->setName($size_name) ->setTIPriceOther($fields[self::F_TIP_OTHER]) ->setTIPriceMotolite($fields[self::F_TIP_MOTOLITE]) ->setTIPricePremium($fields[self::F_TIP_PREMIUM]); $em->persist($size); // put in our index $this->size_index[$size_key] = $size; } // create battery // TODO: check if dupe exists? $price = trim(str_replace(',', '', $fields[self::F_SRP])); $batt = new Battery(); $batt->setManufacturer($bmfg) ->setModel($model) ->setSize($size) ->setSAPCode($fields[self::F_SAP_CODE]) ->setWarrantyPrivate($this->getWarrantyPrivate($model_name)) ->setWarrantyCommercial($this->getWarrantyCommercial($model_name)) ->setSellingPrice($price) ->setReserveCapacity(0) ->setLength(0) ->setWidth(0) ->setHeight(0) ->setTotalHeight(0) ->setProductCode(''); $em->persist($batt); $row_num++; } $em->flush(); } }