Skip to content

Instantly share code, notes, and snippets.

@frankdejonge
Last active October 22, 2018 14:13
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 frankdejonge/bba07f9ddb0756d362bed9bc3ffd5e43 to your computer and use it in GitHub Desktop.
Save frankdejonge/bba07f9ddb0756d362bed9bc3ffd5e43 to your computer and use it in GitHub Desktop.
Asset locating in Symfony with cashed manifest contents.
<?php
namespace App\Twig;
interface AssetLocator
{
public function lookup(string $asset): string;
}
<?php
namespace App\Twig;
use function file_get_contents;
use function getenv;
use function json_decode;
use function ltrim;
use function pathinfo;
use const PATHINFO_EXTENSION;
class DevAssetLocator implements AssetLocator
{
private $map = [];
public function __construct()
{
if (\is_file(__DIR__ . '/../../../public/dist/manifest.json')) {
$this->map = json_decode(file_get_contents(__DIR__ . '/../../../public/dist/manifest.json'), true);
}
}
public function lookup(string $asset): string
{
if (getenv('USE_WEBPACK_DEV_SERVER') !== 'yes') {
return $this->map[$asset] ?? '/' . ltrim($asset, '/');
}
$asset = ltrim($asset, '/');
if (pathinfo($asset, PATHINFO_EXTENSION) === 'js') {
$asset = 'dist/' . $asset;
}
return 'http://localhost:9001/' . ltrim($asset, '/');
}
}
<?php
namespace App\Twig;
class ProdAssetLocator implements AssetLocator
{
private $map = [];
public function __construct(array $map = [])
{
$this->map = $map;
}
public function lookup(string $asset): string
{
return $this->map[$asset] ?? $asset;
}
}
<?php
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\Extension\GlobalsInterface;
use Twig\TwigFilter;
use Twig_Function;
class TwigExtension extends AbstractExtension implements GlobalsInterface
{
/**
* @var AssetLocator
*/
private $assetLocator;
public function __construct(
AssetLocator $assetLocator
) {
$this->assetLocator = $assetLocator;
}
public function getFunctions()
{
return [
new Twig_Function('asset_path', function (string $path) {
return $this->assetLocator->lookup($path);
}),
];
}
}
<?php
namespace App\DependencyInjection;
use App\Twig\ProdAssetLocator;
use function file_get_contents;
use function json_decode;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
class UseProdAssetMapPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$definition = new Definition(ProdAssetLocator::class);
$definition->setArgument(0, json_decode(file_get_contents(__DIR__.'/../../../public/dist/manifest.json'), true));
$container->setDefinition('app.asset_locator', $definition);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment