<?php
/**
* Twig Content Scan
*
* @author Vincent van Waasbergen <v.vanwaasbergen@visualmedia.nl>
*/
namespace VisualMedia\LisaBundle\Twig;
use ReflectionClass;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\Markup;
use VisualMedia\LisaBundle\Component\Manager;
use VisualMedia\LisaBundle\Component\ManagerData;
use VisualMedia\LisaBundle\Doctrine\EntityManager;
use VisualMedia\LisaBundle\Service\EditorWidgetProvider;
use VisualMedia\LisaBundle\Service\LinkProvider;
use VisualMedia\ProductBundle\Entity\BaseProduct;
use VisualMedia\ProductBundle\Entity\BaseProductCategory;
use VisualMedia\ProductBundle\Manager\BaseProductManager;
use VisualMedia\ProductBundle\Manager\BaseProductCategoryManager;
use VisualMedia\RoutingBundle\Manager\BaseRouteManager;
/**
* Twig Content Scan
*/
class TwigContentScan extends AbstractExtension
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* @param ContainerInterface $container
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* {@inheritdoc}
*/
public function getFilters(): array
{
return [
new TwigFilter('scan', [ $this, 'scan' ]),
];
}
/**
* @param string $content
* @return string
*/
public function scan(?string $content)
{
$content = $this->includeWidgets($content);
$content = $this->includeLinks($content);
$content = $this->includeProducts($content);
$content = $this->convertSmartQuotes($content);
return new Markup($content, 'UTF-8');
}
/**
* @param string $content
* @return string
*/
public function includeWidgets(?string $content): ?string
{
if ($this->container->has(EditorWidgetProvider::class)) {
$content = preg_replace_callback('/<div.*?data-type="(.*?)">(.*?)<\/div>/', function($matches) {
list($full, $type, $json) = $matches;
$json = html_entity_decode($json);
$data = json_decode($json, true);
$provider = $this->container->get(EditorWidgetProvider::class);
if (!empty($type) && null !== $widget = $provider->getWidget($type)) {
return $widget->scan($data);
}
return null;
}, $content);
}
return $content;
}
/**
* @param string $content
* @return string
*/
public function includeLinks(?string $content): ?string
{
$content = preg_replace_callback('/href=\"\[(.*?)@\/(.*?)\/#(.*?)]"/', function($matches) {
list($full, $type, $title, $identifier) = $matches;
$linkProvider = $this->container->get(LinkProvider::class);
$router = $this->container->get('router');
$entityManager = $this->container->get('doctrine.orm.entity_manager');
if (null !== $linkFactory = $linkProvider->getLinkFactory($type)) {
// Fixed route.
if ($type === 'fixed_route') {
return sprintf('href="%s"', $router->generate($identifier));
}
// Get all registered entities, based on given type
$entities = [];
foreach ($entityManager->getMetadataFactory()->getAllMetadata() as $metadata) {
if ($metadata->table['name'] === $type) {
$entities[] = sprintf('%s#%d', $metadata->getName(), $identifier);
}
}
// Get route based on given entities, fallback use entity slug. Check for route or entity.
$managerData = new ManagerData([ $this->routeManager::OPTION_ENTITY_KEY_IN => $entities ]);
if ($this->container->has(BaseRouteManager::class) && null === $route = $this->routeManager->getFirst($managerData)) {
$routeManager = $this->container->get(BaseRouteManager::class);
$entityRepository = $entityManager->getRepository($linkFactory->getEntity());
if (null !== $entity = $entityRepository->getFirst(new ManagerData(array('id' => $identifier)))) {
$params = [];
$reflection = new ReflectionClass(get_class($entity));
if ($reflection->hasMethod('getSlug')) {
$params['slug'] = $entity->getSlug();
}
elseif ($reflection->hasProperty('slug')) {
$params['slug'] = $entity->{ 'slug' };
}
else {
$params['id'] = $entity->getId();
}
return sprintf('href="%s"', $router->generate($linkFactory->getRoute(), $params));
}
}
else {
return sprintf('href="%s"', $router->generate(sprintf('route#%d', $route->getId())));
}
}
return null;
}, $content);
return $content;
}
/**
* @param string $content
* @return string
*/
public function includeProducts(?string $content): ?string
{
if ($this->container->has(BaseProductManager::class)) {
$content = preg_replace_callback('/\[include_product\((?<slugs>.*)\)\]/', function($matches) {
if (!empty($slugs = $matches['slugs'])) {
$slugs = html_entity_decode($slugs, ENT_HTML5|ENT_QUOTES);
$slugs = trim(preg_replace('/\s+/', '', $slugs));
$slugs = str_replace('"', '', $slugs);
$slugs = str_replace('\'', '', $slugs);
$slugs = explode(',', $slugs);
$slugs = array_filter($slugs);
$productManager = $this->container->get(BaseProductManager::class);
$qb = $productManager->getEntityManager()->createQueryBuilder();
$qb->select('p');
$qb->from(BaseProduct::class, 'p');
$qb->leftJoin('p.contents', '_contents');
$qb->andWhere($qb->expr()->in('_contents.slug', $slugs));
if (!empty($products = $qb->getQuery()->getResult())) {
$twig = $this->container->get('twig');
$result = $twig->render('@VisualMediaProduct/Product/include.html.twig', [
'products' => $products,
]);
return $result;
}
return $matches[0] ?? null;
}
return null;
}, $content);
}
if ($this->container->has(BaseProductCategoryManager::class)) {
$content = preg_replace_callback('/\[include_product_category\((?<slug>.*)\)\]/', function($matches) {
if (!empty($slug = $matches['slug'])) {
$slug = html_entity_decode($slug, ENT_HTML5|ENT_QUOTES);
$slug = trim(preg_replace('/\s+/', '', $slug));
$slug = str_replace('"', '', $slug);
$slug = str_replace('\'', '', $slug);
$productCategoryManager = $this->container->get(BaseProductCategoryManager::class);
$qb = $productCategoryManager->getEntityManager()->createQueryBuilder();
$qb->select('pc');
$qb->from(BaseProductCategory::class, 'pc');
$qb->leftJoin('pc.contents', '_contents');
$qb->andWhere($qb->expr()->eq('_contents.slug', $qb->expr()->literal((string) $slug)));
if (null !== $category = $qb->getQuery()->getOneOrNullResult()) {
$twig = $this->container->get('twig');
$result = $twig->render('@VisualMediaProduct/Product/include.html.twig', [
'products' => $category->getProducts(),
]);
return $result;
}
return $matches[0] ?? null;
}
return null;
}, $content);
}
return $content;
}
/**
* @param string $string
* @return string
*/
public function convertSmartQuotes(string $string): string
{
$search = [ '', '', '', '' ];
$replace = [ '“', '”', '‘', '’' ];
return str_replace($search, $replace, $string);
}
}