HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/SBogers10/spire.komma-mediadesign.nl/wwwroot/mvc/models/m_shoppingCart.php
<?php


class ShoppingCart
{

    private $units = 0;
    private $items = [];

    public function __construct()
    {
        if(isset($_COOKIE['shopping-cart'])){
            $jsonShoppingCart = json_decode($_COOKIE['shopping-cart']);
            $this->createDistinctShoppingCart($jsonShoppingCart);
        }
    }

    /**
     * Create unique shopping cart items
     */
    private function createDistinctShoppingCart($jsonShoppingCart)
    {

        $flatShoppingCart = $jsonShoppingCart;
        $distinctShoppingCart = [];

        if(isset($flatShoppingCart)) {

            // Loop through flat shopping cart
            foreach ($flatShoppingCart as $shoppingCartUnit) {

                // Also skip shopping cart items that have no id
                // Bug within the spire corp site
                if(!isset($shoppingCartUnit->id) || $shoppingCartUnit->id == '') continue;

                // Create unique key
                $distinctShoppingCartKey = $shoppingCartUnit->id . '-' . $shoppingCartUnit->category;

                // Key by combination of product_id and category_id to group the shopping cart and create unique shopping cart items
                if ( ! isset($distinctShoppingCart[$distinctShoppingCartKey])) {
                    $distinctShoppingCart[$distinctShoppingCartKey] = $shoppingCartUnit;
                    $distinctShoppingCart[$distinctShoppingCartKey]->units = 1;
                }else {
                    $distinctShoppingCart[$distinctShoppingCartKey]->units++;
                }
            }
        }

        // Reset keys
        $distinctShoppingCart = array_values($distinctShoppingCart);

        $this->items = $distinctShoppingCart;
        $this->units = sizeof($flatShoppingCart);
    }

    /**
     * Get the amount of unique shopping cart items
     *
     * @return integer
     */
    public function getUniqueItemsAmount()
    {
        echo sizeof($this->items);
    }

    /**
     * Get the amount of products in the shopping cart
     *
     * @return integer
     */
    public function getItemsAmount()
    {
        echo $this->units;
    }

}