vendor/conecto/pimcore-provider/src/ProviderBundle/Twig/Extension/ConectoExtension.php line 136

Open in your IDE?
  1. <?php
  2. namespace CONECTO\ProviderBundle\Twig\Extension;
  3. use Pimcore\Config;
  4. use Pimcore\Model\Asset;
  5. use Pimcore\Model\Document;
  6. use Pimcore\Navigation\Container;
  7. use Pimcore\Navigation\Builder;
  8. use Symfony\Component\Intl\Countries;
  9. use Twig\Extension\AbstractExtension;
  10. use Twig\TwigFunction;
  11. final class ConectoExtension extends AbstractExtension
  12. {
  13.     /**
  14.      * @var Builder
  15.      */
  16.     private $navigationHelper;
  17.     /**
  18.      * @param Builder $navigationHelper
  19.      */
  20.     public function __construct(Builder $navigationHelper)
  21.     {
  22.         $this->navigationHelper $navigationHelper;
  23.     }
  24.     /**
  25.      * @return \Twig_Function[]
  26.      */
  27.     public function getFunctions(): array
  28.     {
  29.         return [
  30.             new TwigFunction('date_string', [$this'getDate']),
  31.             new TwigFunction('date_in_days', [$this'getDateInDays']),
  32.             new TwigFunction('conecto_country_list', [$this'buildCountryList']),
  33.             new TwigFunction('conecto_file_get_contents', [$this'fileGetContents']),
  34.             new TwigFunction('conecto_build_nav', [$this'buildMainNavigation']),
  35.             new TwigFunction('conecto_get_editable', [$this'getEditable']),
  36.             new TwigFunction('conecto_get_parent_editable', [$this'getParentEditable']),
  37.             new TwigFunction('conecto_get_icons', [$this'getIcons']),
  38.             new TwigFunction('conecto_get_areabricks', [$this'getAreaBricks']),
  39.             new TwigFunction('conecto_get_thumbnailconf', [$this'getThumbnailConf']),
  40.             new TwigFunction('conecto_get_hostname', [$this'getHostname']),
  41.             new TwigFunction('conecto_video_from_dataobject', [$this'videoFromDataobject']),
  42.             new TwigFunction('include_svg', [$this'includeSvg']),
  43.         ];
  44.     }
  45.     /**
  46.      * @return string
  47.      */
  48.     public function getDate(): string
  49.     {
  50.         $date = new \DateTimeImmutable();
  51.         return $date->format('Y-m-d');
  52.     }
  53.     /**
  54.      * @param int $days
  55.      * @return string
  56.      */
  57.     public function getDateInDays(int $days 1): string
  58.     {
  59.         $date = new \DateTime();
  60.         $date->add(new \DateInterval('P'.$days.'D'));
  61.         return $date->format('Y-m-d');
  62.     }
  63.     /**
  64.      * @param $locale
  65.      * @return mixed
  66.      */
  67.     public function buildCountryList($locale)
  68.     {
  69.         return Countries::getNames($locale);
  70.     }
  71.     /**
  72.      * @param string $path
  73.      * @return string
  74.      */
  75.     public function fileGetContents(string $path)
  76.     {
  77.         $fileContent '';
  78.         if(file_exists(PIMCORE_WEB_ROOT '/' $path)) {
  79.             $fileContent file_get_contents(PIMCORE_WEB_ROOT '/' $path);
  80.         }
  81.         return $fileContent;
  82.     }
  83.     /**
  84.      * @param Document $activeDocument
  85.      * @param Document $navigationRootDocument
  86.      * @return Container
  87.      */
  88.     public function buildMainNavigation(Document $activeDocumentDocument $navigationRootDocument): Container
  89.     {
  90.         return $this->navigationHelper->getNavigation(
  91.             $activeDocument,
  92.             $navigationRootDocument,
  93.             null,
  94.             function (\Pimcore\Navigation\Page\Document $page$doc) {
  95.                 if (!$doc instanceof Document) {
  96.                     return;
  97.                 }
  98.                 // Add Document as Custom Setting to access Document Properties in Nav
  99.                 $page->setCustomSetting("document"$doc);
  100.                 return $page;
  101.             }
  102.         );
  103.     }
  104.     /**
  105.      * @param Document $document
  106.      * @param string $editableName
  107.      * @return mixed
  108.      */
  109.     public function getEditable(Document $documentstring $editableName)
  110.     {
  111.         return $document->getEditable($editableName);
  112.     }
  113.     /**
  114.      * @param Document $document
  115.      * @param string $editableName
  116.      * @return mixed
  117.      */
  118.     public function getParentEditable(Document $documentstring $editableName)
  119.     {
  120.         $parent $document->getParent();
  121.         if($parent) {
  122.             if( method_exists($parent'getEditable') ) {
  123.                 $parentEditable $parent->getEditable($editableName);
  124.                 if((
  125.                     $parentEditable instanceof \Pimcore\Model\Document\Editable\Image
  126.                     || $parentEditable instanceof \Pimcore\Model\Document\Editable\Video
  127.                     ) && $parentEditable->getId() > 0
  128.                 ) {
  129.                     return $parentEditable;
  130.                 }
  131.             }
  132.             return $this->getParentEditable($parent$editableName);
  133.         }
  134.         return null;
  135.     }
  136.     /**
  137.      * @return array
  138.      */
  139.     public function getIcons(): array
  140.     {
  141.         return \CONECTO\ProviderBundle\Utility\Icon::getIconData();
  142.     }
  143.     /**
  144.      * Function to automatically get all available area bricks,
  145.      * because this is needed in different templates.
  146.      * Use "disallowed" parameter to remove specific area bricks
  147.      * from the list.
  148.      * The sorting of the area bricks can be defined in the
  149.      * config php files of the area bricks
  150.      *
  151.      * @param array $disallowed disallowed areabricks to remove from list
  152.      * @param array $additional additional areabricks to add to list
  153.      * @return array
  154.      */
  155.     public function getAreabricks(array $disallowed = [], array $additional = []): array
  156.     {
  157.         $areaBricksDirs = [];
  158.         $areaBricksDirs[] = __DIR__ '/../../Document/Areabrick/';
  159.         $areaBricksDirs[] = PIMCORE_PROJECT_ROOT '/src/Document/Areabrick/';
  160.         $areaBricks = [];
  161.         if(sizeof($areaBricksDirs) > 0) {
  162.             foreach($areaBricksDirs as $areaBricksDir) {
  163.                 if(is_dir($areaBricksDir)) {
  164.                     $areaBricksFilenames array_diff(scandir($areaBricksDir), ['.''..''AbstractAreabrick.php']);
  165.                     // Get sorting from AreaBrick php file
  166.                     foreach($areaBricksFilenames as $filename) {
  167.                         $customSorting 9999;
  168.                         if(file_exists($areaBricksDir $filename)) {
  169.                             $fileContent = @file_get_contents($areaBricksDir $filename);
  170.                             if($fileContent) {
  171.                                 $lines explode(PHP_EOL$fileContent);
  172.                                 $lines array_map(function($line) {
  173.                                     return trim($line);
  174.                                 }, $lines);
  175.                                 $sortingCommentStart '/* custom-sorting:';
  176.                                 foreach ($lines as $index => $line) {
  177.                                     if (strpos($line$sortingCommentStart) !== false) {
  178.                                         $customSorting trim(str_replace([$sortingCommentStart"*/"], ''$line));
  179.                                         break;
  180.                                     }
  181.                                 }
  182.                             }
  183.                         }
  184.                         $areaBricks[] = [
  185.                             'sorting' => $customSorting,
  186.                             'name' => strtolower(preg_replace('/([a-zA-Z])(?=[A-Z])/''$1-'str_replace('.php'''$filename))),
  187.                         ];
  188.                     }
  189.                 }
  190.             }
  191.         }
  192.         if($additional && sizeof($additional)) {
  193.             foreach($additional as $areaBrick) {
  194.                 $areaBricks[] = [
  195.                     'sorting' => 999999,
  196.                     'name' => $areaBrick,
  197.                 ];
  198.             }
  199.         }
  200.         uasort($areaBricks, function($a$b) {
  201.             return $a['sorting'] - $b['sorting'];
  202.         });
  203.         return sizeof($disallowed) > array_diff(array_column($areaBricks'name'), $disallowed) : array_column($areaBricks'name');
  204.     }
  205.     /**
  206.      * Get dynamic thumbnail conf
  207.      *
  208.      * @param string $name name for thumbnail conf
  209.      * @param float $ratio thumbnail ratio - defaults to 3/2
  210.      * @param float $cols cols to calculate image width - defaults to 1
  211.      * @param int $baseWidth base content width
  212.      * @return \Pimcore\Model\Asset\Image\Thumbnail\Config
  213.      */
  214.     public function getThumbnailConf(string $name 'default'float $ratio 1.5float $cols 1int $baseWidth 1920): \Pimcore\Model\Asset\Image\Thumbnail\Config
  215.     {
  216.         // thumbnail conf
  217.         $minWidth 380;
  218.         $minHeight floor($minWidth $ratio);
  219.         $breakpoints = [
  220.             [
  221.                 'minWidth' => 576,
  222.                 'imgWidth' => 767,
  223.                 'maxCols' => 2
  224.             ],
  225.             [
  226.                 'minWidth' => 768,
  227.                 'imgWidth' => 991,
  228.                 'maxCols' => 3
  229.             ],
  230.             [
  231.                 'minWidth' => 992,
  232.                 'imgWidth' => 1199,
  233.                 'maxCols' => 4
  234.             ],
  235.             [
  236.                 'minWidth' => 1200,
  237.                 'imgWidth' => $baseWidth,
  238.                 'maxCols' => 6
  239.             ]
  240.         ];
  241.         $medias = [];
  242.         $confName $name '_' str_replace('.''-'round($ratio2)) . '_' str_replace('.''-'round($cols2));
  243.         $conf = new \Pimcore\Model\Asset\Image\Thumbnail\Config();
  244.         $conf->setName($confName);
  245.         $conf->setFormat('SOURCE');
  246.         $conf->setQuality(85);
  247.         $conf->setHighResolution(1);
  248.         $conf->setPreserveColor(false);
  249.         $conf->setPreserveMetaData(false);
  250.         $conf->setRasterizeSVG(false);
  251.         $conf->setDownloadable(false);
  252.         // Default size (smartphones)
  253.         $conf->addItem('cover', [
  254.                 "width" => $minWidth,
  255.                 "height" => $minHeight,
  256.                 "positioning" => "center",
  257.                 "forceResize" => true
  258.         ]);
  259.         // add Media queries
  260.         for($i 0$i sizeof($breakpoints); $i++) {
  261.             $maxThumbWidth $breakpoints[$i]['imgWidth'];
  262.             $tmpCols $cols $breakpoints[$i]['maxCols'] ? $breakpoints[$i]['maxCols'] : $cols;
  263.             $thumbWidth floor($maxThumbWidth $tmpCols);
  264.             $thumbHeight floor($thumbWidth $ratio);
  265.             $mediaQuery "(min-width: " $breakpoints[$i]['minWidth'] . "px)";
  266.             if(isset($breakpoints[$i 1]) && is_array($breakpoints[$i 1])) {
  267.                 $mediaQuery .= "and (max-width: " $breakpoints[$i 1]['minWidth'] . "px)";
  268.             }
  269.             $medias[$mediaQuery][] = [
  270.                 "method" => "cover",
  271.                 "arguments" => [
  272.                     "width" => $thumbWidth,
  273.                     "height" => $thumbHeight,
  274.                     "positioning" => "center",
  275.                     "forceResize" => true
  276.                 ]
  277.             ];
  278.         }
  279.         $conf->setMedias($medias);
  280.         return $conf;
  281.     }
  282.     /**
  283.      * Gets Hostname
  284.      *
  285.      * @return string
  286.      */
  287.     public function getHostname(): string
  288.     {
  289.         return \Pimcore\Tool::getRequestScheme() . '://' \Pimcore\Tool::getHostname();
  290.     }
  291.     /**
  292.      * Renders a Pimcore Video from a Data Object using document's video tag
  293.      *
  294.      * @param \Pimcore\Model\DataObject\Data\Video $video
  295.      * @param array $config
  296.      * @return string
  297.      */
  298.     public function videoFromDataobject(\Pimcore\Model\DataObject\Data\Video $video, array $config = []): void
  299.     {
  300.         $videoData $video->getData();
  301.         if($videoData) {
  302.             $videoEditable = new \Pimcore\Model\Document\Editable\Video();
  303.             // if no video thumb conf given, set default one
  304.             $thumbnailConf = new \Pimcore\Model\Asset\Video\Thumbnail\Config();
  305.             $thumbnailConf->setName('default');
  306.             if(!isset($config['thumbnail']) || !$config['thumbnail']) {
  307.                 $config['thumbnail'] = $thumbnailConf;
  308.             }
  309.             $videoEditable->setConfig($config);
  310.             // set data from data object
  311.             $videoEditable->setDataFromResource([
  312.                 'type' => $video->getType(),
  313.                 'id' => ($videoData instanceof Asset) ? $videoData->getId() : $videoData,
  314.                 'title' => $video->getTitle(),
  315.                 'description' => $video->getDescription(),
  316.                 'poster' => ($video->getPoster() ? $video->getPoster()->getId() : '')
  317.             ]);
  318.             echo $videoEditable->frontend();
  319.         }
  320.     }
  321.     /**
  322.      * @param string $icon
  323.      * @param bool $inline
  324.      * @param bool $asData
  325.      * @return string
  326.      */
  327.     public function includeSvg(string $iconbool $inline falsebool $asData false): string
  328.     {
  329.         $svgPaths = [
  330.             PIMCORE_WEB_ROOT '/static/images/layout/svg/',
  331.             PIMCORE_WEB_ROOT '/static/images/icons/'
  332.         ];
  333.         $iconPath null;
  334.         foreach ($svgPaths as $path) {
  335.             if(file_exists($path$icon '.svg')) {
  336.                 $iconPath $path$icon '.svg';
  337.                 break;
  338.             }
  339.         }
  340.         if(!$iconPath) {
  341.             return '';
  342.         }
  343.         $svg '';
  344.         if( $inline || $asData ) {
  345.             $svg file_get_contents($iconPath);
  346.             if( $asData ) {
  347.                 $svg urlencode($svg);
  348.             } else {
  349.                 $svg str_replace(PIMCORE_WEB_ROOT''$svg);
  350.             }
  351.             if( !$inline || $asData ) {
  352.                 $svg '<img src="data:image/svg+xml;base64,' base64_encode($svg) . '" />';
  353.             }
  354.         }
  355.         return $svg ?? '';
  356.     }
  357. }