src/Twig/Runtime/PlatformComponentRuntime.php line 441

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