src/Twig/Extension/CartExtension.php line 216

Open in your IDE?
  1. <?php
  2. /**
  3.  * Pimcore
  4.  *
  5.  * This source file is available under two different licenses:
  6.  * - GNU General Public License version 3 (GPLv3)
  7.  * - Pimcore Enterprise License (PEL)
  8.  * Full copyright and license information is available in
  9.  * LICENSE.md which is distributed with this source code.
  10.  *
  11.  *  @copyright  Copyright (c) Pimcore GmbH (http://www.pimcore.org)
  12.  *  @license    http://www.pimcore.org/license     GPLv3 and PEL
  13.  */
  14. namespace App\Twig\Extension;
  15. use Twig\Extension\AbstractExtension;
  16. use Twig\TwigFunction;
  17. use Pimcore\Model\DataObject;
  18. use Pimcore\Bundle\EcommerceFrameworkBundle\Factory;
  19. use Symfony\Component\Security\Core\User\UserInterface;
  20. use App\Model\Utility;
  21. class CartExtension extends AbstractExtension
  22. {
  23.     const DEFAULT_CART_NAME 'cart';
  24.     const DEFAULT_CART_NAME_B2C 'cart_b2c';
  25.     /**
  26.      * @var Factory
  27.      */
  28.     protected $factory;
  29.     public function __construct(Factory $factory)
  30.     {
  31.         $this->factory $factory;
  32.     }
  33.     public function getFunctions()
  34.     {
  35.         return [
  36.             new TwigFunction('app_cart_items_count', [$this'getCartItems']),
  37.             new TwigFunction('app_cart_items_count_b2c', [$this'getCartItemsB2C']),
  38.             new TwigFunction('truncate_name', [$this'truncateName']),
  39.             new TwigFunction('app_wish_list_count', [$this'getWishlistItems']),
  40.             new TwigFunction('app_get_order_status', [$this'getOrderStatus']),
  41.             new TwigFunction('app_get_quote_status', [$this'getQuoteStatus']),
  42.             new TwigFunction('app_get_quote_order', [$this'getQuoteOrder']),
  43.             new TwigFunction('app_get_draft_status', [$this'getDraftStatus']),
  44.             new TwigFunction('app_get_booking_status', [$this'getBookingStatus']),
  45.             new TwigFunction('app_get_booking_days', [$this'getBookingDays']),
  46.             new TwigFunction('app_get_product_check_stock', [$this'getProductCheckStock']),
  47.             new TwigFunction('app_get_all_categories', [$this'getCategories']),
  48.             new TwigFunction('app_get_params', [$this'getAllParams']),
  49.             new TwigFunction('italian_date', [$this'getItalianDate']),
  50.             new TwigFunction('italian_datetime', [$this'getItalianDatetime']),
  51.             new TwigFunction('asset_path', [$this'getAssetPath']),
  52.             new TwigFunction('calculate_bytes', [$this'readableBytes']),
  53.             new TwigFunction('european_price', [$this'getEuropeanPrice']),
  54.             new TwigFunction('european_count', [$this'getEuropeanCount']),
  55.             new TwigFunction('unserializedata', [$this'unserializedata'])
  56.         ];
  57.     }
  58.     public function getProductCheckStock($product){
  59.         $stock 0;
  60.         $color 'orange';
  61.         $isAvailable false;
  62.         $stock = (int) $product->getStockAvailability();
  63.         if($stock>=THRESHOLD_QTY)
  64.         {
  65.             $isAvailable true;
  66.             $color 'green';
  67.         }else if($stock<=0){
  68.             $isAvailable false;
  69.             $color 'red';
  70.         }
  71.         return ['isAvailable'=>$isAvailable,'stock'=>$stock,'color'=>$color];
  72.     }
  73.     public function getOrderStatus($order){
  74.         $result '<font style="vertical-align: inherit;">IN LAVORAZIONE</font>';
  75.         $color "";
  76.         $invoice 0;
  77.         if($order instanceof \Pimcore\Model\DataObject\OnlineShopOrder){
  78.             if(strtolower($order->getWorkflowState()) == "delivered"){
  79.                 $result '<font style="vertical-align: inherit;">Consegnato</font>';
  80.                 $color "green";
  81.                 $invoice 1;
  82.             }
  83.             else if(strtolower($order->getWorkflowState()) == "dispatched"){
  84.                 $result '<font style="vertical-align: inherit;">SPEDITO</font>';
  85.                 $color "green";
  86.                 $invoice 1;
  87.             }
  88.             else if(strtolower($order->getWorkflowState()) == "confirmed"){
  89.                 $result '<font style="vertical-align: inherit;">IN LAVORAZIONE</font>';
  90.                 $color "";
  91.                 $invoice 1;
  92.             }
  93.             else if(strtolower($order->getWorkflowState()) == "partially_shipped"){
  94.                 $result '<font style="vertical-align: inherit;">PARZIALMENTE SPEDITO</font><br/>';
  95.                 $color "orange";
  96.                 $invoice 1;
  97.             }else if(strtolower($order->getWorkflowState()) == "cancelled"){
  98.                 $result '<font style="vertical-align: inherit;"><strike>ANNULLATO</strike></font>';
  99.                 $color "red";
  100.                 $invoice 0;
  101.             }
  102.         }
  103.         return ['color'=>$color,'result'=>$result,'invoice'=>$invoice];
  104.     }
  105.     public function getBookingStatus($order){
  106.         $result '<font style="vertical-align: inherit;">'.BOOKING_EXPIRY_DAYS.' GIORNI ALLA SCADENZA</font>';
  107.         $color ='green';
  108.         $days 0;
  109.         $cancelled false;
  110.         if($order instanceof \Pimcore\Model\DataObject\PurchaseOrder){
  111.             $cancelled $order->getIsCancelled();
  112.             $expired $order->getIsExpired();
  113.             if($expired){
  114.                 $color "red";
  115.                 $result '<font style="vertical-align: inherit;">'.strtoupper('Prenotazione scaduta').'</font>';
  116.             }else if($cancelled){
  117.                 $color "red";
  118.                 $result '<font style="vertical-align: inherit;"><strike>ANNULLATA</strike></font>';
  119.             }else{
  120.                 $fromDate $order->getFromDate();
  121.                 $toDate $order->getDueDate();
  122.                // p_r($fromDate->getTimeStamp());
  123.                 $days $this->secondsToTime($fromDate->getTimeStamp(),strtotime('now'));
  124.               //p_r($days);p_r(BOOKING_EXPIRY_DAYS);
  125.                 if($days <= BOOKING_EXPIRY_DAYS){
  126.                     $color "green";
  127.                     $result '<font style="vertical-align: inherit;">'.(BOOKING_EXPIRY_DAYS-$days).' GIORNI ALLA SCADENZA</font>';
  128.                 }else if($days<=&& $days>1){
  129.                     $color "orange";
  130.                     $result '<font style="vertical-align: inherit;">'.(BOOKING_EXPIRY_DAYS-$days).' GIORNI ALLA SCADENZA</font>';
  131.                 }else if($days >= BOOKING_EXPIRY_DAYS){
  132.                     $color "red";
  133.                     $order->setIsExpired(TRUE);
  134.                     $order->save();
  135.                     $result '<font style="vertical-align: inherit;">'.strtoupper('prenotazione scaduta').'</font>';
  136.                 }
  137.             }
  138.         }
  139.         return ['color'=>$color,'result'=>$result,'isCancelled'=>$cancelled];
  140.     }
  141.     public function getBookingDays($orderId){
  142.         $result '<font style="vertical-align: inherit;">'.BOOKING_EXPIRY_DAYS.'</font>';
  143.         $color ='green';
  144.         $days 5;
  145.         $cancelled false;
  146.         $order \Pimcore\Model\DataObject::getById($orderId);
  147.         if($order instanceof \Pimcore\Model\DataObject\PurchaseOrder){
  148.             $cancelled $order->getIsCancelled();
  149.             $expired $order->getIsExpired();
  150.             if($expired){
  151.                 $days 0;
  152.                 $color "red";
  153.                 $result '<font style="vertical-align: inherit;">0</font>';
  154.             }else if($cancelled){
  155.                 $color "red";
  156.                 $days 0;
  157.                 $result '<font style="vertical-align: inherit;">0</font>';
  158.             }else{
  159.                 $fromDate $order->getFromDate();
  160.                 $toDate $order->getDueDate();
  161.                // p_r($fromDate->getTimeStamp());
  162.                 $days $this->secondsToTime($fromDate->getTimeStamp(),strtotime('now'));
  163.               //p_r($days);p_r(BOOKING_EXPIRY_DAYS);
  164.                 if($days <= BOOKING_EXPIRY_DAYS){
  165.                     $color "green";
  166.                     $result '<font style="vertical-align: inherit;">'.$days.'</font>';
  167.                 }else if($days<=&& $days>1){
  168.                     $color "orange";
  169.                     $result '<font style="vertical-align: inherit;">'.$days.'</font>';
  170.                 }else if($days >= BOOKING_EXPIRY_DAYS){
  171.                     $color "red";
  172.                     $order->setIsExpired(TRUE);
  173.                     $order->save();
  174.                     $result '<font style="vertical-align: inherit;">'.$days.'</font>';
  175.                 }
  176.             }
  177.         }
  178.         return ['color'=>$color,'result'=>$result,'isCancelled'=>$cancelled,'days'=>$days];
  179.     }
  180.     function secondsToTime($from,$seconds) {
  181.         $dtF = new \DateTime("@$from");
  182.         $dtT = new \DateTime("@$seconds");
  183.         return $dtF->diff($dtT)->format('%a');
  184.     }
  185.     /**
  186.      * @return CartInterface
  187.      */
  188.     public function getWishlistItems()
  189.     {
  190.         $totalCount 0;
  191.         $user \Pimcore::getContainer()->get('security.token_storage')->getToken()->getUser();
  192.         if($user instanceof \Pimcore\Model\DataObject){
  193.             $wishList = new DataObject\Wishlist\Listing();
  194.             $wishList->setCondition('user__id = ?',[$user->getId()]);
  195.             $list $wishList->getCount();
  196.             $totalCount = !empty($list)?$list:0;
  197.         }
  198.         return $totalCount;
  199.     }
  200.     /**
  201.      * @return CartInterface
  202.      */
  203.     protected function getCart()
  204.     {
  205.         $cartManager $this->factory->getCartManager();
  206.         return $cartManager->getOrCreateCartByName(self::DEFAULT_CART_NAME);
  207.     }
  208.     public function getCartItems()
  209.     {
  210.         $cart $this->getCart();
  211.         return count($cart->getItems());
  212.     }
  213.     /**
  214.      * @return CartInterface
  215.      */
  216.     protected function getCartB2C()
  217.     {
  218.         $cartManager $this->factory->getCartManager();
  219.         return $cartManager->getOrCreateCartByName(self::DEFAULT_CART_NAME_B2C);
  220.     }
  221.     public function getCartItemsB2C()
  222.     {
  223.         $cart $this->getCartB2C();
  224.         return count($cart->getItems());
  225.     }
  226.     public function truncateName($string){
  227.         $string = (strlen($string) > 120) ? substr($string,0,120).'...' $string;
  228.         return $string;
  229.     }
  230.     public function getCategories(){
  231.         $utility = new Utility();
  232.         $categories $utility->getCategories();
  233.         $category = new DataObject\Category\Listing();
  234.         $category->setCondition('o_id IN (?)',[$categories[0]['cat']]);
  235.         $category->setOrder('name ASC');
  236.         $categoryList $category->load();
  237.         return $categoryList;
  238.     }
  239.     public function getAllParams(){
  240.         return $_GET;
  241.     }
  242.     public function getItalianDate($date){
  243.         if(method_exists($date,"getTimestamp")){
  244.             $months = array(
  245.                     '01' => 'Gennaio',
  246.                     '02' => 'Febbraio',
  247.                     '03' => 'Marzo',
  248.                     '04' => 'Aprile',
  249.                     '05' => 'Maggio',
  250.                     '06' => 'Giugno',
  251.                     '07' => 'Luglio',
  252.                     '08' => 'Agosto',
  253.                     '09' => 'Settembre',
  254.                     '10' => 'Ottobre',
  255.                     '11' => 'Novembre',
  256.                     '12' => 'Dicembre');
  257.             list($day$month$year) = explode('-',date('d-m-Y',$date->getTimestamp()));
  258.             return $day ' ' $months[$month] . ' ' $year;
  259.         }else{
  260.             return date('Y-m-d H:i:s');
  261.         }
  262.     }
  263.     public function getItalianDateTime($date){
  264.         //if(method_exists($date,"getTimestamp")){
  265.         $months = array(
  266.                 '01' => 'Gennaio',
  267.                 '02' => 'Febbraio',
  268.                 '03' => 'Marzo',
  269.                 '04' => 'Aprile',
  270.                 '05' => 'Maggio',
  271.                 '06' => 'Giugno',
  272.                 '07' => 'Luglio',
  273.                 '08' => 'Agosto',
  274.                 '09' => 'Settembre',
  275.                 '10' => 'Ottobre',
  276.                 '11' => 'Novembre',
  277.                 '12' => 'Dicembre');
  278.         list($day$month$year) = explode('-',date('d-m-Y',$date));
  279.         return $day ' ' $months[$month] . ' ' $year.' ore '.date('h:i A',$date);
  280.     }
  281.     function readableBytes($bytes) {
  282.         $i floor(log($bytes) / log(1024));
  283.         $sizes = array('B''KB''MB''GB''TB''PB''EB''ZB''YB');
  284.         $totalSize = (pow(1024$i) > 0)?sprintf('%.02F'$bytes pow(1024$i)) * :'';
  285.         $fmt = new \NumberFormatter'it_IT'\NumberFormatter::DECIMAL );
  286.         $totalSize =  $fmt->format((float)$totalSize);
  287.         return (pow(1024$i) > 0)?$totalSize' ' $sizes[$i]:0;
  288.     }
  289.     /**
  290.      * @return int|string
  291.     */
  292.     public static function getEuropeanPrice($price,$product=false): ?string
  293.     {
  294.         if($product)
  295.         {
  296.             preg_match('/([0-9]+\.[0-9]+)/'$price->getNetAmount()->__toString(), $matches);
  297.             $number = (float) $matches[1]; // 55.35
  298.             $formatter = new \NumberFormatter("it-IT"\NumberFormatter::CURRENCY);
  299.             $formatter->setAttribute$formatter::FRACTION_DIGITS);
  300.             return $formatter->formatCurrency($number'EUR');
  301.         }else
  302.         {
  303.             if(is_numeric($price)){
  304.                 $matches[1] = $price;
  305.             }else{
  306.                 preg_match('/([0-9]+\.[0-9]+)/'$price$matches);
  307.             }
  308.             $number = (!empty($matches[1]))?(float) $matches[1]:00.00// 55.35
  309.             $formatter = new \NumberFormatter("it-IT"\NumberFormatter::CURRENCY);
  310.             $formatter->setAttribute$formatter::FRACTION_DIGITS);
  311.             return $formatter->formatCurrency($number'EUR');
  312.         }
  313.     }
  314.     /**
  315.      * @return int|string
  316.     */
  317.     public static function getEuropeanCount($qty): ?string
  318.     {
  319.         $fmt = new \NumberFormatter'it_IT'\NumberFormatter::DECIMAL );
  320.         return $fmt->format($qty);
  321.     }
  322.     public function unserializedata($data){
  323.         return unserialize($data);
  324.     }
  325.     public function getAssetPath($path){
  326.         return BASE_URL.$path;
  327.     }
  328.     public function getQuoteStatus($quote){
  329.         if(!$quote->getWorkflowState()){
  330.             $quote->setWorkflowState('not_processed');
  331.         }
  332.         //return $quote->getWorkflowState();
  333.         $result '<font style="vertical-align: inherit; padding:2px; color:'.QUOTE_STATUS[$quote->getWorkflowState()]['color'].'">'.strtoupper(QUOTE_STATUS[$quote->getWorkflowState()]['title']).'</font>';
  334.         return $result;
  335.     }
  336.     public function getQuoteOrder($searchable,$column,$order){
  337.         if($searchable == $column){
  338.             if($order == 'desc'){
  339.                 return '<i class="ml-2 uparrow quote_order_by" column="'.$searchable.'" orderby="asc"></i>';
  340.             }else{
  341.                 return '<i class="ml-2 downarrow quote_order_by" column="'.$searchable.'" orderby="desc"></i>';
  342.             }
  343.         }else{
  344.             return '<i class="ml-2 downarrow quote_order_by" column="'.$searchable.'" orderby="'.$order.'"></i>';
  345.         }
  346.     }
  347. }