<?php
/**
* Description of AppExtension
* Ajout de filtre pour twig
* @author steph
* @source : https://symfony.com/doc/current/templating/twig_extension.html
*/
namespace Acme\SudcmsBundle\Twig;
use Acme\SudcmsBundle\Service\UrlizerService;
use DateTime;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
class AppExtension extends AbstractExtension {
public function getFilters() {
return [
new TwigFilter('urlrewrite', [$this, 'urlRewrite']),
new TwigFilter('html_entity_decode', [$this, 'html_entity_decode']),
new TwigFilter('timeDiff', [$this, 'timeDiff']),
];
}
public function getFunctions() {
return [
new TwigFunction('webp', [$this, 'webp']),
new TwigFunction('modOptions', [$this, 'modOptions']),
new TwigFunction('verifIsIn', [$this, 'verifIsIn']),
new TwigFunction('telephonize', [$this, 'telephonize']),
];
}
public function timeDiff($datetime) {
$datetime1 = new DateTime($datetime);
$datetime2 = new DateTime(date('Y-m-d H:i:s'));
$interval = $datetime2->diff($datetime1);
$nbDays = $interval->format('%d');
$nbHours = $interval->format('%h');
$nbMin = $interval->format('%i');
if ($nbDays > 0) {
return $nbDays . ' jours';
} elseif ($nbHours > 0) {
return $nbHours . 'h';
} elseif ($nbMin == 0) {
return 'moins d\'une minute';
} else {
return $nbMin . 'min';
}
}
public function urlRewrite($string) {
$urlizer = new UrlizerService();
return $urlizer->urlize($string);
}
public function html_entity_decode($string) {
return html_entity_decode($string, ENT_QUOTES);
}
public function webp($webpSupported, $media_file) {
if ($webpSupported) {
$media_file = str_replace(['.png', '.jpg', '.jpeg', '.gif'], '.webp', $media_file);
}
return $media_file;
}
public function modOptions($optionsModule) {
$listeModOpt = [];
$cmptOpt = 0;
foreach ($optionsModule as $key => $modOpt) {
$listeModOpt[$modOpt->getOptionCodeInterne()] = $modOpt->getOptionValue();
$cmptOpt++;
}
return $listeModOpt;
}
public function verifIsIn($is, $array) {
$return = 0;
$tabVerif = explode(",", $array);
foreach ($tabVerif as $taVe) {
if ($taVe == $is) {
$return = 1;
}
}
return $return;
}
public function telephonize($number) {
if ($number) {
$number = str_replace(" ", "", $number);
$number = str_replace(".", "", $number);
$number = str_replace("/", "", $number);
$number = str_replace("-", "", $number);
$number = substr($number, 1);
$number = "+33" . $number;
}
return $number;
}
}