Add html indent bundle

This commit is contained in:
2018-07-18 21:40:17 +03:00
parent 218a911dfd
commit 8451c8abd0
12 changed files with 820 additions and 5 deletions

View File

@ -0,0 +1,20 @@
<?php
namespace Homepage\HtmlPrettierBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
class HtmlPrettierExtension extends Extension
{
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
}
}

View File

@ -0,0 +1,56 @@
<?php
namespace Homepage\HtmlPrettierBundle;
use Gajus\Dindent\Indenter;
use Sculpin\Core\Event\SourceSetEvent;
use Sculpin\Core\Sculpin;
use Sculpin\Core\Source\SourceSet;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class HtmlPrettier implements EventSubscriberInterface
{
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array
{
return [
Sculpin::EVENT_AFTER_FORMAT => ['formatHtml', -100],
];
}
public function formatHtml(SourceSetEvent $event): void
{
$indenter = new Indenter([
'indentation_character' => ' ',
]);
$sources = $this->filterSource($event->sourceSet());
/** @var \Sculpin\Core\Source\SourceInterface $source */
foreach ($sources as $source) {
$html = $source->formattedContent();
$formatted = $indenter->indent($html);
$source->setFormattedContent($formatted);
}
}
private function filterSource(SourceSet $sourceSet): \Generator
{
/** @var \Sculpin\Core\Source\SourceInterface $source */
foreach ($sourceSet->allSources() as $source) {
$filename = $source->filename();
if ($this->endsWith($filename, '.md') || $this->endsWith($filename, '.html.twig')) {
yield $source;
}
}
}
private function endsWith($haystack, $needle): bool
{
$length = \strlen($needle);
return $length === 0 || (substr($haystack, -$length) === $needle);
}
}

View File

@ -0,0 +1,10 @@
<?php
namespace Homepage\HtmlPrettierBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class HtmlPrettierBundle extends Bundle
{
public const class_name = __CLASS__;
}

View File

@ -0,0 +1,6 @@
services:
homepage.html_prettier:
class: \Homepage\HtmlPrettierBundle\HtmlPrettier
tags:
- { name: kernel.event_subscriber }