src/Twig/Runtime/PlatformComponentRuntime.php line 97

Open in your IDE?
  1. <?php
  2. namespace App\Twig\Runtime;
  3. use App\Entity\User;
  4. use App\Services\Back\Settings\FrontService;
  5. use Exception;
  6. use JsonException;
  7. use Psr\Log\LoggerInterface;
  8. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  9. use Symfony\Component\HttpKernel\KernelInterface;
  10. use Symfony\Component\Security\Core\Security;
  11. use Twig\Environment;
  12. use Twig\Error\LoaderError;
  13. use Twig\Error\RuntimeError;
  14. use Twig\Error\SyntaxError;
  15. use Twig\Extension\RuntimeExtensionInterface;
  16. class PlatformComponentRuntime implements RuntimeExtensionInterface
  17. {
  18. private ParameterBagInterface $params;
  19. private Environment $twig;
  20. private Security $security;
  21. private LoggerInterface $logger;
  22. private FrontService $frontService;
  23. private KernelInterface $kernel;
  24. private string $projectDir;
  25. private array $contentDataCache = [];
  26. private array $componentOptionsCache = [];
  27. private array $componentViewCache = [];
  28. private array $customAtomicViewCache = [];
  29. /**
  30. * @param ParameterBagInterface $params
  31. * @param Environment $twig
  32. * @param Security $security
  33. * @param LoggerInterface $logger
  34. * @param FrontService $frontService
  35. * @param KernelInterface $kernel
  36. * @param string $projectDir
  37. */
  38. public function __construct(
  39. ParameterBagInterface $params,
  40. Environment $twig,
  41. Security $security,
  42. LoggerInterface $logger,
  43. FrontService $frontService,
  44. KernelInterface $kernel,
  45. string $projectDir
  46. ) {
  47. $this->params = $params;
  48. $this->twig = $twig;
  49. $this->security = $security;
  50. $this->logger = $logger;
  51. $this->frontService = $frontService;
  52. $this->projectDir = $projectDir;
  53. $this->kernel = $kernel;
  54. }
  55. /**
  56. * Retourne le contenu d'un component
  57. *
  58. * @TODO Attention,si on passe le $component comme un tableau avec les valeurs du yaml !
  59. * On ne peut pas utiliser le système d'ACL dynamique
  60. *
  61. * @param string|array $component
  62. * @param string $componentKey
  63. * @param null $data
  64. * @param null $index
  65. * @param bool $debug
  66. *
  67. * @return string
  68. *
  69. * @throws JsonException
  70. */
  71. public function component($component, string $componentKey = '', $data = NULL, $index = NULL, bool $debug = FALSE): string
  72. {
  73. $keys = $componentKey;
  74. if (is_array($component) && isset($component[ 'type' ])) {
  75. $value = $component;
  76. } else {
  77. $keyArr = explode('.', $keys);
  78. if (count($keyArr) === 2) {
  79. $data = $this->getContentData($keyArr[ 1 ], $keyArr[ 0 ]);
  80. $value = $data[ 'pageArray' ];
  81. } else {
  82. $value = $this->checkComponent($component, $keys, $index);
  83. }
  84. }
  85. if (!isset($value[ 'type' ])) {
  86. return '<div class="text-danger">The component ' . $component . ' is typeless!</div>';
  87. }
  88. // try {
  89. return $this->buildComponent($value, $keys, $data, $debug);
  90. // }
  91. // catch (LoaderError|RuntimeError|SyntaxError $e)
  92. // {
  93. // if($this->kernel->getEnvironment() == 'dev') throw $e;
  94. //
  95. // $message = 'Le component ' . (is_array($keys) ? implode('.', $keys) : $value[ 'type' ]) . ' ne peut pas être généré.';
  96. // $this->logger->critical($message . $e->getMessage());
  97. //
  98. // $error = '<div class="text-danger">' . $message;
  99. // /** @var User $currentUser */
  100. // $currentUser = $this->security->getUser();
  101. //
  102. // if (($currentUser !== NULL && $currentUser->isDeveloper()) || $this->kernel->getEnvironment() === 'dev') {
  103. // $error .= '<pre>' . $e->getMessage() . '</pre>';
  104. // }
  105. // $error .= '</div>';
  106. // return $error;
  107. // }
  108. }
  109. /**
  110. * @param string $page
  111. * @param $data
  112. * @param bool $isSecurity
  113. *
  114. * @return string
  115. *
  116. * @throws JsonException
  117. */
  118. public function content(string $page, $data = NULL, bool $isSecurity = FALSE, string $key = null): string
  119. {
  120. $frontType = $isSecurity ? 'security' : 'content';
  121. $contentData = $this->getContentData($page, $frontType);
  122. $pageArray = $contentData[ 'pageArray' ] ?? [];
  123. $frontCat = $contentData[ 'frontCat' ];
  124. $divs = $this->getContentStartDivs($pageArray);
  125. $content = '';
  126. if($key) {
  127. if (!isset($pageArray[$key])) {
  128. return '';
  129. }
  130. $content .= $this->component($pageArray[$key], $contentData[ 'contentKey' ] . '.sections.' . $key, $data, NULL, TRUE);
  131. return implode('', $divs) . $content . str_repeat('</div>', count($divs));
  132. }
  133. $items = $pageArray[ 'sections' ];
  134. foreach ($items as $key => $item)
  135. {
  136. // try {
  137. $content .= $this->component($item, $contentData[ 'contentKey' ] . '.sections.' . $key, $data, NULL, TRUE);
  138. // $content .= $this->component( $frontCat . '.' . $page . '.sections.' . $key, $data );
  139. // } catch (Exception $e) {
  140. // /** @var User $currentUser */
  141. // $currentUser = $this->security->getUser();
  142. // if ($currentUser !== NULL && $currentUser->isDeveloper()) {
  143. // echo '<div style="border: 1px red solid; padding:8px; color:red; text-align:center">' .
  144. // '<strong>' . $frontCat . '.' . $page . '.sections.' . $key . '</strong><br>' .
  145. // $e->getMessage() .
  146. // '</div>';
  147. // }
  148. // }
  149. }
  150. return implode('', $divs) . $content . str_repeat('</div>', count($divs));
  151. }
  152. /**
  153. * @param $item
  154. *
  155. * @return array
  156. */
  157. public function getItemData($item): array
  158. {
  159. $result = [];
  160. if (isset($item[ 'data' ]) && count($item[ 'data' ]) > 0) {
  161. foreach ($item[ 'data' ] as $k => $v) {
  162. $result[ 'data-' . str_replace('_', '-', $k) ] = $v;
  163. }
  164. }
  165. return $result;
  166. }
  167. /**
  168. * Retourne le tableau permettant la génération dynamique d'un élément en twig (wrapper, item, container)
  169. *
  170. * Les components doivent être configuré avec les éléments suivants :
  171. *
  172. * mon_component:
  173. * type: mon_type_de_component
  174. * wrapper: <== va gérer une div qui engloble le component
  175. * class: ""
  176. * class: "" <== va gérer la class du component
  177. * container: <== va gérer une div interne au component qui va contenir les sous-éléments du component
  178. * class: ""
  179. *
  180. * <div class="ma-classe-wrapper" + autres éléments dans wrapper>
  181. * <div class="ma-classe" + autres élément>
  182. * <div class="ma-classe-container" + autres éléments dans container>
  183. *
  184. * Cette configuration permet une plus grande souplesse pour organiser les éléments via les class bootstrap
  185. *
  186. * @param array|string $item tableau contenant les données de l'élément, si c'est une string, c'est pour maintenir l'ancien système
  187. * @param string $key clé du data-component-acl pour son identification
  188. * @param bool $debug
  189. *
  190. * @return array tableau contenant les informations
  191. *
  192. * id => si le component doit avoir un id, '' par défaut
  193. * class => class de l'élément, '' par défaut
  194. * data => tableau qui contient tous les éléments data de l'élément et leur valeur (data-foo="bla"), [] par défaut
  195. * tag => le tag de l'élément si c'est précisé, div par défaut
  196. * style => tableau si des éléments doivent être passé dans style (style="background:red"), défaut []
  197. * enabled => Bool pour savoir si l'élément s'affiche ou non, défaut TRUE
  198. * display => tableau qui gère l'affichage par addition ou soustraction sur des pages, défaut []
  199. * univers => uniquement si des datas sont passée dans l'item
  200. */
  201. public function generateDomOption($item, string $key = '', bool $debug = false): array
  202. {
  203. $result = [
  204. 'id' => '',
  205. 'data' => [],
  206. 'tag' => 'div',
  207. 'style' => [],
  208. 'enabled' => true,
  209. 'display' => []
  210. ];
  211. // $item n'est pas un array (ancien système → wrapper correspond à la class)
  212. if (!is_array($item)) {
  213. $result[ 'class' ] = $item;
  214. return $result;
  215. }
  216. $result[ 'class' ] = $this->getClassForItem($item);
  217. $result[ 'id' ] = $item[ 'id' ] ?? $result[ 'id' ];
  218. $result[ 'tag' ] = $item[ 'tag' ] ?? $result[ 'tag' ];
  219. if (isset($item[ 'data' ]) && $item[ 'data' ] !== []) {
  220. $result[ 'data' ] = $this->getItemData($item);
  221. }
  222. if ($key !== '') {
  223. $result[ 'data' ][ 'data-component-acl' ] = $key;
  224. $result[ 'enabled' ] = $item[ 'enabled' ] ?? TRUE;
  225. $result[ 'display' ] = $item[ 'display' ] ?? [];
  226. if (isset($item[ 'univers' ]) && $item[ 'univers' ] !== []) {
  227. $result[ 'univers' ] = $item[ 'univers' ];
  228. }
  229. }
  230. if (isset($item[ 'style' ]) && $item[ 'style' ] !== []) {
  231. foreach ($item[ 'style' ] as $rule => $value) {
  232. $result[ 'style' ][ str_replace('_', '-', $rule) ] = $value;
  233. }
  234. }
  235. return $result;
  236. }
  237. /**
  238. * Génère le tableau permettant la création dynamique d'un atom dans le twig
  239. *
  240. * Pour un atom, c'est la clef wrapper qui va prendre le data-acl-component
  241. *
  242. * @param array|null $atom tableau contenant les data de l'atom TODO gerer un toArray si on passe un objet
  243. * @param string|null $key clé identifiant l'atom pour les ACL
  244. * @param bool $debug
  245. *
  246. * @return array
  247. */
  248. public function generateAtomOptions(?array $atom, ?string $key = '', bool $debug = FALSE): array
  249. {
  250. // wrapper n'existe pas, ou est null, ou n'est pas un tableau
  251. switch (TRUE) {
  252. case !isset($atom[ 'wrapper' ]):
  253. $wrapper = [];
  254. break;
  255. case is_string($atom[ 'wrapper' ]):
  256. $wrapper = [
  257. 'class' => $atom[ 'wrapper' ],
  258. ];
  259. break;
  260. default:
  261. $wrapper = $atom[ 'wrapper' ];
  262. break;
  263. }
  264. $result = array_merge(
  265. [
  266. 'enabled' => $atom[ 'enabled' ] ?? TRUE,
  267. ],
  268. $wrapper,
  269. );
  270. return $this->generateDomOption($result, $key);
  271. }
  272. /**
  273. * @param $component
  274. * @param string|null $key
  275. *
  276. * @return array
  277. */
  278. public function generateComponentOptions($component, ?string $key = '', $debug = false): array
  279. {
  280. $cacheKey = md5(json_encode([$key, $component]));
  281. if (array_key_exists($cacheKey, $this->componentOptionsCache)) {
  282. return $this->componentOptionsCache[$cacheKey];
  283. }
  284. $key = $key ?? '';
  285. // WRAPPER
  286. $wrapperKey = 'wrapper';
  287. $wrapper = isset($component[ $wrapperKey ]) ? $this->generateDomOption($component[ $wrapperKey ], '', $debug) : $this->generateDomOption([], '', $debug);
  288. // ITEM
  289. $item = $this->generateDomOption($component, $key, $debug);
  290. // CONTAINER
  291. $containerKey = 'container';
  292. $container = isset($component[ $containerKey ]) ? $this->generateDomOption($component[ $containerKey ], '', $debug) : $this->generateDomOption([], '', $debug);
  293. return $this->componentOptionsCache[$cacheKey] = [
  294. 'wrapper' => $wrapper,
  295. 'item' => $item,
  296. 'container' => $container,
  297. ];
  298. }
  299. /**
  300. * @param string $keys
  301. * @param array|null $platform
  302. * @param string|null $lastKeyPlatform
  303. *
  304. * @return array|mixed
  305. *
  306. * @throws JsonException
  307. */
  308. public function getFrontDataFromSettingOrYaml(string $keys, ?array $platform, ?string $lastKeyPlatform = NULL)
  309. {
  310. return $this->frontService->getFrontDataFromSettingOrYaml($keys, $platform, $lastKeyPlatform);
  311. }
  312. /**
  313. * TODO Vérifier son utilisation, pour le moment uniquement sur default_progression_status_step.html.twig
  314. *
  315. * @param $atomic_component
  316. *
  317. * @return string
  318. *
  319. * @throws LoaderError
  320. * @throws RuntimeError
  321. * @throws SyntaxError
  322. */
  323. public function customAtomicContent($atomic_component): string
  324. {
  325. $view = $this->resolveComponentView($atomic_component, $this->customAtomicViewCache);
  326. if ($view === null) {
  327. return $atomic_component . ' not found !';
  328. }
  329. return $this->twig->render($view);
  330. }
  331. /**
  332. * @param $component
  333. * @param $keys
  334. * @param $index
  335. *
  336. * @return mixed
  337. */
  338. private function checkComponent($component, &$keys, $index)
  339. {
  340. $platform = $this->params->get('platform');
  341. $value = $platform;
  342. $keys = explode('.', $component);
  343. $i = 1;
  344. foreach ($keys as $key) {
  345. if (!isset($value[ $key ]) &&
  346. !isset($value[ 'global' ][ $key ]) &&
  347. !isset($value[ 'front' ][ $key ]) &&
  348. !isset($value[ 'back_office' ][ $key ])) {
  349. // On affiche l'erreur de key non trouvée que pour les développeurs.
  350. // En prod et pour les autres utilisateurs, on n'affiche rien (une erreur log est générée néanmoins).
  351. /** @var User $currentUser */
  352. $currentUser = $this->security->getUser();
  353. if ($currentUser !== NULL && $currentUser->isDeveloper()) {
  354. return "key '$key' of '$component' does not exist";
  355. }
  356. $this->logger->error("key '$key' of '$component' does not exist");
  357. return '';
  358. }
  359. if (isset($value[ 'global' ][ $key ])) {
  360. $value = $value[ 'global' ][ $key ];
  361. } elseif (isset($value[ 'front' ][ $key ])) {
  362. $value = $value[ 'front' ][ $key ];
  363. } elseif (isset($value[ 'back_office' ][ $key ])) {
  364. $value = $value[ 'back_office' ][ $key ];
  365. } else {
  366. $value = $value[ $key ];
  367. }
  368. // si un index est passé et qu'on est à la dernière clé, on va chercher l'objet à l'index donné.
  369. if (NULL !== $index && $i === count($keys)) {
  370. $value = $value[ $index ];
  371. }
  372. $i++;
  373. }
  374. return $value;
  375. }
  376. /**
  377. * @throws SyntaxError
  378. * @throws RuntimeError
  379. * @throws LoaderError
  380. */
  381. private function buildComponent($value, $keys, $data, $debug = FALSE): string
  382. {
  383. $response = '<div class="text-danger">' . $value[ 'type' ] . ' not found in components !</div>';
  384. /** @var User $currentUser */
  385. $currentUser = $this->security->getUser();
  386. $componentAclFullKey = is_array($keys) ? implode('.', $keys) : $keys;
  387. if (!(isset($value[ 'disabled' ]) && $value[ 'disabled' ] === TRUE)) {
  388. $view = $this->resolveComponentView($value['type'], $this->componentViewCache);
  389. if (isset($view)) {
  390. $response = $this->twig->render($view, [
  391. 'value' => $value,
  392. 'data' => $data,
  393. 'componentKey' => $componentAclFullKey,
  394. ]);
  395. }
  396. }
  397. if (isset($view) && $currentUser !== NULL && $currentUser->isDeveloper()) {
  398. $response = "\n<!-- ***** START component " . $value[ 'type' ] . " : " . $view . " ***** -->\n" .
  399. $response .
  400. "\n<!-- ***** END component " . $value[ 'type' ] . " ***** -->\n";
  401. }
  402. return $response;
  403. }
  404. private function resolveComponentView(string $componentType, array &$cache): ?string
  405. {
  406. if (array_key_exists($componentType, $cache)) {
  407. return $cache[$componentType];
  408. }
  409. $folder = '/templates/platform/component';
  410. $paths = [
  411. 'platform/component/atom/' . $componentType . '.html.twig' => $this->projectDir . $folder . '/atom/' . $componentType . '.html.twig',
  412. 'platform/component/molecule/' . $componentType . '.html.twig' => $this->projectDir . $folder . '/molecule/' . $componentType . '.html.twig',
  413. 'platform/component/organism/' . $componentType . '.html.twig' => $this->projectDir . $folder . '/organism/' . $componentType . '.html.twig',
  414. ];
  415. foreach ($paths as $view => $path) {
  416. if (file_exists($path)) {
  417. return $cache[$componentType] = $view;
  418. }
  419. }
  420. return $cache[$componentType] = null;
  421. }
  422. /**
  423. * @param string $page
  424. * @param string $frontType
  425. *
  426. * @return array
  427. * @throws JsonException
  428. */
  429. private function getContentData(string $page, string $frontType): array
  430. {
  431. $cacheKey = $frontType . ':' . $page;
  432. if (array_key_exists($cacheKey, $this->contentDataCache)) {
  433. return $this->contentDataCache[$cacheKey];
  434. }
  435. if (!in_array($frontType, ['security', 'common', 'content'])) {
  436. $frontType = 'content';
  437. }
  438. // on regarde si on a des données en BDD pour cette page
  439. $fromBdd = $this->frontService->getArrayDataFromSetting('front.' . $frontType . '.' . $page);
  440. if ($fromBdd !== []) {
  441. $pageArray = $fromBdd;
  442. } else {
  443. $platform = $this->params->get('platform');
  444. $pageArray = $platform[ 'front' ][ $frontType ];
  445. }
  446. $testPage = explode('.', $page);
  447. if (count($testPage) > 1) {
  448. foreach ($testPage as $item) {
  449. $pageArray = $pageArray[ $item ];
  450. }
  451. } else {
  452. $pageArray = $pageArray[ $page ];
  453. }
  454. return $this->contentDataCache[$cacheKey] = [
  455. 'pageArray' => $pageArray,
  456. 'frontCat' => $frontType,
  457. 'contentKey' => $frontType . '.' . $page,
  458. ];
  459. }
  460. /**
  461. * Génère les div d'ouverture lorsque content() est appelé
  462. *
  463. * TODO à revoir pour verrouiller
  464. *
  465. * container peut avoir plusieurs valeurs
  466. * - TRUE => on ajoute une div class="container" au debut
  467. * - container => on ajoute une div class="container" au debut
  468. * - container-fluid => on ajoute une div class="container-fluid" au debut
  469. * - fluid => on ajoute une div class="container-fluid" au debut
  470. *
  471. * si la clef row existe et n'est pas FALSE => on rajoute une div class="row" après le container
  472. * si la clef row existe et n'est pas FALSE et que la clef row_justify existe => on rajoute une div class="row [valeur de row_justify]" après le container
  473. *
  474. * @param array $pageArray
  475. *
  476. * @return array
  477. */
  478. private function getContentStartDivs(array $pageArray): array
  479. {
  480. $divs = [];
  481. // 3 cas possibles
  482. // la clef n'existe pas ou est à false → pas de container
  483. if (isset($pageArray[ 'container' ])) {
  484. // si la clef est à true ou "container" → container
  485. if (in_array(
  486. $pageArray[ 'container' ],
  487. [TRUE, 'container'],
  488. TRUE
  489. )) {
  490. $divs[] = '<div class="container">';
  491. // si la clef est à "fluid" ou "container-fluid" => container-fluid
  492. } elseif (in_array(
  493. $pageArray[ 'container' ],
  494. ['container-fluid', 'fluid']
  495. )) {
  496. $divs[] = '<div class="container-fluid">';
  497. }
  498. }
  499. if (
  500. isset($pageArray[ 'row' ])
  501. && $pageArray[ 'row' ] !== FALSE
  502. ) {
  503. $row_justify = $pageArray[ 'row_justify' ] ?? '';
  504. $divs[] = '<div class="row ' . $row_justify . '">';
  505. }
  506. return $divs;
  507. }
  508. private function getClassForItem($item)
  509. {
  510. $allClass = $item[ 'class' ] ?? '';
  511. $allClassArray = explode(' ', $allClass);
  512. $classCatArr = [];
  513. if (isset($item[ 'class_category' ])) {
  514. foreach ($item[ 'class_category' ] as $key => $value) {
  515. $classCatArr[ $key ] = !is_array($value) ? explode(' ', $value) : $value;
  516. }
  517. }
  518. $merged = array_merge($allClassArray, ...array_values($classCatArr));
  519. $allClass = array_unique($merged);
  520. return implode(' ', $allClass);
  521. }
  522. public function urlExist($url): bool
  523. {
  524. stream_context_set_default( [
  525. 'ssl' => [
  526. 'verify_peer' => false,
  527. 'verify_peer_name' => false,
  528. ],
  529. ]);
  530. $headers = get_headers($url);
  531. return (bool)stripos($headers[ 0 ], "200 OK");
  532. }
  533. }