Skip to content

Instantly share code, notes, and snippets.

@imiroslavov
Last active October 2, 2020 14:26
Show Gist options
  • Save imiroslavov/07fff536b0681b6eb747da1a921e8ea4 to your computer and use it in GitHub Desktop.
Save imiroslavov/07fff536b0681b6eb747da1a921e8ea4 to your computer and use it in GitHub Desktop.
<?php
namespace App\Cache;
use App\Service\RouteMapService;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\RouterInterface;
/**
* Class RouteMapCacheWarmer.
*/
class RouteMapCacheWarmer implements CacheWarmerInterface
{
private RouteCollection $routeCollection;
public function __construct(RouterInterface $router)
{
$this->routeCollection = $router->getRouteCollection();
}
public function warmUp($cacheDirectory): array
{
$map = [];
foreach ($this->routeCollection as $name => $route) {
$map[$name] = $route->getPath();
}
$map = var_export($map, true);
$map = <<<EOF
<?php
// This file was generated by running cache:warmup"
return $map;
EOF;
file_put_contents($cacheDirectory.'/'.RouteMapService::ROUTE_MAP_FILENAME, $map, LOCK_EX);
return [];
}
public function isOptional(): bool
{
return false;
}
}
<?php
namespace App\Service;
use Symfony\Component\HttpKernel\KernelInterface;
/**
* Class RouteMapService.
*/
class RouteMapService
{
const ROUTE_MAP_FILENAME = 'route_map.php';
private array $routeMap;
public function __construct(KernelInterface $kernel)
{
$this->routeMap = require_once $kernel->getCacheDir().'/'.static::ROUTE_MAP_FILENAME;
}
public function get(string $name): ?string
{
return $this->routeMap[$name] ?? null;
}
}
services:
App\Cache\RouteMapCacheWarmer:
tags:
- { name: kernel.cache_warmer, priority: 0 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment