LogansUA
7/21/2016 - 8:55 AM

Symfony2 clear route cache by deleting app<Environment>UrlGenerator.* and app<Environment>UrlMatcher.* files

Symfony2 clear route cache by deleting appUrlGenerator.* and appUrlMatcher.* files

# AppBundle/Resources/config/services.yml
services:
    app.bundle.redirect_manager:
        class: AppBundle\Service\ClearRouteCacheService
        arguments:
            - "@filesystem"
            - "@router"
            - "%kernel.cache_dir%"
<?php

namespace AppBundle\Service;

use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpFoundation\File\File;

/**
 * Class ClearRouteCacheService
 */
class ClearRouteCacheService
{
    /**
     * @var Filesystem $fs Filesystem
     */
    private $fs;

    /**
     * @var Router $router Router
     */
    private $router;

    /**
     * @var string $cacheDir Cache dir path
     */
    private $cacheDir;

    /**
     * Constructor
     *
     * @param Filesystem $fs             Filesystem
     * @param Router     $router         Router
     * @param string     $kernelCacheDir Cache dir path
     */
    public function __construct(Filesystem $fs, Router $router, $kernelCacheDir)
    {
        $this->fs       = $fs;
        $this->router   = $router;
        $this->cacheDir = $kernelCacheDir;
    }

    /**
     * Clear cache
     */
    public function clearRouteCache()
    {
        // Delete routing cache files
        $finder = new Finder();

        /** @var File $file */
        foreach ($finder->files()->depth('== 0')->in($this->cacheDir) as $file) {
            if (preg_match('/UrlGenerator|UrlMatcher/', $file->getFilename()) === 1) {
                $this->fs->remove($file->getRealPath());
            }
        }

        $this->router->warmUp($this->cacheDir);
    }
}