Skip to content

Instantly share code, notes, and snippets.

@Boorj
Forked from rossriley/CSVImportCommand.php
Created November 23, 2017 12:23
Show Gist options
  • Save Boorj/5ddef090f46b3cb09e97eb5a8754100a to your computer and use it in GitHub Desktop.
Save Boorj/5ddef090f46b3cb09e97eb5a8754100a to your computer and use it in GitHub Desktop.
Import Content to Bolt from CSV File
<?php
namespace Mysite\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;
use Bolt\Application;
class ContentImportCommand extends Command
{
public $db;
public $app;
public function __construct(Application $app)
{
$this->app = $app;
$this->app['request'] = false;
parent::__construct();
}
protected function configure()
{
$this->setName('example:content-import')
->setDescription('This command imports content from a CSV format file.')
->setHelp('')
->addOption(
'file', 'f', InputOption::VALUE_REQUIRED, 'CSV File to import from', null
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$file = $input->getOption('file');
$pages = $this->parseCsv($file);
$existing = $this->app['storage']->getContent('pages');
// This empties the current database
foreach ($existing as $existing) {
$this->app['storage']->deleteContent('pages', $existing['id']);
}
foreach ($pages as $page) {
$record = $this->app['storage']->getEmptyContent('pages');
$record->setValues([
'title' => $page['Title'],
'teaser' => $page['Teaser'],
'body' => $page['Body'],
'status' => 'published',
]);
if ($page['Category'] == 'News') {
$record->setTaxonomy('pages', 'news');
}
if ($page['Category'] == 'About') {
$record->setTaxonomy('pages', 'about');
}
if ($page['Category'] == 'Other') {
$record->setTaxonomy('pages', 'other');
}
$this->app['storage']->saveContent($record);
$output->writeln('<info>Successfully saved page: '.$record['title'].'</info>');
}
}
protected function parseCsv($file)
{
ini_set('auto_detect_line_endings', '1');
mb_internal_encoding('utf8');
$rows = [];
$file = new \SplFileObject($file);
$file->setFlags(\SplFileObject::DROP_NEW_LINE);
$headers = false;
while (!$file->eof()) {
if (!$headers) {
$headers = $file->fgetcsv();
}
$row = $file->fgetcsv();
if (count(array_filter($row))) {
$rows[] = array_combine($headers, $row);
}
}
return $rows;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment