customerRepository = $customerRepository; $this->dataObjectHelper = $dataObjectHelper; $this->customerFactory = $customerFactory; $this->filesystem = $filesystem; } protected function configure() { $this->setName('customer:import:netsuite'); $this->setDescription('Update customer data from Netsuite excel file. Netsuite excel file with customer update data, must contain customer email'); $this->addOption( 'filePath', 'fp', InputOption::VALUE_REQUIRED, ",\r\n please place file in var directory, and give relative file path to filePath" ); } /** * @param string $filePath * @return string */ protected function getFilePath(string $filePath) { $varDirectory = $this->filesystem->getDirectoryRead(DirectoryList::VAR_DIR); // For a specific file return $varDirectory->getAbsolutePath($filePath); } protected function execute(InputInterface $input, OutputInterface $output) { $filePath = $input->getOption('filePath'); $filePath = $this->getFilePath($filePath); if (!file_exists($filePath) || !is_readable($filePath)) { $output->writeln(sprintf('File "%s" does not exist or is not readable.', $filePath)); return 1; } if (!in_array(strtolower(pathinfo($filePath, PATHINFO_EXTENSION)), ['xls', 'xlsx'])) { $output->writeln(sprintf('Import file "%s" must be excel.', $filePath)); return 1; } $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); $reader->setReadDataOnly(true); $workSheet = $reader->load($filePath)->getSheet(0); foreach ($workSheet->toArray() as $row => $item) { if ($row > 0) { $item[3] = empty($item[3]) ? null : trim($item[3]); $item[1] = empty($item[1]) ? null : trim($item[1]); $item[2] = empty($item[2]) ? null : trim($item[2]); if (empty($item[3])) { $output->writeln(sprintf('Row %d email is empty, ignore.', $row+1)); continue; } if (empty($item[1]) && empty($item[2])) { $output->writeln(sprintf('Row %d internal id and stage are empty, ignore.', $row+1)); continue; } $data = [ 'email' => $item[3], 'extension_attributes' => [ 'netsuite_status' => strtolower($item[2]), 'netsuite_id' => $item[1], ], ]; $customer = $this->customerFactory->create(); $this->dataObjectHelper->populateWithArray($customer, $data, CustomerInterface::class); $output->writeln(sprintf('Row %d import success', $row+1)); try { $this->customerRepository->save($customer); } catch (\Exception $e) { $output->writeln(sprintf('Row %d import fail, message: %s', $row+1, $e->getMessage())); } } } return 0; } }