Last active
June 27, 2017 02:45
-
-
Save elenakondrateva/eaa393b8b1ad6f491759a220662bb883 to your computer and use it in GitHub Desktop.
Symfony Command Import from CSV abstract class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Acme\CoreBundle\Command; | |
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; | |
use Symfony\Component\Console\Input\InputArgument; | |
use Symfony\Component\Console\Input\InputInterface; | |
use Symfony\Component\Console\Input\InputOption; | |
use Symfony\Component\Console\Output\OutputInterface; | |
abstract class ImportFromCSVCommand extends ContainerAwareCommand | |
{ | |
const STATUS_CODE_SUCCESS = 0; | |
const STATUS_CODE_GENERAL_ERROR = -1; | |
/** | |
* Output additional and debugging info | |
* @var bool | |
*/ | |
protected $verbose = false; | |
/** | |
* @var integer | |
*/ | |
protected $rowsProcessed = 0; | |
protected function execute(InputInterface $input, OutputInterface $output) { | |
$this->input = $input; | |
$this->output = $output; | |
if ($input->getOption('verbose')) { | |
$this->verbose = true; | |
} | |
$this->preImport(); | |
$rowsProcessed = $this->importCSV($input->getOption('csv')); | |
$this->postImport(); | |
$output->writeln(''); | |
$output->writeln(sprintf('<comment>Done. Total processed: %d.</comment>', $rowsProcessed)); | |
return self::STATUS_CODE_SUCCESS; | |
} | |
protected function preImport() | |
{ | |
} | |
protected function postImport() | |
{ | |
} | |
/** | |
* @param $csvPath path to CSV file in filesystem | |
* @return bool | |
*/ | |
protected function importCSV($csvPath) | |
{ | |
if (!file_exists($csvPath)) { | |
$this->output->writeln('<error>Wrong path to CSV file.</error>'); | |
return false; | |
} | |
if (pathinfo($csvPath)['extension'] != 'csv' || mime_content_type($csvPath) != 'text/plain') { | |
$this->output->writeln('<error>File must be in CSV format.</error>'); | |
return false; | |
} | |
if (($handle = fopen($csvPath, 'r')) !== false) { | |
$i = 0; | |
while (($data = fgetcsv($handle, null, ';')) !== false) { | |
$i++; | |
$data = explode(',', $data[0]); | |
if ($this->processCSVRow($i, $data)) { | |
$this->rowsProcessed++; | |
} | |
} | |
} | |
return $this->rowsProcessed; | |
} | |
/** | |
* @param $rowNumber | |
* @param array $data | |
* @return boolean | |
*/ | |
protected abstract function processCSVRow($rowNumber, array $data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment