vendor/terminal42/contao-node/src/EventListener/InsertTagsListener.php line 64

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4.  * Node Bundle for Contao Open Source CMS.
  5.  *
  6.  * @copyright  Copyright (c) 2019, terminal42 gmbh
  7.  * @author     terminal42 <https://terminal42.ch>
  8.  * @license    MIT
  9.  */
  10. namespace Terminal42\NodeBundle\EventListener;
  11. use Contao\CoreBundle\Monolog\ContaoContext;
  12. use Contao\Environment;
  13. use Contao\StringUtil;
  14. use Psr\Log\LoggerInterface;
  15. use Terminal42\NodeBundle\NodeManager;
  16. class InsertTagsListener
  17. {
  18.     /**
  19.      * @var NodeManager
  20.      */
  21.     private $manager;
  22.     /**
  23.      * @var LoggerInterface|null
  24.      */
  25.     private $logger;
  26.     /**
  27.      * InsertTagsListener constructor.
  28.      */
  29.     public function __construct(NodeManager $managerLoggerInterface $logger null)
  30.     {
  31.         $this->manager $manager;
  32.         $this->logger $logger;
  33.     }
  34.     /**
  35.      * On replace insert tag.
  36.      *
  37.      * @return string|bool
  38.      */
  39.     public function onReplace(string $tag)
  40.     {
  41.         $chunks explode('::'$tag);
  42.         if ('insert_node' !== $chunks[0] && 'insert_nodes' !== $chunks[0]) {
  43.             return false;
  44.         }
  45.         $ids StringUtil::trimsplit(','$chunks[1]);
  46.         $total = \count($ids);
  47.         if (=== $total) {
  48.             // Let Contao generate an "unknown insert tag" error in the back end
  49.             return false;
  50.         }
  51.         if (=== $total) {
  52.             if (null === $buffer $this->manager->generateSingle((int) $ids[0])) {
  53.                 $this->logError($ids$tag);
  54.             }
  55.             return $buffer;
  56.         }
  57.         $nodes $this->manager->generateMultiple($ids);
  58.         $invalid array_keys(array_diff_key(array_flip($ids), $nodes));
  59.         if (!empty($invalid)) {
  60.             $this->logError($invalid$tag);
  61.         }
  62.         return implode("\n"$nodes);
  63.     }
  64.     private function logError(array $idsstring $tag): void
  65.     {
  66.         if (null === $this->logger) {
  67.             return;
  68.         }
  69.         $this->logger->error(
  70.             'Invalid nodes ('.implode(', '$ids).') in insert tag ('.$tag.') on page ' Environment::get('uri'),
  71.             ['contao' => new ContaoContext(self::class, ContaoContext::ERROR)]
  72.         );
  73.     }
  74. }