lib/composer/LisaBundle/src/VisualMedia/LisaBundle/Twig/TwigContentScan.php line 63

Open in your IDE?
  1. <?php
  2. /**
  3. * Twig Content Scan
  4. *
  5. * @author Vincent van Waasbergen <v.vanwaasbergen@visualmedia.nl>
  6. */
  7. namespace VisualMedia\LisaBundle\Twig;
  8. use ReflectionClass;
  9. use Symfony\Component\DependencyInjection\ContainerInterface;
  10. use Twig\Extension\AbstractExtension;
  11. use Twig\TwigFilter;
  12. use Twig\Markup;
  13. use VisualMedia\LisaBundle\Component\Manager;
  14. use VisualMedia\LisaBundle\Component\ManagerData;
  15. use VisualMedia\LisaBundle\Doctrine\EntityManager;
  16. use VisualMedia\LisaBundle\Service\EditorWidgetProvider;
  17. use VisualMedia\LisaBundle\Service\LinkProvider;
  18. use VisualMedia\ProductBundle\Entity\BaseProduct;
  19. use VisualMedia\ProductBundle\Entity\BaseProductCategory;
  20. use VisualMedia\ProductBundle\Manager\BaseProductManager;
  21. use VisualMedia\ProductBundle\Manager\BaseProductCategoryManager;
  22. use VisualMedia\RoutingBundle\Manager\BaseRouteManager;
  23. /**
  24. * Twig Content Scan
  25. */
  26. class TwigContentScan extends AbstractExtension
  27. {
  28. /**
  29. * @var ContainerInterface
  30. */
  31. protected $container;
  32. /**
  33. * @param ContainerInterface $container
  34. */
  35. public function __construct(ContainerInterface $container)
  36. {
  37. $this->container = $container;
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function getFilters(): array
  43. {
  44. return [
  45. new TwigFilter('scan', [ $this, 'scan' ]),
  46. ];
  47. }
  48. /**
  49. * @param string $content
  50. * @return string
  51. */
  52. public function scan(?string $content)
  53. {
  54. $content = $this->includeWidgets($content);
  55. $content = $this->includeLinks($content);
  56. $content = $this->includeProducts($content);
  57. $content = $this->convertSmartQuotes($content);
  58. return new Markup($content, 'UTF-8');
  59. }
  60. /**
  61. * @param string $content
  62. * @return string
  63. */
  64. public function includeWidgets(?string $content): ?string
  65. {
  66. if ($this->container->has(EditorWidgetProvider::class)) {
  67. $content = preg_replace_callback('/<div.*?data-type="(.*?)">(.*?)<\/div>/', function($matches) {
  68. list($full, $type, $json) = $matches;
  69. $json = html_entity_decode($json);
  70. $data = json_decode($json, true);
  71. $provider = $this->container->get(EditorWidgetProvider::class);
  72. if (!empty($type) && null !== $widget = $provider->getWidget($type)) {
  73. return $widget->scan($data);
  74. }
  75. return null;
  76. }, $content);
  77. }
  78. return $content;
  79. }
  80. /**
  81. * @param string $content
  82. * @return string
  83. */
  84. public function includeLinks(?string $content): ?string
  85. {
  86. $content = preg_replace_callback('/href=\"\[(.*?)@\/(.*?)\/#(.*?)]"/', function($matches) {
  87. list($full, $type, $title, $identifier) = $matches;
  88. $linkProvider = $this->container->get(LinkProvider::class);
  89. $router = $this->container->get('router');
  90. $entityManager = $this->container->get('doctrine.orm.entity_manager');
  91. if (null !== $linkFactory = $linkProvider->getLinkFactory($type)) {
  92. // Fixed route.
  93. if ($type === 'fixed_route') {
  94. return sprintf('href="%s"', $router->generate($identifier));
  95. }
  96. // Get all registered entities, based on given type
  97. $entities = [];
  98. foreach ($entityManager->getMetadataFactory()->getAllMetadata() as $metadata) {
  99. if ($metadata->table['name'] === $type) {
  100. $entities[] = sprintf('%s#%d', $metadata->getName(), $identifier);
  101. }
  102. }
  103. // Get route based on given entities, fallback use entity slug. Check for route or entity.
  104. $managerData = new ManagerData([ $this->routeManager::OPTION_ENTITY_KEY_IN => $entities ]);
  105. if ($this->container->has(BaseRouteManager::class) && null === $route = $this->routeManager->getFirst($managerData)) {
  106. $routeManager = $this->container->get(BaseRouteManager::class);
  107. $entityRepository = $entityManager->getRepository($linkFactory->getEntity());
  108. if (null !== $entity = $entityRepository->getFirst(new ManagerData(array('id' => $identifier)))) {
  109. $params = [];
  110. $reflection = new ReflectionClass(get_class($entity));
  111. if ($reflection->hasMethod('getSlug')) {
  112. $params['slug'] = $entity->getSlug();
  113. }
  114. elseif ($reflection->hasProperty('slug')) {
  115. $params['slug'] = $entity->{ 'slug' };
  116. }
  117. else {
  118. $params['id'] = $entity->getId();
  119. }
  120. return sprintf('href="%s"', $router->generate($linkFactory->getRoute(), $params));
  121. }
  122. }
  123. else {
  124. return sprintf('href="%s"', $router->generate(sprintf('route#%d', $route->getId())));
  125. }
  126. }
  127. return null;
  128. }, $content);
  129. return $content;
  130. }
  131. /**
  132. * @param string $content
  133. * @return string
  134. */
  135. public function includeProducts(?string $content): ?string
  136. {
  137. if ($this->container->has(BaseProductManager::class)) {
  138. $content = preg_replace_callback('/\[include_product\((?<slugs>.*)\)\]/', function($matches) {
  139. if (!empty($slugs = $matches['slugs'])) {
  140. $slugs = html_entity_decode($slugs, ENT_HTML5|ENT_QUOTES);
  141. $slugs = trim(preg_replace('/\s+/', '', $slugs));
  142. $slugs = str_replace('"', '', $slugs);
  143. $slugs = str_replace('\'', '', $slugs);
  144. $slugs = explode(',', $slugs);
  145. $slugs = array_filter($slugs);
  146. $productManager = $this->container->get(BaseProductManager::class);
  147. $qb = $productManager->getEntityManager()->createQueryBuilder();
  148. $qb->select('p');
  149. $qb->from(BaseProduct::class, 'p');
  150. $qb->leftJoin('p.contents', '_contents');
  151. $qb->andWhere($qb->expr()->in('_contents.slug', $slugs));
  152. if (!empty($products = $qb->getQuery()->getResult())) {
  153. $twig = $this->container->get('twig');
  154. $result = $twig->render('@VisualMediaProduct/Product/include.html.twig', [
  155. 'products' => $products,
  156. ]);
  157. return $result;
  158. }
  159. return $matches[0] ?? null;
  160. }
  161. return null;
  162. }, $content);
  163. }
  164. if ($this->container->has(BaseProductCategoryManager::class)) {
  165. $content = preg_replace_callback('/\[include_product_category\((?<slug>.*)\)\]/', function($matches) {
  166. if (!empty($slug = $matches['slug'])) {
  167. $slug = html_entity_decode($slug, ENT_HTML5|ENT_QUOTES);
  168. $slug = trim(preg_replace('/\s+/', '', $slug));
  169. $slug = str_replace('"', '', $slug);
  170. $slug = str_replace('\'', '', $slug);
  171. $productCategoryManager = $this->container->get(BaseProductCategoryManager::class);
  172. $qb = $productCategoryManager->getEntityManager()->createQueryBuilder();
  173. $qb->select('pc');
  174. $qb->from(BaseProductCategory::class, 'pc');
  175. $qb->leftJoin('pc.contents', '_contents');
  176. $qb->andWhere($qb->expr()->eq('_contents.slug', $qb->expr()->literal((string) $slug)));
  177. if (null !== $category = $qb->getQuery()->getOneOrNullResult()) {
  178. $twig = $this->container->get('twig');
  179. $result = $twig->render('@VisualMediaProduct/Product/include.html.twig', [
  180. 'products' => $category->getProducts(),
  181. ]);
  182. return $result;
  183. }
  184. return $matches[0] ?? null;
  185. }
  186. return null;
  187. }, $content);
  188. }
  189. return $content;
  190. }
  191. /**
  192. * @param string $string
  193. * @return string
  194. */
  195. public function convertSmartQuotes(string $string): string
  196. {
  197. $search = [ '“', '”', '‘', '’' ];
  198. $replace = [ '“', '”', '‘', '’' ];
  199. return str_replace($search, $replace, $string);
  200. }
  201. }