src/Service/Content/Widgetizer.php line 86

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service\Content;
  4. use App\Entity\Content\PageTranslation;
  5. use Symfony\Component\HttpFoundation\RequestStack;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpKernel\Controller\ControllerReference;
  8. use Symfony\Component\HttpKernel\Fragment\InlineFragmentRenderer;
  9. class Widgetizer
  10. {
  11. protected array $widgets = [
  12. 'google_map' => 'App\\Controller\\App\\App\\PublicController::googleMapAction',
  13. 'contact_form' => 'App\\Controller\\App\\App\\PublicController::contactFormAction',
  14. 'blog' => 'App\\Controller\\Content\\App\\BlogController::byTypeAction',
  15. 'documents' => 'App\\Controller\\Content\\App\\DocumentController::widgetAction',
  16. ];
  17. private InlineFragmentRenderer $fragmentRenderer;
  18. private RequestStack $requestStack;
  19. public function __construct(InlineFragmentRenderer $fragmentRenderer, RequestStack $requestStack)
  20. {
  21. $this->fragmentRenderer = $fragmentRenderer;
  22. $this->requestStack = $requestStack;
  23. }
  24. public function compile(string $content = null): ?string
  25. {
  26. if (empty($content)) {
  27. return '';
  28. }
  29. return preg_replace_callback('/%%(.*)%%/', [$this, 'replaceWithWidget'], $content);
  30. }
  31. private function replaceWithWidget($matches): string
  32. {
  33. $parameters = explode(' ', $matches[1]);
  34. $widget = array_shift($parameters);
  35. $controller = $this->widgets[$widget] ?? null;
  36. if (!$controller) {
  37. return '';
  38. }
  39. $parameters = $this->mapParams($parameters);
  40. $response = $this->getWidget($controller, $parameters);
  41. if (!$response instanceof Response) {
  42. return '';
  43. }
  44. return $response->getContent();
  45. }
  46. private function mapParams($params = array()): array
  47. {
  48. $newParams = array();
  49. foreach ($params as $param) {
  50. preg_match('/([a-zA-Z0-9_]+)\=\"([^"]+)\"/', $param, $matches);
  51. $value = array_pop($matches);
  52. $key = array_pop($matches);
  53. $newParams[$key] = $value;
  54. }
  55. return $newParams;
  56. }
  57. private function getWidget($controller, array $attributes = array(), array $query = array()): ?Response
  58. {
  59. $request = $this->requestStack->getCurrentRequest();
  60. $attributes['_locale'] = $request->getLocale();
  61. return $this->fragmentRenderer->render(new ControllerReference($controller, $attributes, $query), $request);
  62. }
  63. public function widgetize(PageTranslation $translation): PageTranslation
  64. {
  65. return $translation
  66. ->setContent(
  67. $this->compile(
  68. $translation->getContent()
  69. )
  70. )
  71. /*->setPageTop(
  72. $this->compile(
  73. $translation->getPageTop()
  74. )
  75. )
  76. ->setPageBottom(
  77. $this->compile(
  78. $translation->getPageBottom()
  79. )
  80. )*/;
  81. }
  82. }