How to move First/Selected order to last in Laravel? - php

I want to move my first order to the bottom of the list and not to delete the first order as well.
here is my code. This is deleting/unset first order as well.
`
if (isset($request['defer_order']) && $request['defer_order'] != null) {
$order_id = $request['defer_order'];
foreach ($order_items as $key => $order_item) {
$last = count($order_items);
if ($order_item->order_id == $order_id) {
unset($order_items[$key]);
$order_items[$last + 1] = $order_item;
}
}
$order_items = $order_items;
}
`
I am trying to move first order to the bottom of the list.

Since you are using unset, the order is removed from the array. You can use the code below instead. It will add your desired order at the end without changing anything in the array
if (isset($request['defer_order']) && $request['defer_order'] != null) {
$order_id = $request['defer_order'];
$order_items = (array)$order_items;
$myOrder = '';
foreach ($order_items as $order_item) {
if ($order_item['order_id'] == $order_id) {
$myOrder = $order_item;
unset($order_items[$key]);
break;
}
}
if ($myOrder != '') {
$order_items[] = $myOrder;
}
$order_items = (object)$order_items;
}
Updated the code as per your requirement

Related

Magento 2 Bundle price

I would like to ask you for some help or even just a comparison.
On my site I have bundles that are dimanically priced with select products, some with radio and some with default.
Magento 2 however shows two different prices between listing and product page. I have checked at code level and on the product page there is a manipulation via js that changes the price. In fact when the page loads you see a price before the update. Have you ever implemented some solution to make the same prices appear? This is the piece of code I am trying to implement but without success as it returns the same price because the products are set to default even though they are not selected on the product page.
$product = $this->productRepository->get($product_sku);
$selectionCollection = $product->getTypeInstance(true)
->getSelectionsCollection(
$product->getTypeInstance(true)->getOptionsIds($product),
$product
);
$children_ids = $this->bundleType->getChildrenIds($product->getId(), true);
$bundle_items = [];
$optionsCollection = $product->getTypeInstance(true)
->getOptionsCollection($product);
foreach ($optionsCollection as $options) {
$optionArray[$options->getOptionId()]['option_title'] = $options->getDefaultTitle();
$optionArray[$options->getOptionId()]['option_type'] = $options->getType();
if ($options->getType() !== 'checkbox' && $options->getRequired() === "1") {
foreach ($selectionCollection as $selection) {
foreach ($children_ids as $bundle_id) {
if ((array_values($bundle_id)[0] === $selection->getEntityId())
&& $options->getId() === $selection->getOptionId()) {
$price = $selection->getPrice();
$qty = $selection->getSelectionQty();
$bundle_items[] = $price * $qty;
}
}
}
}
}
$finale_price = array_sum($bundle_items);
I finally solved it by creating a function that would return the tier price. Mine is a bit more customised because I have different prices depending also on the customer group. I'll leave the code.
public function getBundlePrice($product_sku, $product_sal)
{
$product = $this->productRepository->get($product_sku);
$selectionCollection = $product->getTypeInstance(true)
->getSelectionsCollection(
$product->getTypeInstance(true)->getOptionsIds($product),
$product
);
$children_ids = $this->bundleType->getChildrenIds($product->getId(), true);
$bundle_items = [];
$optionsCollection = $product->getTypeInstance(true)
->getOptionsCollection($product);
foreach ($optionsCollection as $options) {
$optionArray[$options->getOptionId()]['option_title'] = $options->getDefaultTitle();
$optionArray[$options->getOptionId()]['option_type'] = $options->getType();
if ($options->getType() !== 'checkbox' && $options->getRequired() === "1") {
foreach ($selectionCollection as $selection) {
foreach ($children_ids as $bundle_id) {
if ((array_values($bundle_id)[0] === $selection->getEntityId())
&& $options->getId() === $selection->getOptionId()) {
$price = $selection->getPrice();
$qty = $selection->getSelectionQty();
if ($qty > 1 || $selection->getTierPrice()) {
$price = $this->getCustomPrice($selection);
} else if ($this->customerSession->getCustomer()->getGroupId() === "2") {
$price = $selection->getPartnerPrice();
}
$bundle_items[] = $price * $qty;
}
}
}
}
}
return $this->calculator->getAmount(array_sum($bundle_items), $product_sal);
}

"Cannot get return value of a generator that hasn't returned " php backtracking

I am trying to do backtracking to solved a problem but I get this error:
Error: genator hasn´t returned
Fisrt I will introduce the main problem that the software must resolve:
I have been trying to create the software for a hospital, this
software must create a schedule with the doctors for each day. Each
day must have 5 assigned doctors, one for a specialty called "trauma",
another for "ucr" and another for "box13".
Before assigning doctors, the user must enter the number of holes of
each type that doctor can do that month. So I know how many "trauma",
"ucr" or "box13" have any doctor that month.
Aaah! one more thing, you can not assign a doctor two days in a row.
So I decided to create a backtracking algorithm, the problem is that I am getting a Generator object at the end of the execution but I don´t get a valid return.
function bt($ps){
if($ps->is_solution()){
return $ps->get_solution();
}
else{
yield from $ps->successors();
}
}
class Briker_vc_PS{
public function __construct( $decisiones, $diasTotalFinal, $fechaInicio, $box13, $ucr, $trauma, $numGuardiasAsig){
$this->decisiones= $decisiones;
$this->diasTotalFinal = $diasTotalFinal;
$this->fechaInicio = $fechaInicio;
$this->box13 = $box13;
$this->ucr = $ucr;
$this->trauma = $trauma;
$this->numGuardiasAsig = $numGuardiasAsig;
}
public function is_solution(){
return $this->numGuardiasAsig == $this->diasTotalFinal*5;
}
public function get_solution(){
return $this->decisiones;
}
public function state(){
return $this->decisiones[$this->fechaInicio];
}
public function successors(){
if( array_key_exists( $this->fechaInicio, $this->decisiones) == false ){
$this->decisiones[$this->fechaInicio] = [];
}
if( array_key_exists( 'ids', $this->decisiones[$this->fechaInicio]) == false ){
$this->decisiones[$this->fechaInicio]['ids'] = [];
}
if( array_key_exists( $this->fechaInicio ,$this->decisiones) and array_key_exists( 'box13' ,$this->decisiones) and array_key_exists( 'trauma' ,$this->decisiones) and array_key_exists( 'ucr' ,$this->decisiones)){
if( (count($this->decisiones['trauma'])==1) and (count($this->decisiones['ucr'])==2) and (count($this->decisiones['box13'])==2) ){
$this->fechaInicio = date("Y-m-d",strtotime($this->fechaInicio." +1 day"));
$this->decisiones[$this->fechaInicio]['date'] = $this->fechaInicio;
}
}
$anterior = date("Y-m-d",strtotime($this->fechaInicio." -1 day"));
$Lista=[];
if( array_key_exists( 'trauma' ,$this->decisiones) == false ){
foreach($this->trauma as $key => $val){
if( (in_array($key, $this->decisiones[$this->fechaInicio]['ids']) == false) and (in_array($key, $this->decisiones[$anterior]['ids']) == false) ){
$decisions= $this->decisiones;
$decisions[$this->fechaInicio]['trauma'] = [$key];
$auxtra= $this->trauma;
if($auxtra[$key] -1 == 0){
unset($auxtra[$key]);
}else{
$auxtra[$key] = $auxtra[$key] -1;
}
$num = $this->numGuardiasAsig +1 ;
$decisions[$this->fechaInicio]['ids'][] = $key;
yield from bt(new Briker_vc_PS( $decisions, $this->diasTotalFinal, $this->fechaInicio, $this->box13, $this->ucr, $auxtra, $num));
}
}
}
if( (array_key_exists( 'box13' ,$this->decisiones) == false) or (count($this->decisiones['box13'])<2) ){
foreach($this->box13 as $key => $val){
if( (in_array($key, $this->decisiones[$this->fechaInicio]['ids']) == false) and (in_array($key, $this->decisiones[$anterior]['ids']) == false) ){
$decisions= $this->decisiones;
if(array_key_exists( 'box13' ,$this->decisiones) == false){
$decisions[$this->fechaInicio]['box13'] = array();
}
$decisions[$this->fechaInicio]['box13'][] = $key;
$auxbox13= $this->box13;
if($auxbox13[$key] -1 == 0){
unset($auxbox13[$key]);
}else{
$auxbox13[$key] = $auxbox13[$key] -1;
}
$num = $this->numGuardiasAsig +1 ;
$decisions[$this->fechaInicio]['ids'][] = $key;
yield from bt( new Briker_vc_PS( $decisions, $this->diasTotalFinal, $this->fechaInicio, $auxbox13, $this->ucr, $this->trauma, $num));
}
}
}
if( (array_key_exists( 'ucr' ,$this->decisiones) == false) or (count($this->decisiones['ucr'])<2) ){
foreach($this->ucr as $key => $val){
if( (in_array($key, $this->decisiones[$this->fechaInicio]['ids']) == false) and (in_array($key, $this->decisiones[$anterior]['ids']) == false) ){
$decisions= $this->decisiones;
if(array_key_exists( 'ucr' ,$this->decisiones) == false){
$decisions[$this->fechaInicio]['ucr'] = array();
}
$decisions[$this->fechaInicio]['ucr'][] = $key;
$auxucr= $this->ucr;
if($auxucr[$key] -1 == 0){
unset($auxucr[$key]);
}else{
$auxucr[$key] = $auxucr[$key] -1;
}
$decisions[$this->fechaInicio]['ids'][] = $key;
$num = $this->numGuardiasAsig +1 ;
yield from bt(new Briker_vc_PS( $decisions, $this->diasTotalFinal, $this->fechaInicio, $this->box13, $auxucr, $this->trauma, $num));
}
}
}
}
protected $GuardiasMedico;
protected $decisiones;
}
And this is the main program
$month = $_REQUEST['mes'];
$year = $_REQUEST['any'];
$fecha_inicio = "01-".$month."-".$year;
// fisrt i get the number of "trauma", "ucr" and "box13" for each doctor
// And i create a array with it with key the doctor_id
$db = new SQLite3($dbname);
$result = $db->query('SELECT m.id, m.nombre, m.apellido, mgm.ucr, mgm.trauma, mgm.box13 FROM medico AS m INNER JOIN MedicoGuardiaMes AS mgm ON m.id = mgm.doctor_id WHERE m.borrado = 0 AND mgm.mes = '.$month.' AND mgm.any = '.$year);
$box13 = [];
$ucr = [];
$trauma = [];
while($res = $result->fetchArray()){
$box13[$res['id']] = $res['box13'];
$ucr[$res['id']] = $res['ucr'];
$trauma[$res['id']] = $res['trauma'];
}
// I create the solution array and add the last day from the previous month
$dataBaseDecisiones = [];
$anterior = date("Y-m-d",strtotime($fecha_inicio." -1 day"));
$dataBaseDecisiones[$anterior] = [];
$dataBaseDecisiones[$anterior]['ids'] = [];
$diasTotalFinal=cal_days_in_month(CAL_GREGORIAN, $month, $year);
// Finally I create the initial object and starts the backtracking
$initial_ps = new Briker_vc_PS($dataBaseDecisiones, $diasTotalFinal, $fecha_inicio, $box13, $ucr, $trauma, $numGuardiasAsig);
var_dump( bt($initial_ps)->getReturn() );
I don´t know why this code is not working or if I am using yield the right way.
The problem that is reported happens because of the last line in your code:
bt($initial_ps)->getReturn();
When bt executes the else part it performs a recursive search until there is a return, and then it yields that value. But that does not finish the iterator's results and this yielded value is not considered the iterator's return value. So getReturn() triggers the exception you got.
You don't explain what you intend to get as output in that var_dump. If you want to output all the yielded results, then collect all those results first, for instance with iterator_to_array:
$iter = bt($initial_ps);
print_r(iterator_to_array($iter));
And only then you can execute:
print_r($iter->getReturn());

Invalid argument supplied for foreach() inside shopping cart ,

I am trying to get more than 1 item in my shopping cart array but I run into an issue
This is my database after inserting 1 item with post method
Items is defined in db as text
After trying to insert second product the items result gets overwritten.
My developers tools output after clicking add to cart
ADD
I am using add to cart button from my modal >https://pastebin.com/HKSRTG4L that is submitting via ajax and parsed to add-cart.php
Where I have add to cart function : https://pastebin.com/guv0rB6x
This is my code from cart.php :
<?php
include_once $_SERVER['DOCUMENT_ROOT']."/EcomApp/konfiguracija.php";
require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/config.php';
include 'include/head.php';
include 'include/izbornik.php';
if($cart_id != ''){
$cartQ = $veza->prepare("SELECT * FROM cart WHERE id = '$cart_id';");
$cartQ->execute();
$result= $cartQ->fetch(PDO::FETCH_ASSOC);
$items = json_decode($result['items'],true);var_dump($items) ;
$i = 1;
$sub_total = 0;
$item_count = 0;
}
?>
<div class="col-md-12">
<div class="row">
<h2 class ="text-center">Your Shopping Cart </h2><hr>
<?php if($cart_id =='') :?>
<div class="bg-danger">
<p class="text-center text-danger">
Your shopping cart is empty!
</p>
</div>
<?php else: ?>
<table class="table" >
<thead><th>#</th><th>Item</th><th>Price</th><th>Quantity</th><th>Size</th><th>Sub Total</th></thead>
<tbody>
<?php
foreach ($items as $item){
$product_id =$item['id'];
$productQ = $veza ->prepare("SELECT * FROM products WHERE id = '$product_id'");
$productQ ->execute();
$product= $productQ->fetch(PDO::FETCH_ASSOC);
$sArray = explode (',',$product['sizes']);
foreach($sArray as $sizeString){
$s = explode(':',$sizeString);
if($s[0] ==$item['size']){
$available = $s[1];
}
}
?>
<tr>
<td><?=$i;?></td>
<td><?=$product['title'];?></td>
<td><?=$product['price'];?></td>
<td><?=$item['quantity'];?></td>
<td><?=$item['size'];?></td>
<td><?=$item['quantity'] * $product['price'];?></td>
</t>
<?php } ?>
</tbody>
</table>
<?php endif; ?>
</div>
<?php include 'include/footer.php';?>
I am 93% sure the problem is with array merge since currently the insert is overwriting the row with new results and not adding to the array.
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/konfiguracija.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/config.php';
$product_id = sanitize($_POST['product_id']);
$size = sanitize($_POST['size']);
$available = sanitize($_POST['available']);
$quantity = sanitize($_POST['quantity']);
$item = array();
$item[]= array(
'id' => $product_id,
'size' => $size,
'quantity' => $quantity,
);
$domain = ($_SERVER['HTTP_HOST'] != 'localhost')?'.'.$_SERVER['HTTP_HOST']:false;
$query = $veza->prepare("SELECT * FROM products WHERE id = '$product_id'");
$query ->execute();
$product = $query->fetch(PDO::FETCH_ASSOC);
$_SESSION['success_launch'] = $product['title']. 'was added to your cart.';
//check does cookie cart exist
if($cart_id != ''){
$cartQ= $veza->prepare("SELECT * FROM cart WHERE id = '$cart_id'");
$cart = $cartQ->fetch(PDO::FETCH_ASSOC);
$previous_items = json_decode($cart['items'],true);
$item_match = 0;
$new_items = array();
foreach ($prevous_items as $pitem){
if($item[0]['id']==$pitem['id'] && $item[0]['size'] == $pitem['size']){
$pitem ['quantity']= $pitem['quantity']+$item[0]['quantity'];
if ($pitem['quantity']>$available){
$pitem['quantity'] = $available;
}
$item_match = 1;
}
$new_items[] = $pitem;
}
if($item_match != 1){
$new_items = array_merge($item,(array)$previous_items);
}
$items_json = json_encode($new_items);
$cart_expire = date("Y-m-d H:i:s", strtotime("+30 days"));
$something=$veza->prepare("UPDATE cart SET items = '$items_json',expire_date= '$cart_expire'WHERE id ='$cart_id'");
$something ->execute();
setcookie(CART_COOKIE,'',1,'/',$domain,false);
setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false);
}else {
INSERT
//add cart inside database
$items_json = json_encode($item);
$cart_expire = date("Y-m-d H:i:s",strtotime("+30 days"));
$smth=$veza->prepare("INSERT INTO cart (items,expire_date) VALUES ('$items_json','$cart_expire')");
$smth->execute();
$cart_id = $veza->lastInsertId();
setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false);
}
var_dump($cart_id);
?>
add to cart function : https://pastebin.com/guv0rB6x
function add_to_cart(){
jQuery('#modal_errors').html("");
var size = jQuery('#size').val();
var quantity = jQuery('#quantity').val();
var available = jQuery('#available').val();
var error = '';
var data = jQuery("#add_product_form").serialize();
if(size == '' || quantity == '' || quantity == 0){
error += '<p class= "bg-danger text-center">You must choose a size and quantity</p>';
jQuery('#modal_errors').html(error);
return;
}else if (quantity>available){
error += '<p class= "bg-danger text-center">There are only '+available+' available.</p>';
jQuery('#modal_errors').html(error);
return;
}else{
jQuery.ajax({
url: '/EcomApp/admin/parsers/add_cart.php',
method : 'post',
data : data,
success : function(){
location.reload();
},
error : function(){alert("Something went wrong");}
});
}
}
konfiguracija.php there is a (Undefined offset: 1) on line 65
$user_data['last'] = $fn1;
but I think it is not directly connected to the functionality
try{
$veza = new PDO("mysql:host=" . $host . ";dbname=" . $dbname,$dbuser,$dbpass);
$veza->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$veza->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8';");
$veza->exec("SET NAMES 'utf8';");
}catch(PDOException $e){
switch($e->getCode()){
case 1049:
header("location: " . $eone . "error/wrongDBname.html");
exit;
break;
default:
header("location: " . $eone . "error/error.php?code=" . $e->getCode());
exit;
break;
}
}
require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/config.php';
require_once BASEURL.'helpers/helpers.php';
session_start();
//
$cart_id = '';
if(isset($_COOKIE[CART_COOKIE])){
$cart_id = sanitize($_COOKIE[CART_COOKIE]);
}
if(isset($_SESSION['SDUser'])){
$user_id =$_SESSION['SDUser'];
$query = $veza->prepare("SELECT* FROM korisnik WHERE id ='$user_id'");
$query->execute();
$user_data = $query->fetch(PDO::FETCH_ASSOC);
$fn = explode(' ', $user_data['full_name']);
$user_data['first'] = $fn[0];
$user_data['last'] = $fn[1];
// print_r($user_data);
}
if(isset($_SESSION['success_launch'])){
echo '<h1><p class="text-success">'.$_SESSION['success_launch'].'</p></h1>';
unset($_SESSION['success_launch']);
}
if(isset($_SESSION['error_launch'])){
echo '<div class="success"><p class="text-success">'.$_SESSION['error_launch'].'</p></div>';
unset($_SESSION['error_launch']);
}
In add_cart.php:
$previous_items = json_decode($cart['items'],true);
$item_match = 0;
$new_items = array();
foreach ($prevous_items as $pitem){
Notice that $previous_items and $prevous_items are different.
That's why you're getting:
Notice: Undefined variable: prevous_items in
/opt/lampp/htdocs/EcomApp/admin/parsers/add_cart.php on line 29
You didn't take my previous advice to make your life easier.
Apparently working code is not enough. Always validate and fail fast ( http://www.practical-programming.org/ppl/docs/articles/fail_fast_principle/fail_fast_principle.html ):
if(!$cart_id){
$cartQ = $veza->prepare("SELECT * FROM cart WHERE id = ?");
$cartQ->execute([(int)$cart_id]);
$result= $cartQ->fetch(PDO::FETCH_ASSOC);
if (!isset($result['items'])) {
throw new \RuntimeException("The items were not found.");
}
$items = json_decode($result['items'],true);
if (!$items) {
throw new \RuntimeException("Invalid items format.");
}
$i = 1;
$sub_total = 0;
$item_count = 0;
}
As said, do something like this:
<?php
$validKeys = ['product_id', 'size', 'available', 'quantity'];
foreach ($validKeys as $key) {
if (!isset($_POST[$key])) {
throw new RuntimeException("Parameter $key is missing.");
}
}
require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/konfiguracija.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/EcomApp/config.php';
$product_id = sanitize($_POST['product_id']);
$size = sanitize($_POST['size']);
$available = sanitize($_POST['available']);
$quantity = sanitize($_POST['quantity']);
Most probably you missed something in the client side (javascript or HTML form), for instance, you might have misspelled "product_id".
ADDED:
https://pastebin.com/guv0rB6x
function add_to_cart(){
jQuery('#modal_errors').html("");
var size = jQuery('#size').val();
var quantity = jQuery('#quantity').val();
var available = jQuery('#available').val();
var error = '';
var data = jQuery("#add_product_form").serialize();
if(size == '' || quantity == '' || quantity == 0){
error += '<p class= "bg-danger text-center">You must choose a size and quantity</p>';
jQuery('#modal_errors').html(error);
return;
}else if (quantity>available){
error += '<p class= "bg-danger text-center">There are only '+available+' available.</p>';
jQuery('#modal_errors').html(error);
return;
}else{
jQuery.ajax({
url: '/EcomApp/admin/parsers/add_cart.php',
method : 'post',
data : data,
success : function(){
location.reload();
},
error : function(){alert("Something went wrong");}
});
}
}
You're not checking if the "product_id" field is empty.
ADDED:
Replace:
$previous_items = json_decode($cart['items'],true);
$item_match = 0;
$new_items = array();
foreach ($prevous_items as $pitem){
if($item[0]['id']==$pitem['id'] && $item[0]['size'] == $pitem['size']){
$pitem ['quantity']= $pitem['quantity']+$item[0]['quantity'];
if ($pitem['quantity']>$available){
$pitem['quantity'] = $available;
}
$item_match = 1;
}
$new_items[] = $pitem;
}
if($item_match != 1){
$new_items = array_merge($item,(array)$previous_items);
}
With something like this:
$previous_items = json_decode($cart['items'], true);
if (!$previous_items) {
$previous_items = array();
}
$items_by_unique = array();
foreach (array_merge($item, $previous_items) as $item) {
if (!isset($item['id'], $item['size'], $item['quantity'])) {
throw new RuntimeException('Found a invalid invalid data: ' . json_encode($item));
}
$unique = $item['id'] . '-' . $item['size'];
if (isset($items_by_unique[$unique])) {
$old_item = $items_by_unique[$unique];
$item['quantity'] = $old_item['quantity'];
}
if ($item['quantity'] > $available) {
$item['quantity'] = $available;
}
$items_by_unique[$unique] = $item;
}
$items_json = json_encode(array_values($items_by_unique));
The code has lots of issues that make very hard to find the mistakes and it's very hard to answer a question which is really several questions which are always increasing, as if we're making a debugging service for free... We could be discussing here for several hours and days, like a job, until everything is corrected. In that case, it's going to be very hard to help and take care of our personal lives and jobs.
Anyway, I'm going to enumerate some issues that make the code very hard to debug.
Most of the returned values are not validated, assuming that they're what's expected, instead failing immediately when there's an error. That means that you may only notice there's a mistake a lot later and hunt for the its source, which might be in a different file.
For instance, when you do something like this:
$query = $veza->prepare("SELECT * FROM products WHERE id = '$product_id'");
$query->execute();
$product = $query->fetch(PDO::FETCH_ASSOC);
You should always check if $product is at least not empty:
if (!$product) {
throw new RuntimeException("The product #$product_id" was not found.");
}
Also, putting variables inside SQL statements can be very dangerous. If you're using prepared statements you should do something like this:
$query = $veza->prepare("SELECT * FROM products WHERE id = ? LIMIT 1");
$query->execute([$product_id]);
The code does not take advantage of reusability. You can implement classes or functions and test them independently.
For instance, you could have done something like this:
<?php
/**
* Add a new item ...
*
* If it's being requested more items then available ...
*
* #param array $newItem The new item that should be added.
* #param array $items The list of items where the item should be added.
* #param integer $available Available items.
* #return void
*/
function add_item(array $newItem, array &$items, int $available=MAX_INT_MAX)
{
throw_error_if_invalid_item($newItem);
$unique = $newItem['id'] . '-' . $newItem['size'];
if (isset($items_by_unique[$unique])) {
add_item_quantity(
$items_by_unique[$unique],
$item['quantity'],
$available
);
} else {
$items[] = $newItem;
}
}
/**
* Add quantity ...
*
* #param array $item ...
* #param integer $moreQuantity ...
* #param integer $available ...
* #return void
*/
function add_item_quantity(array &$item, int $moreQuantity, int $available=MAX_INT_MAX)
{
$item['quantity'] += $moreQuantity;
if ($item['quantity'] > $available) {
$item['quantity'] = $available;
}
}
/**
* ...
*
* #param array $item ...
* #return void
*/
function throw_error_if_invalid_item(array $item)
{
if (!isset($item['id'], $item['size'], $item['quantity'])) {
throw new RuntimeException(
'Found a invalid invalid item data: ' . json_encode($item)
);
}
}
Then you can make individual test in isolated files:
<?php
$item = array(
'id' => 10,
'size' => 'm',
'quantity' => 2,
);
add_item_quantity($item, 3, 10);
if ($item['quantity'] != 5) {
echo "wrong! quantity = {$item['quantity']}\n";
} else {
echo "correct!\n";
}
If you put your classes or functions in dedicated files, you can reuse them as a library making the code easy to read, testable and secure:
<?php
throw_error_if_invalid_item($_POST);
$newItem = create_item($_POST);
$items = fetch_cart_items($cart_id);
add_item($newItem, $items, 10);
save_cart_items($items);
show_json_items($json);
With classes it would be much easier (eg: you wouldn't have to worry about missing array keys) and you could use PHPUnit to test all the functions and methods automatically. Check how I did that for a simple project:
https://github.com/pedroac/nonce4php
You can also make any error or warning halt the script:
<?php
set_error_handler(
function (int $errno , string $errstr, string $errfile, int $errline) {
http_response_code(500);
echo "ERROR #$errono:$errfile:$errline: $errstr";
die();
}
);
set_exception_handler(
function (Throwable $exception) {
http_response_code(500);
echo $exception->getMessage();
die();
}
);
If you follow the good practices, it will be much easier to found mistakes and let others help you.
I fixed this issue by casting the second argument of array_merge to an array:
$new_items = array_merge($item, (array)$previous_items);

Add exactly 1 product to cart programmatically in Magento

Using Magento 1.8.1, on the checkout page, I'm trying to add a product to the cart in the code. Here is the code I'm using:
$totals = Mage::getSingleton('checkout/cart')->getQuote()->getTotals();
$subtotal = $totals["subtotal"]->getValue();
$free_samples_prod_id = 1285;
if ( $subtotal >= 50 ) {
$this->addProduct($free_samples_prod_id, 1);
}
else{
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
foreach ($items as $item) {
if ($item->getProduct()->getId() == $free_samples_prod_id) {
$itemId = $item->getItemId();
$cartHelper->getCart()->removeItem($itemId)->save();
break;
}
}
}
The code is in: app\code\core\Mage\Checkout\Model\Cart.php under public function init()
The product does get added sucessfully, however, everytime somebody visits their cart page, the quantity increases by one. How can I modify that code so the quantity is always 1?
Thank you
Axel makes a very good point, but to answer your immediate question, why not test for the product's presence before you add it
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
$subtotal = $totals["subtotal"]->getValue();
$free_samples_prod_id = 1285;
if ( $subtotal >= 50 ) {
$alreadyAdded = false;
foreach ($items as $item) {
if($item->getId() == $free_samples_prod_id) { $alreadyAdded = true; break; }
}
if(!$alreadyAdded) { $this->addProduct($free_samples_prod_id, 1); }
}

Codeignighter Cart class base fee

I have a unique shop where some products incur a base fee, lets say
A photographer charges $20 for the first hour then $1 there-after.
I am passing a variable into my codeignighter cart ; so for 5 hours I would pass the variable into cart->insert();
$item['id'] = 1;
$item['qty'] = 5;
$item['base'] = 20.00;
I made some changes to the cart class so this would work and has been fine so far, what I now need and cant seem to figure this out is when there are options it considers it a different product and this fee is charged once per rowid.
I would like my class to only allow 1 charge for the item regardless of the various options.
Below are the three functions I created inside my Cart class
and I call set_base($item) in the _save_cart() function.
private function set_base($item)
{
if( $this->base_exist($item) )
{
return FALSE;
}
// Only allow the base cost for 1 row id, it doesnt matter which one, just one
$this->_base_indexes['rowid'][$item['id']] = $item['rowid'];
$this->_cart_contents['cart_total'] += $item['base'];
return TRUE;
}
private function base_exist($item)
{
if ( array_key_exists($item['id'] , $this->_base_indexes['applied']) )
{
if ( ( $item['rowid'] == $this->_base_indexes['applied'][$item['id']] ) )
{
return TRUE;
}
}
return FALSE;
}
private function base_reset()
{
$this->_base_indexes = array();
$this->_base_indexes['applied'] = array();
return $this->_base_indexes;
}
Inside _save_cart();
I call
$this->base_reset();
Inside the cart_contents() loop I have added;
if(isset($val['base']))
{
$this->set_base($val);
}
$this->_cart_contents['cart_total'] += ($val['price'] * $val['qty']);
Hope this was clear :/
OK i changed it a little bit,
the foreach loop in the save_cart function now looks like; and I can remove the three functions I had before.
foreach ($this->_cart_contents as $key => $val)
{
// We make sure the array contains the proper indexes
if ( ! is_array($val) OR ! isset($val['price']) OR ! isset($val['qty']))
{
continue;
}
if(isset($val['base']))
{
//If it doesnt exist, add the fee
if (!(isset($this->_base_indexes[$val['id']]) == $val['rowid']) )
{
$this->_base_indexes[$val['id']] = $val['rowid'];
$this->_cart_contents['cart_total'] += $val['base'];
$sub = ($this->_cart_contents[$key]['price'] * $this->_cart_contents[$key]['qty']) + $val['base'];
}
else
{
//$this->_cart_contents[$key]['base'] = 0;
$sub = ($this->_cart_contents[$key]['price'] * $this->_cart_contents[$key]['qty']);
}
}
$this->_cart_contents['cart_total'] += ($val['price'] * $val['qty']);
$this->_cart_contents['total_items'] += $val['qty'];
$this->_cart_contents[$key]['subtotal'] = $sub;
}

Categories