Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weatheredwatcher/7fd93c2ae11638cf7103cb9b67bb5c57 to your computer and use it in GitHub Desktop.
Save weatheredwatcher/7fd93c2ae11638cf7103cb9b67bb5c57 to your computer and use it in GitHub Desktop.
<?php
namespace App\Command;
use App\Entity\Blog as EntityBlog;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Finder\Finder;
use Mni\FrontYAML\Parser;
use Doctrine\ORM\EntityManagerInterface as EntityManager;
use Carbon\Carbon;
class ConvertMarkdownToBlogCommand extends Command
{
// the name of the command (the part after "bin/console")
protected static $defaultName = 'app:convert-blog';
private $manager;
public function __construct(EntityManager $manager)
{
$this->manager = $manager;
parent::__construct();
}
protected function configure()
{
$this
->setDescription('Import Markdown Files, like from Hugo or Jekyl.')
->setHelp('This command allows you to import markdown files into the blog...')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$path = "/home/weatheredwatcher/Sites/weatheredwatcher.netlify.com/content/posts";
$finder = new Finder();
$parser = new Parser();
$finder->files()->in($path);
foreach ($finder as $file) {
$title = $file->getFilename();
$contents = $file->getContents();
$document = $parser->parse($contents,false);
$yaml = $document->getYAML();
$text = $document->getContent();
$entry = new EntityBlog();
$created = new Carbon($yaml['date']);
$entry->setTitle($yaml['title']);
$entry->setContent($text);
$entry->setCreated($created);
$this->manager->persist($entry);
}
$this->manager->flush();
return Command::SUCCESS;
returning int(1))
}
}
@weatheredwatcher
Copy link
Author

In setting up my new site in php, I wanted to go back to a DB backed blog. Most of my entries are in flat files and markdown. So I wrote this code to convert a directory of markdown files into DB entries. It should be fairly easy to modify based on your markdown files and you entity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment