<?php
declare(strict_types=1);
namespace App\Twig;
use Sylius\Component\Core\Repository\PromotionRepositoryInterface;
use Sylius\Component\Registry\ServiceRegistryInterface;
use App\Entity\Customer\Customer;
use App\Services\ShippingService;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use Symfony\Component\DependencyInjection\ContainerInterface;
// use Sylius\Component\Core\Repository\ProductVariantRepositoryInterface;
// use Doctrine\ORM\EntityManager;
use Doctrine\Persistence\ManagerRegistry;
use App\Entity\SitePageCMSTranslation;
use App\Entity\SiteCollectionTranslation;
final class TwigExtension extends AbstractExtension {
private const FREE_DELIVERY_PROMOTION_CODE_PREFIX = 'FREE_DELIVERY';
private const CARTE_KDO_CODE = 'CART.CAD.WEB.AUTRE';
private $shippingService;
private $promotionRepository;
public function __construct(
ShippingService $shippingService,
PromotionRepositoryInterface $promotionRepository,
ContainerInterface $container,
ManagerRegistry $doctrine
// ProductVariantRepositoryInterface $productVariantRepository,
// EntityManager $entityManager
// ServiceRegistryInterface $ruleRegistry
) {
$this->shippingService = $shippingService;
$this->promotionRepository = $promotionRepository;
$this->container = $container;
// $this->productVariantRepository = $productVariantRepository;
$this->doctrine = $doctrine;
}
public function getFunctions(): array
{
return [
new TwigFunction('app_shipping_estimate_start_date', [$this->shippingService, 'getEstimateStartDate']),
new TwigFunction('app_shipping_estimate_end_date', [$this->shippingService, 'getEstimateEndDate']),
new TwigFunction('app_fidelity_points_earned_from_last_12_month', [$this, 'getFidelityPointsEarnedFromLast12Month']),
new TwigFunction('app_getpromotion', [$this, 'displayPromotion']),
new TwigFunction('app_collection_look_link', [$this, 'displayLookLink']),
new TwigFunction('app_product_accessoires', [$this, 'isAccessoryInCart']),
// new TwigFunction('app_user_boutique', [$this, 'displayUserBoutique']),
new TwigFunction('app_last_product_variants_viewed', [$this, 'getLastProductVariantsViewed']),
new TwigFunction('app_guide_level2', [$this, 'getGuideContent']),
new TwigFunction('app_encode_filtre', [$this, 'getEncodeFiltre']),
new TwigFunction('app_is_shipping_free', [$this, 'isShippingFree']),
new TwigFunction('app_show_delivery', [$this, 'showDelivery']),
new TwigFunction('app_has_delivery', [$this, 'hasDelivery']),
new TwigFunction('app_empty_address', [$this, 'isEmptyAddress']),
new TwigFunction('encrypt_sha_256', [$this, 'encryptSha256']),
new TwigFunction('app_show_cadeau', [$this, 'showCadeau']),
new TwigFunction('app_has_cadeau', [$this, 'hasCadeau']),
new TwigFunction('app_is_available_payment', [$this, 'isAvailablePayment']),
new TwigFunction('app_get_localurl', [$this, 'switchLanguage']),
new TwigFunction('app_percentage_promo', [$this, 'getPromoPercentage']),
new TwigFunction('app_hreflang', [$this, 'getHreflang']),
new TwigFunction('app_show_free_shipping', [$this, 'showFreeShipping']),
new TwigFunction('app_has_return_colissimo', [$this, 'hasReturnColissimo']),
];
}
public function getFidelityPointsEarnedFromLast12Month(Customer $customer): int
{
return 0;
}
public function isShippingFree(int $shippingMethodID)
{
$promotions = $this->promotionRepository->findActive();
$cart = $this->container->get('sylius.context.cart')->getCart();
foreach ($promotions as $promotion) {
if (str_contains($promotion->getCode(), self::FREE_DELIVERY_PROMOTION_CODE_PREFIX)) {
if (!$promotion->hasRules()) {
continue;
}
$response = true;
foreach ($promotion->getRules() as $rule) {
if($rule->getType() != "shipping_method") {
$checker = $this->container->get('sylius.promotion_rule_checker.'.$rule->getType());
if (!$checker->isEligible($cart, $rule->getConfiguration())) {
$response = false;
}
}
else {
$hasShipping = false;
foreach($rule->getConfiguration()['shipping_method'] as $shippingMethod) {
if($shippingMethod->getId() == $shippingMethodID){
$hasShipping = true;
}
}
if($hasShipping && $response) {
return true;
}
}
}
}
}
return false;
}
public function showFreeShipping()
{
$cart = $this->container->get('sylius.context.cart')->getCart();
$shippingMethodsResolver = $this->container->get('sylius.shipping_methods_resolver');
if(!empty($cart->getShipments()) && !empty($cart->getShipments()[0])) {
foreach ($shippingMethodsResolver->getSupportedMethods($cart->getShipments()[0]) as $availableShippingMethod) {
if($availableShippingMethod->getConfiguration()['ppmc']['amount'] == 0) {
return true;
}
}
}
return false;
}
public function showDelivery() {
//On vérifie si on a que des cartes cadeaux, auquel cas on affiche pas de mode de livraison
$cart = $this->container->get('sylius.context.cart')->getCart();
$showDelivery = false;
foreach($cart->getItems() as $item){
if($item->getVariant()->getCode() != self::CARTE_KDO_CODE){
$showDelivery = true;
break;
}
}
return $showDelivery;
}
public function hasDelivery() {
//On vérifie si on a que des cartes cadeaux, auquel cas on affiche pas de mode de livraison
$cart = $this->container->get('sylius.context.cart')->getCart();
return $cart->getShipments()->first();
}
public function isEmptyAddress() {
$user = $this->container->get('security.token_storage')->getToken()->getUser();
// dump($user->getCustomer()->getDefaultAddress()->getId());
if(empty($user->getCustomer()->getDefaultAddress())){
return true;
}
return false;
}
public function showCadeau() {
$showCadeau = false;
$availablePaymentsMethods = $this->container->get('sylius.repository.payment_method')->findBy(['enabled' => true]);
foreach($availablePaymentsMethods as $availablePaymentsMethod) {
if($availablePaymentsMethod->getCode() == 'KDO') {
$showCadeau = true;
break;
}
}
return $showCadeau;
}
public function hasCadeau() {
$cart = $this->container->get('sylius.context.cart')->getCart();
$hasCarteKdo = false;
dump($cart->getPayments());
foreach($cart->getPayments() as $payment) {
$details = $payment->getDetails();
if(array_key_exists('giftCardCode', $details)) {
$hasCarteKdo = true;
}
}
return $hasCarteKdo;
}
public function encryptSha256($data) {
return hash('sha256', $data);
}
public function isAvailablePayment($code) {
// dump($code);
// app.session.get('admin_impersonate_shop_user_id') == app.user.id
$session = $this->container->get('session')->get('admin_impersonate_shop_user_id');
$cart = $this->container->get('sylius.context.cart')->getCart();
$availablePaymentMethods = $this->container->get('sylius.repository.payment_method')->findBy(['enabled' => true]);
$hasCarteKdo = false;
foreach($cart->getPayments() as $payment) {
$details = $payment->getDetails();
if(array_key_exists('giftCardCode', $details)) {
$hasCarteKdo = true;
}
}
$reallyAvailablePaymentMethods = [];
foreach($availablePaymentMethods as $availablePaymentMethod) {
if($availablePaymentMethod->getCode() != 'KDO') {
$reallyAvailablePaymentMethods[] = $availablePaymentMethod->getCode();
}
}
// app.session.get('admin_impersonate_shop_user_id') == app.user.id
if($hasCarteKdo) {
if (($key = array_search('VIR', $reallyAvailablePaymentMethods)) !== false) {
unset($reallyAvailablePaymentMethods[$key]);
}
if (($key = array_search('CHQ', $reallyAvailablePaymentMethods)) !== false) {
unset($reallyAvailablePaymentMethods[$key]);
}
}
if($session == null) {
if (($key = array_search('TPE_CB', $reallyAvailablePaymentMethods)) !== false) {
unset($reallyAvailablePaymentMethods[$key]);
}
if (($key = array_search('HIPAY_LINK', $reallyAvailablePaymentMethods)) !== false) {
unset($reallyAvailablePaymentMethods[$key]);
}
}
if($cart->getTotal() < 5000) {
if (($key = array_search('HIPAY_ALMA', $reallyAvailablePaymentMethods)) !== false) {
unset($reallyAvailablePaymentMethods[$key]);
}
}
// dump($cart->getTotal());
return in_array($code, $reallyAvailablePaymentMethods);
}
public function displayPromotion($product)
{
$active = 0;
$quantity2 = $this->container->get('sylius.repository.promotion')->findOneByCode('2quantity');
if($quantity2){
$quantity2 = $quantity2->getRules();
foreach($quantity2 as $cdt){
foreach($cdt->getConfiguration() as $key => $product_promo){
if($key == 'product_code' && $product_promo == $product->getCode()){
$active = 1;
}
}
if($active == 1){
foreach($cdt->getPromotion()->getActions() as $action){
if($action->getType() == "unit_percentage_discount"){
foreach($action->getConfiguration() as $config){
// $percentage = $config['percentage'];
// $price = $product->getCurrentPrice();
return $cdt->getPromotion()->getName();
}
}
}
}
}
}
return;
}
public function displayLookLink($id)
{
$repository = $this->container->get('sylius.repository.taxon');
$taxon = $repository->find($id);
if($taxon){
return $taxon->getSlug();
}
return 'aa';
}
public function isAccessoryInCart($product): int
{
$cart = $this->container->get('sylius.context.cart')->getCart();
foreach($cart->getItems() as $item){
if($product->getId() == $item->getProduct()->getId()){
return 1;
}
}
return 0;
}
// public function displayUserBoutique(): string
// {
// $user = $this->container->get('security.token_storage')->getToken()->getUser();
// if($user->getCustomer()->getFavoriteShop()){
// return $user->getCustomer()->getFavoriteShop()->getName();
// }
// return '';
// }
/**
* Récupère les dernières déclinaisons produit
*/
public function getLastProductVariantsViewed(int $limit = 16): array
{
// Récupère les dernières déclinaisons de produits consultées
$lastViewedProductVariantsIds = $this->container->get('session')->get('lastViewedProductVariantsIds', []);
if (count($lastViewedProductVariantsIds) <= 0) {
return [];
}
$lastViewedProductVariants = $this->container->get('sylius.repository.product_variant')
->createQueryBuilder('p')
->where('p.id IN (:ids)')
->andWhere('p.enabled = 1')
->setParameter('ids', $lastViewedProductVariantsIds)
->setMaxResults($limit)
->getQuery()
->getResult();
return $lastViewedProductVariants;
}
/**
* Récupère le dernier article d'une sous catégorie du guide
*/
public function getGuideContent($slug): array
{
$content = array();
$repository = $this->container->get('sylius.repository.taxon');
$taxon = $repository->findOneBySlug($slug, $this->container->get('sylius.context.locale')->getLocaleCode()); // Get one taxonomy by defined criteria.
$content['taxon'] = $taxon;
$taxonsChilds = $repository->findChildren($taxon->getCode());
if(is_array($taxonsChilds) && count($taxonsChilds) > 0){
foreach($taxonsChilds as $souscategorie){
$souscategories[$souscategorie->getId()] = $souscategorie;
$content['souscategories'] = $souscategories;
if($taxon->getParent()->getCode() != 'leguide'){
$content['souscategorieslast'] = 1;
krsort($souscategories);
$content['articles'] = $souscategories;
$content['article'] = array_slice($souscategories, 0, 1);
}else{
$content['souscategorieslast'] = 0;
$taxonsChilds2 = $repository->findChildren($souscategorie->getCode());
if(is_array($taxonsChilds2) && count($taxonsChilds2) > 0){
foreach($taxonsChilds2 as $article){
$articles[$article->getId()] = $article;
}
krsort($articles);
$content['articles'] = $articles;
$content['article'] = array_slice($articles, 0, 1);
}
}
$content['souscategories'] = array();
$souscategoriessamelevel = $taxon->getParent();
$taxonsChilds2 = $repository->findChildren($souscategoriessamelevel->getCode());
if(is_array($taxonsChilds2) && count($taxonsChilds2) > 0){
foreach($taxonsChilds2 as $souscat){
$content['souscategories'][] = $souscat;
}
}
}
}else{
if($taxon->getParent()->getCode() != 'leguide'){
$content['souscategorieslast'] = 1;
$souscategoriessamelevel = $taxon->getParent();
$taxonsChilds2 = $repository->findChildren($souscategoriessamelevel->getCode());
if(is_array($taxonsChilds2) && count($taxonsChilds2) > 0){
foreach($taxonsChilds2 as $souscat){
$content['souscategories'][] = $souscat;
}
}
}
}
return $content;
}
public function switchLanguage() {
$actual_link = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
dump($actual_link );
return '';
}
public function getEncodeFiltre($filtre)
{
// dump($filtre);
return $this->replaceSpecialChar(strtolower($filtre));
}
function replaceSpecialChar($str) {
$ch0 = array(
"œ"=>"oe",
"Œ"=>"OE",
"æ"=>"ae",
"Æ"=>"AE",
"À" => "A",
"Á" => "A",
"Â" => "A",
"à" => "A",
"Ä" => "A",
"Å" => "A",
"Ā" => "A",
"Ă" => "A",
"Ǎ" => "A",
"Ạ" => "A",
"Ả" => "A",
"Ấ" => "A",
"Ầ" => "A",
"Ẩ" => "A",
"Ẫ" => "A",
"Ậ" => "A",
"Ắ" => "A",
"Ằ" => "A",
"Ẳ" => "A",
"Ẵ" => "A",
"Ặ" => "A",
"Ǻ" => "A",
"Ą" => "A",
"à" => "a",
"á" => "a",
"â" => "a",
"à" => "a",
"ä" => "a",
"å" => "a",
"ā" => "a",
"ă" => "a",
"ǎ" => "a",
"ạ" => "a",
"ả" => "a",
"ấ" => "a",
"ầ" => "a",
"ẩ" => "a",
"ẫ" => "a",
"ậ" => "a",
"ắ" => "a",
"ằ" => "a",
"ẳ" => "a",
"ẵ" => "a",
"ặ" => "a",
"ǻ" => "a",
"ą" => "a",
"Ç" => "C",
"Ć" => "C",
"Ĉ" => "C",
"Ċ" => "C",
"Č" => "C",
"ç" => "c",
"ć" => "c",
"ĉ" => "c",
"ċ" => "c",
"č" => "c",
"Ð" => "D",
"Ď" => "D",
"Đ" => "D",
"ď" => "d",
"đ" => "d",
"È" => "E",
"É" => "E",
"Ê" => "E",
"Ë" => "E",
"Ē" => "E",
"Ĕ" => "E",
"Ė" => "E",
"Ę" => "E",
"Ě" => "E",
"Ẹ" => "E",
"Ẻ" => "E",
"Ẽ" => "E",
"Ế" => "E",
"Ề" => "E",
"Ể" => "E",
"Ễ" => "E",
"Ệ" => "E",
"è" => "e",
"é" => "e",
"ê" => "e",
"ë" => "e",
"ē" => "e",
"ĕ" => "e",
"ė" => "e",
"ę" => "e",
"ě" => "e",
"ẹ" => "e",
"ẻ" => "e",
"ẽ" => "e",
"ế" => "e",
"ề" => "e",
"ể" => "e",
"ễ" => "e",
"ệ" => "e",
"Ĝ" => "G",
"Ğ" => "G",
"Ġ" => "G",
"Ģ" => "G",
"ĝ" => "g",
"ğ" => "g",
"ġ" => "g",
"ģ" => "g",
"Ĥ" => "H",
"Ħ" => "H",
"ĥ" => "h",
"ħ" => "h",
"Ì" => "I",
"Í" => "I",
"Î" => "I",
"Ï" => "I",
"Ĩ" => "I",
"Ī" => "I",
"Ĭ" => "I",
"Į" => "I",
"İ" => "I",
"Ǐ" => "I",
"Ỉ" => "I",
"Ị" => "I",
"Ĵ" => "J",
"ĵ" => "j",
"Ķ" => "K",
"ķ" => "k",
"Ĺ" => "L",
"Ļ" => "L",
"Ľ" => "L",
"Ŀ" => "L",
"Ł" => "L",
"ĺ" => "l",
"ļ" => "l",
"ľ" => "l",
"ŀ" => "l",
"ł" => "l",
"Ñ" => "N",
"Ń" => "N",
"Ņ" => "N",
"Ň" => "N",
"ñ" => "n",
"ń" => "n",
"ņ" => "n",
"ň" => "n",
"ʼn" => "n",
"Ò" => "O",
"Ó" => "O",
"Ô" => "O",
"Õ" => "O",
"Ö" => "O",
"Ø" => "O",
"Ō" => "O",
"Ŏ" => "O",
"Ő" => "O",
"Ơ" => "O",
"Ǒ" => "O",
"Ǿ" => "O",
"Ọ" => "O",
"Ỏ" => "O",
"Ố" => "O",
"Ồ" => "O",
"Ổ" => "O",
"Ỗ" => "O",
"Ộ" => "O",
"Ớ" => "O",
"Ờ" => "O",
"Ở" => "O",
"Ỡ" => "O",
"Ợ" => "O",
"ò" => "o",
"ó" => "o",
"ô" => "o",
"õ" => "o",
"ö" => "o",
"ø" => "o",
"ō" => "o",
"ŏ" => "o",
"ő" => "o",
"ơ" => "o",
"ǒ" => "o",
"ǿ" => "o",
"ọ" => "o",
"ỏ" => "o",
"ố" => "o",
"ồ" => "o",
"ổ" => "o",
"ỗ" => "o",
"ộ" => "o",
"ớ" => "o",
"ờ" => "o",
"ở" => "o",
"ỡ" => "o",
"ợ" => "o",
"ð" => "o",
"Ŕ" => "R",
"Ŗ" => "R",
"Ř" => "R",
"ŕ" => "r",
"ŗ" => "r",
"ř" => "r",
"Ś" => "S",
"Ŝ" => "S",
"Ş" => "S",
"ś" => "s",
"ŝ" => "s",
"ş" => "s",
"Ţ" => "T",
"Ť" => "T",
"Ŧ" => "T",
"ţ" => "t",
"ť" => "t",
"ŧ" => "t",
"Ù" => "U",
"Ú" => "U",
"Û" => "U",
"Ü" => "U",
"Ũ" => "U",
"Ū" => "U",
"Ŭ" => "U",
"Ů" => "U",
"Ű" => "U",
"Ų" => "U",
"Ư" => "U",
"Ǔ" => "U",
"Ǖ" => "U",
"Ǘ" => "U",
"Ǚ" => "U",
"Ǜ" => "U",
"Ụ" => "U",
"Ủ" => "U",
"Ứ" => "U",
"Ừ" => "U",
"Ử" => "U",
"Ữ" => "U",
"Ự" => "U",
"ù" => "u",
"ú" => "u",
"û" => "u",
"ü" => "u",
"ũ" => "u",
"ū" => "u",
"ŭ" => "u",
"ů" => "u",
"ű" => "u",
"ų" => "u",
"ư" => "u",
"ǔ" => "u",
"ǖ" => "u",
"ǘ" => "u",
"ǚ" => "u",
"ǜ" => "u",
"ụ" => "u",
"ủ" => "u",
"ứ" => "u",
"ừ" => "u",
"ử" => "u",
"ữ" => "u",
"ự" => "u",
"Ŵ" => "W",
"Ẁ" => "W",
"Ẃ" => "W",
"Ẅ" => "W",
"ŵ" => "w",
"ẁ" => "w",
"ẃ" => "w",
"ẅ" => "w",
"Ý" => "Y",
"Ŷ" => "Y",
"?" => "Y",
"Ỳ" => "Y",
"Ỹ" => "Y",
"Ỷ" => "Y",
"Ỵ" => "Y",
"ý" => "y",
"ÿ" => "y",
"ŷ" => "y",
"ỹ" => "y",
"ỵ" => "y",
"ỷ" => "y",
"ỳ" => "y",
"Ź" => "Z",
"Ż" => "Z",
'+' =>'',
"'" =>'',
' ' =>'-',
'.' =>'-',
);
$str = strtr($str,$ch0);
return $str;
}
function getPromoPercentage($price, $originalPrice){
// dump($price);
// dump($originalPrice);
// dump($product->getProduct()->getPriceOriginal());
// $productVariantRepo = $this->container->get('sylius.repository.product_variant');
// $productVariantRepo::hasDiscount($product);
// return 100 - (($price) * $originalPrice / 100);
return '- '.round((($price - $originalPrice)) / $price * 100, 2) .' %';
}
function getHreflang($langue, $urlfrom, $route, $params){
$entityManager = $this->doctrine->getManager();
$conn = $entityManager->getConnection();
$urls = array(
'fr-fr' => array(
'/idees-cadeaux' => 'gift-ideas',
'/collections' => 'collections',
),
'en' => array(
'/gift-ideas' => 'idees-cadeaux',
'/collections' => 'collections',
),
);
if($langue == 'en'){
$locale = 'en_US';
$locale_inverse = 'fr_FR';
}else{
$locale = 'fr_FR';
$locale_inverse = 'en_US';
}
$categories = [
'en_US' => [
'enfant' => 'children',
'classique' => 'classic',
'temporaire' => 'temporary'
],
'fr_FR' => [
'children' => 'enfant',
'classic' => 'classique',
'temporary' => 'temporaire'
]
];
$url = '';
switch ($route ) {
case 'app_product_variant_show':
$sql = '
SELECT * FROM sylius_product_variant_translation
WHERE translatable_id = :translatable_id
AND locale = :locale
';
$stmt = $conn->prepare($sql);
$resultSet = $stmt->executeQuery([
'translatable_id' => $params['id'],
'locale' => $locale_inverse,
]);
$result = $resultSet->fetchAllAssociative();
$url = "p/".$result[0]['slug'].'-'.$params['id'];
break;
case 'sylius_shop_product_index':
$repository = $this->container->get('sylius.repository.taxon');
$taxon = $repository->findOneBySlug($params['slug'], $locale);
$sql = '
SELECT * FROM sylius_taxon_translation
WHERE translatable_id = :translatable_id
AND locale = :locale
';
$stmt = $conn->prepare($sql);
$resultSet = $stmt->executeQuery([
'translatable_id' => $taxon->getId(),
'locale' => $locale_inverse,
]);
$result = $resultSet->fetchAllAssociative();
$url = $result[0]['slug'];
break;
case 'app_page_cms_show':
$sitePageCmsRepository = $entityManager->getRepository(SitePageCMSTranslation::class);
$sitePageCmsTranslation = $sitePageCmsRepository->findOneBySlug($params['slug']);
$sql = '
SELECT * FROM site_page_cms_translation
WHERE translatable_id = :translatable_id
AND locale = :locale
';
$stmt = $conn->prepare($sql);
$resultSet = $stmt->executeQuery([
'translatable_id' => $sitePageCmsTranslation->getTranslatable()->getId(),
'locale' => $locale_inverse,
]);
$result = $resultSet->fetchAllAssociative();
if(isset($result[0])){
$url = "ppmc/".$result[0]['slug'];
}
break;
case 'app_collection_category':
$slugBase = '';
if(isset($categories[$locale_inverse][$params['slugCategory']])){
$slugBase = $categories[$locale_inverse][$params['slugCategory']];
$url = "collections/".$slugBase;
}
break;
case 'app_collection_show':
if(isset($categories[$locale_inverse][$params['slugCategory']])){
$slugBase = $categories[$locale_inverse][$params['slugCategory']];
$url = "collections/".$slugBase;
$collectionTranslationRepository = $entityManager->getRepository(SiteCollectionTranslation::class);
$collectionTranslation = $collectionTranslationRepository->findOneBySlug($params['slug']);
$sql = '
SELECT * FROM site_collection_translation
WHERE translatable_id = :translatable_id
AND locale = :locale
';
$stmt = $conn->prepare($sql);
$resultSet = $stmt->executeQuery([
'translatable_id' => $collectionTranslation->getTranslatable()->getId(),
'locale' => $locale_inverse,
]);
$result = $resultSet->fetchAllAssociative();
if(isset($result[0])){
$url = "collections/".$slugBase."/".$result[0]['slug'];
}
}
break;
default:
if(isset($urls[$langue][$urlfrom])){
$url = $urls[$langue][$urlfrom];
}
}
return $url;
}
function hasReturnColissimo($idOrder) {
$filepath = __DIR__ . '/../../data/etiquettes/'.$idOrder.'-etiquette-retour-colissimo.pdf';
if(file_exists($filepath)) {
return $filepath;
}
return false;
}
}