Skip to content

Instantly share code, notes, and snippets.

@Prometee
Created December 11, 2018 16:24
Show Gist options
  • Save Prometee/3354ec87c0946fdc0e1c99536cbd5e57 to your computer and use it in GitHub Desktop.
Save Prometee/3354ec87c0946fdc0e1c99536cbd5e57 to your computer and use it in GitHub Desktop.
Allow twig template override into a Bundle or an App
<?php
declare(strict_types=1);
namespace App\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
abstract class AbstractTwigTemplateCompilerPass implements CompilerPassInterface
{
protected $overridden_bundles_views = [];
public function loadOverridenBundlesDirectory($dir)
{
foreach (scandir($dir) as $item) {
$path = $dir . '/' . $item;
if (preg_match('#(Bundle|Plugin)$#', $item) && is_dir($path)) {
$this->overridden_bundles_views[$path] = preg_replace('#(Bundle)$#', '', $item);
}
}
}
public function process(ContainerBuilder $container)
{
if ($this->overridden_bundles_views) {
$loader = $container->getDefinition('twig.loader.filesystem');
//Backup the calls
$calls = $loader->getMethodCalls();
$call0 = null;
//Backup the first addPath because is normally the main one
foreach ($calls as $i => $call) {
if ($call[0] === 'addPath') {
$call0 = $calls[$i];
unset($calls[$i]);
break;
}
}
foreach ($this->overridden_bundles_views as $path => $twig_name) {
array_unshift($calls, ['addPath', [$path, $twig_name]]);
}
//Readd main call
if ($call0) {
array_unshift($calls, $call0);
}
//Save and replace new calls
$loader->setMethodCalls($calls);
}
}
}
<?php
declare(strict_types=1);
namespace App;
use App\DependencyInjection\Compiler\TwigTemplateCompilerPass
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\DependencyInjection\ContainerBuilder;
final class Kernel extends BaseKernel
{
// ...
protected function build(ContainerBuilder $container)
{
$container->addCompilerPass(new TwigTemplateCompilerPass(__DIR__ . '/Resources/views/overrides'));
parent::build($container);
}
// ...
}
<?php
declare(strict_types=1);
namespace App\DependencyInjection\Compiler;
class TwigTemplateCompilerPass extends AbstractTwigTemplateCompilerPass
{
public function __construct($dir)
{
$this->loadOverridenBundlesDirectory($dir);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment