From 07373e49c2ba8166a287347b0631cdd745b276ae Mon Sep 17 00:00:00 2001 From: Alexey Skobkin Date: Thu, 28 May 2015 22:21:58 +0300 Subject: [PATCH] Users import command. --- .../Command/ImportUsersCommand.php | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 src/Skobkin/Bundle/PointToolsBundle/Command/ImportUsersCommand.php diff --git a/src/Skobkin/Bundle/PointToolsBundle/Command/ImportUsersCommand.php b/src/Skobkin/Bundle/PointToolsBundle/Command/ImportUsersCommand.php new file mode 100644 index 0000000..46912b1 --- /dev/null +++ b/src/Skobkin/Bundle/PointToolsBundle/Command/ImportUsersCommand.php @@ -0,0 +1,102 @@ + (-1)) TO '/tmp/point_users.csv' WITH HEADER DELIMITER '|' CSV; + */ +class ImportUsersCommand extends ContainerAwareCommand +{ + protected function configure() + { + $this + ->setName('point:import:users') + ->setDescription('Import users from CSV file') + ->addArgument( + 'file', + InputArgument::REQUIRED, + 'CSV file path' + ) + ->addOption( + 'check-only', + null, + InputOption::VALUE_NONE, + 'If set, command will not perform write operations in the database' + ) + ->addOption( + 'no-skip-first', + null, + InputOption::VALUE_NONE, + 'Do not skip first line (if no headers in CSV file)' + ) + ; + } + + protected function execute(InputInterface $input, OutputInterface $output) + { + $em = $this->getContainer()->get('doctrine.orm.entity_manager'); + $fs = new Filesystem(); + + $fileName = $input->getArgument('file'); + + if (!($fs->exists($fileName) && is_readable($fileName))) { + $output->writeln('File does not exists or not readable.'); + return false; + } + + if (false === ($file = fopen($fileName, 'r'))) { + $output->writeln('fopen() error'); + return false; + } + + if (!$input->getOption('no-skip-first')) { + // Reading headers line + $test = fgets($file); + } + + $count = 0; + + while (false !== ($row = fgetcsv($file, 1000, '|'))) { + if (count($row) !== 4) { + continue; + } + + $createdAt = \DateTime::createFromFormat('Y-m-d_H:i:s', $row[3]); + + if (!$createdAt) { + $createdAt = new \DateTime(); + } + + $user = new User(); + $user + ->setId($row[0]) + ->setLogin($row[1]) + ->setName($row[2]) + ->setCreatedAt($createdAt) + ; + + if (!$input->getOption('check-only')) { + $em->persist($user); + $em->flush($user); + $em->detach($user); + } + + if ($output->isVerbose()) { + $output->writeln('@' . $row[1] . ' added'); + } + + $count++; + } + + $output->writeln($count . ' users imported.'); + } +} \ No newline at end of file