/**
	 * Test cart preview total product count when the same product is used multiple times
	 */
	public function testCartPreviewCount_DuplicateProducts()
	{
		$cart_srl = 774;
		$cart = new Cart($cart_srl);

		// Make sure we start with 4 products
		$this->assertEquals(4, count($cart->getProducts()));

		// Add one new product to cart (of the same type as one that already is in the cart)
		$product_repository = new ProductRepository();
		$product = $product_repository->getProduct(133);
		$cart->addProduct($product, 1);

		// Make sure new product was added to cart
		$cart = new Cart($cart_srl);
		$this->assertEquals(5, $cart->count(TRUE));

		$cart_preview = new CartPreview($cart, 2);

		$cart_preview_products = $cart_preview->getProducts();
		$this->assertEquals(2, count($cart_preview_products));

		$cart_products_count = $cart_preview->getCartProductsCount();
		$this->assertEquals(5, $cart_products_count);
	}
Exemple #2
0
 /**
  * @param Request $request
  * @throws Exception
  */
 public function addToCartAction(Request $request)
 {
     $id = $request->get('id');
     if (!$id) {
         throw new Exception('Bad request', 400);
     }
     $cart = new Cart();
     $cart->addProduct($id);
     header('Location: /cart/show');
 }
function loadApi($action)
{
    switch ($action) {
        case 'add_product':
            if (!Request::has(array('productid', 'quantity'))) {
                throw new Exception("Product not valid.");
            }
            try {
                Cart::addProduct(Request::get('productid'), Request::get('quantity'));
                $data = json_encode(array('error' => 'no', 'message' => 'Add product success.'));
                return $data;
            } catch (Exception $e) {
                throw new Exception($e->getMessage());
            }
            break;
    }
}
Exemple #4
0
<?php

require_once 'classes/ec/product.php';
require_once 'classes/ec/cart.php';
$product = new Product($_POST['id']);
$cart = new Cart();
$cart->addProduct($product);
header('Location: cart_list.php');
exit;
Exemple #5
0
    private $p = [];
    public function addProduct($k, $p)
    {
        $this->p[$k] = (double) $p;
    }
    public function getTotal($tax)
    {
        $sum = 0;
        array_walk($this->p, function ($val) use($tax, &$sum) {
            $sum += $val * ($tax + 1.0);
        });
        return $sum;
    }
}
$cart = new Cart();
$cart->addProduct('apple', 10);
$cart->addProduct('rasberry', 45);
echo $cart->getTotal(0.196);
var_dump('------- static private-------');
$sum = function ($v) {
    return function () use($v) {
        return ++$v;
    };
};
$r = $sum(10);
echo $r();
$r = $sum(10);
echo $r();
var_dump('---------- Exemple de contexte global pour une variable PHP');
$val = 10;
function baz()
 /**
  * Action для добавления товара в корзину при помощи асинхронного запроса (ajax)
  * @param integer $id <p>id товара</p>
  */
 public function actionAddAjax($id)
 {
     // Добавляем товар в корзину и печатаем результат: количество товаров в корзине
     echo '(' . Cart::addProduct($id) . ')';
     return true;
 }
Exemple #7
0
 public function testAddProduct()
 {
     $cart = new Cart(774);
     $pRepo = new ProductRepository();
     $product1 = $pRepo->getProduct(130);
     $product2 = $pRepo->getProduct(133);
     $cart->emptyCart();
     $this->assertEquals(0, $cart->count(), "Delete didn't work");
     $cart->addProduct($product1);
     $this->assertEquals(1, $cart->count(), "Adding product 1 failed");
     $this->assertEquals($cart->count(), count($cart->getProducts()), "?");
     $cart->addProduct($product2, 1405);
     $this->assertEquals(2, $cart->count(), "Adding product 2 failed");
     //getProducts should ignore its internal cache, so we tell it to.
     $this->assertEquals($cart->count(), count($cart->getProducts(NULL, NULL, TRUE)), "?");
 }
Exemple #8
0
 public function actionAdd($id)
 {
     echo Cart::addProduct($id);
     return true;
 }
Exemple #9
0
 public function getResponse()
 {
     $this->doorGets->checkAjaxMode();
     $response = array('code' => 404, 'data' => array());
     $arrayAction = array('index' => 'Home', 'add' => 'add', 'plus' => 'plus', 'minus' => 'minus', 'remove' => 'remove', 'shippingMethod' => 'shippingMethod');
     $out = '';
     $params = $this->doorGets->Params();
     $modules = $this->doorGets->getAllActiveModules();
     $lgActuel = $this->doorGets->getLangueTradution();
     $lg = 'en';
     if (array_key_exists('lg', $params['GET']) && array_key_exists($params['GET']['lg'], $this->doorGets->allLanguages)) {
         $lg = $this->doorGets->myLanguage = $params['GET']['lg'];
     }
     if (array_key_exists($this->Action, $arrayAction)) {
         switch ($this->Action) {
             case 'index':
                 break;
             case 'add':
                 if (true) {
                     $uri = array_key_exists('uri', $params['GET']) && !empty($params['GET']['uri']) ? $params['GET']['uri'] : '';
                     $quantity = array_key_exists('qty', $params['GET']) && !empty($params['GET']['qty']) ? (int) $params['GET']['qty'] : 1;
                     $id = array_key_exists('id', $params['GET']) && !empty($params['GET']['id']) ? $params['GET']['id'] : '';
                     if (empty($quantity)) {
                         $quantity = 1;
                     }
                     if (!empty($uri) && !empty($id) && array_key_exists($uri, $modules)) {
                         $sqlUri = $this->doorGets->getRealUri($uri);
                         $table = '_m_' . $sqlUri;
                         $tableTraduction = $table . '_traduction';
                         $isContent = $this->doorGets->dbQS($id, $table);
                         if (!empty($isContent)) {
                             $idTraduction = $this->doorGets->getIdContentTraduction($isContent);
                             if (!is_null($idTraduction)) {
                                 $isContentTraduction = $this->doorGets->dbQS($idTraduction, $tableTraduction);
                                 if (!empty($isContentTraduction)) {
                                     $product = array('uri' => $uri, 'id' => $id, 'quantity' => $quantity);
                                     $Cart = new Cart($this->doorGets);
                                     $Cart->addProduct($product);
                                     $Cart->save();
                                     $products = $Cart->getProducts();
                                     $productName = $products[$uri . '-' . $id]['title'];
                                     $response = array('code' => 200, 'data' => array('message' => $productName . ' ' . $this->doorGets->__("est dans votre panier") . '.', 'products' => $Cart->getProducts(), 'count' => $Cart->getCount(), 'totalAmount' => number_format($Cart->getTotalAmount(), 2, ',', ' '), 'totalAmountVat' => number_format($this->vat * $Cart->getTotalAmount() + $Cart->shippingAmount, 2, ',', ' '), 'subtotalAmountVat' => $Cart->getSubTotalAmountPromoVAT(true), 'totalAmountPromo' => number_format($Cart->getTotalAmountPromo(), 2, ',', ' '), 'totalAmountPromoVat' => number_format($this->vat * $Cart->getTotalAmountPromo() + $Cart->shippingAmount, 2, ',', ' '), 'shippingAmount' => $Cart->getShippingAmount(), 'langue' => $lg, 'uri' => $uri));
                                 }
                             }
                         }
                     }
                 }
                 break;
             case 'minus':
                 if (array_key_exists('uri', $params['GET'])) {
                     $uri = $params['GET']['uri'];
                     $Cart = new Cart($this->doorGets);
                     $newAmount = $Cart->minusProduct($uri);
                     $Cart->save();
                     $response = array('code' => 200, 'data' => array('message' => $this->doorGets->__("Le quantité du produit a été mise à jour") . '.', 'products' => $Cart->getProducts(true), 'count' => $Cart->getCount(), 'totalAmount' => $Cart->getTotalAmount(true), 'totalAmountVat' => $Cart->getTotalAmountVAT(true), 'subtotalAmountVat' => $Cart->getSubTotalAmountPromoVAT(true), 'totalAmountPromo' => $Cart->getTotalAmountPromo(true), 'totalAmountPromoVat' => $Cart->getTotalAmountPromoShippingVAT(true), 'shippingAmount' => $Cart->getShippingAmount(), 'langue' => $lg, 'newAmount' => $newAmount, 'uri' => $uri));
                 }
                 break;
             case 'plus':
                 if (array_key_exists('uri', $params['GET'])) {
                     $uri = $params['GET']['uri'];
                     $Cart = new Cart($this->doorGets);
                     $newAmount = $Cart->plusProduct($uri);
                     $Cart->save();
                     $response = array('code' => 200, 'data' => array('message' => $this->doorGets->__("Le quantité du produit a été mise à jour") . '.', 'products' => $Cart->getProducts(true), 'count' => $Cart->getCount(), 'totalAmount' => $Cart->getTotalAmount(true), 'totalAmountVat' => $Cart->getTotalAmountVAT(true), 'subtotalAmountVat' => $Cart->getSubTotalAmountPromoVAT(true), 'totalAmountPromo' => $Cart->getTotalAmountPromo(true), 'totalAmountPromoVat' => $Cart->getTotalAmountPromoShippingVAT(true), 'shippingAmount' => $Cart->getShippingAmount(), 'langue' => $lg, 'newAmount' => $newAmount, 'uri' => $uri));
                 }
                 break;
             case 'remove':
                 if (array_key_exists('uri', $params['GET'])) {
                     $uri = $params['GET']['uri'];
                     $Cart = new Cart($this->doorGets);
                     $Cart->removeProduct($uri);
                     $Cart->save();
                     $response = array('code' => 200, 'data' => array('message' => $this->doorGets->__("Le produit a été supprimé de votre panier") . '.', 'products' => $Cart->getProducts(true), 'count' => $Cart->getCount(), 'totalAmount' => $Cart->getTotalAmount(true), 'totalAmountVat' => $Cart->getTotalAmountVAT(true), 'subtotalAmountVat' => $Cart->getSubTotalAmountPromoVAT(true), 'totalAmountPromo' => $Cart->getTotalAmountPromo(true), 'totalAmountPromoVat' => $Cart->getTotalAmountPromoShippingVAT(true), 'shippingAmount' => $Cart->getShippingAmount(), 'langue' => $lg, 'uri' => $uri));
                 }
                 break;
             case 'shippingMethod':
                 if (array_key_exists('key', $params['GET'])) {
                     $key = $params['GET']['key'];
                     $Cart = new Cart($this->doorGets);
                     $Cart->setShippingMethod($key);
                     $Cart->save();
                     $response = array('code' => 200, 'data' => array('message' => $this->doorGets->__("Le prix de la livraison est à jour") . '.', 'products' => $Cart->getProducts(true), 'count' => $Cart->getCount(), 'totalAmount' => $Cart->getTotalAmount(true), 'totalAmountVat' => $Cart->getTotalAmountVAT(true), 'subtotalAmountVat' => $Cart->getSubTotalAmountPromoVAT(true), 'totalAmountPromo' => $Cart->getTotalAmountPromo(true), 'totalAmountPromoVat' => $Cart->getTotalAmountPromoShippingVAT(true), 'shippingAmount' => $Cart->getShippingAmount(), 'langue' => $lg));
                 }
                 break;
         }
     }
     return json_encode($response, JSON_FORCE_OBJECT);
 }
Exemple #10
0
function loadApi($action)
{
    switch ($action) {
        case 'htmlpopupdata':
            $htmlData = Cart::htmlPopupData();
            $data = json_encode(array('data' => $htmlData));
            return $data;
            break;
        case 'add_product':
            if (!Request::has(array('productid', 'quantity'))) {
                throw new Exception("Product not valid.");
            }
            try {
                Cart::addProduct(Request::get('productid'), Request::get('quantity'));
                $data = json_encode(array('error' => 'no', 'message' => 'Add product success.'));
                return $data;
            } catch (Exception $e) {
                throw new Exception($e->getMessage());
            }
            break;
        case 'remove_product':
            if (!Request::has('productid')) {
                throw new Exception("Product not valid.");
            }
            Cart::removeProduct(Request::get('productid'));
            $data = json_encode(array('error' => 'no', 'message' => 'Remove product success.'));
            return $data;
            break;
        case 'remove_coupon':
            if (!Request::has('code')) {
                throw new Exception("Coupon not valid.");
            }
            Cart::removeCoupon();
            $data = json_encode(array('error' => 'no', 'message' => 'Remove coupon success.'));
            return $data;
            break;
        case 'remove_voucher':
            if (!Request::has('code')) {
                throw new Exception("Voucher not valid.");
            }
            Cart::removeVoucher();
            $data = json_encode(array('error' => 'no', 'message' => 'Remove voucher success.'));
            return $data;
            break;
        case 'clear':
            Cart::clear();
            $data = json_encode(array('error' => 'no', 'message' => 'Clear cart success.'));
            return $data;
            break;
        case 'add_coupon':
            if (!Request::has('code')) {
                throw new Exception("Coupon code not valid.");
            }
            try {
                Cart::addCoupon(Request::get('code'));
                $data = json_encode(array('error' => 'no', 'message' => 'Add coupon success.'));
                return $data;
            } catch (Exception $e) {
                throw new Exception($e->getMessage());
            }
            break;
        case 'add_voucher':
            if (!Request::has('code')) {
                throw new Exception("Voucher code not valid.");
            }
            try {
                Cart::addVoucher(Request::get('code'));
                $data = json_encode(array('error' => 'no', 'message' => 'Add voucher success.'));
                return $data;
            } catch (Exception $e) {
                throw new Exception($e->getMessage());
            }
            break;
    }
}
Exemple #11
0
<?php

require_once ROOT . DS . 'controllers' . DS . 'cart.class.php';
require_once ROOT . DS . 'controllers' . DS . 'cookie.class.php';
require_once 'db.class.php';
$cart = new Cart();
$db = new DB($db_host, $db_user, $db_password, $db_name);
$action = isset($_GET['action']) ? $_GET['action'] : 'list';
if ($action == 'add') {
    $id = $_GET['id'];
    $cart->addProduct($id);
    header('Location: index.php');
} elseif ($action == 'delete') {
    $id = $_GET['id'];
    $cart->deleteProduct($id);
    header('Location: cart.php');
} elseif ($action == 'clear') {
    $cart->clear();
    header('Location: cart.php');
} else {
    if ($cart->isEmpty()) {
        echo "Cart is empty";
    } else {
        $id_sql = $cart->getProducts(true);
        $sql = "SELECT * FROM books WHERE id IN ({$id_sql})";
        $books = $db->query($sql);
        echo "My cart: <br>";
        foreach ($books as $book) {
            echo "<b>{$book['title']}</b>  <a href='cart.php?action=delete&id={$book['id']}'>Delete from cart</a> <br>";
        }
    }
Exemple #12
0
    public function getPrice()
    {
        return $this->price;
    }
}
class Cart
{
    private $products = array();
    public function addProduct($product)
    {
        $product->applyPriceDown();
        $this->products[] = $product;
    }
    public function getTotalPrice()
    {
        $total = 0;
        foreach ($this->products as $product) {
            $total += $product->getPrice();
        }
        return $total;
    }
}
$cart = new Cart();
$meet = new Meet();
$vegetable = new Vegetable();
$freezed = new FreezedFood();
$cart->addProduct($meet);
$cart->addProduct($vegetable);
$cart->addProduct($freezed);
$total = $cart->getTotalPrice();
var_dump($total);
 /**
  * @param $id
  * @return bool
  * Метод для добавления товара с помощью ajax
  */
 public function actionAjax($id)
 {
     return Cart::addProduct($id);
 }