Created
July 25, 2016 10:38
-
-
Save rossriley/46c8b70b076e8f437ff32376cdfbb3b9 to your computer and use it in GitHub Desktop.
Import Content to Bolt from CSV File
This file contains hidden or 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 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