Skip to content

Instantly share code, notes, and snippets.

@BoShurik
Created July 5, 2016 16:19
Show Gist options
  • Save BoShurik/b45d28e6ff6f65ddd785df0ccf1fda87 to your computer and use it in GitHub Desktop.
Save BoShurik/b45d28e6ff6f65ddd785df0ccf1fda87 to your computer and use it in GitHub Desktop.
Fragment path resolver to clear cache for widgets rendered by render_esi
<?php
namespace AppBundle\Cache;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Controller\ControllerReference;
use Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface;
class FragmentPathResolver
{
/**
* @var FragmentRendererInterface
*/
private $fragmentRenderer;
/**
* @var RequestStack
*/
private $requestStack;
public function __construct(FragmentRendererInterface $fragmentRenderer, RequestStack $requestStack)
{
$this->fragmentRenderer = $fragmentRenderer;
$this->requestStack = $requestStack;
}
/**
* @param string $controller
* @param array $parameters
* @param array $query
* @return null|string
*/
public function resolve($controller, array $parameters = array(), array $query = array())
{
$controllerReference = new ControllerReference($controller, $parameters, $query);
$response = $this->fragmentRenderer->render($controllerReference, $this->requestStack->getMasterRequest());
return $this->parsePath($response->getContent());
}
/**
* @param string $content
* @return null|string
*/
private function parsePath($content)
{
if (empty($content)) {
return null;
}
if (!preg_match('/src=[\'"](.*?)[\'"]/iu', $content, $matches)) {
return null;
}
return $this->fixOrder($matches[1]);
}
/**
* @param $uri
* @return string
*/
private function fixOrder($uri)
{
$hashPosition = strpos($uri, '&_hash=');
if ($hashPosition === false) {
return null;
}
$hash = substr($uri, $hashPosition + 1);
$uri = substr($uri, 0, $hashPosition);
$queryPosition = strpos($uri, '?');
if ($queryPosition === false) {
return null;
}
$fragment = substr($uri, 0, $queryPosition + 1);
$query = substr($uri, $queryPosition + 1);
return sprintf('%s%s&%s', $fragment, $hash, $query);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment