Your code snippet includes a TODO comment about verifying inventory availability before accepting items as valid order items. This is important to prevent users from ordering more items than are available in stock.
Where to check inventory availability?
In your current code, the natural place to check inventory quantities is inside the getValidOrderItems() method, since this is where you validate cart item data against the current product data from the database.
How to do inventory validation?
From your example data:
$item (cart item) contains 'available_quantity'.
$product (from DB) contains 'quantity' which appears to be stock available.
Proposed updated getValidOrderItems() snippet including inventory check:
php
User
code
protected function getValidOrderItems(array $cartItems): array
{
$productIds = array_column($cartItems, 'id');
$this->logDebug("Get Valid Order Item, product IDs extracted", ['product IDs' => $productIds]);
$products = Content::find()
->id($productIds)
->ofType('product')
->indexBy('id')
->asArray()
->all();
$this->logDebug("Get Valid Order Item, products fetched from DB", ['products' => $products]);
$validItems = [];
foreach ($cartItems as $item)
{
$productId = $item['id'] ?? null;
if (!$productId || !isset($products[$productId]))
{
$this->logDebug(
"Get Valid Order Item, skipping invalid or missing product ID",
['product IDs' => $productId]
);
continue;
}
$product = $products[$productId];
$requestedQuantity = max(1, (int) ($item['quantity'] ?? 1));
// Check available quantities in inventory
// available_quantity might come from cart or session or elsewhere and product['quantity'] is DB stock.
$availableQuantity = (int) ($item['available_quantity'] ?? 0);
$productQuantity = (int) ($product['quantity'] ?? 0);
$maxAvailable = min($availableQuantity, $productQuantity);
if ($requestedQuantity > $maxAvailable)
{
$this->logDebug(
"Get Valid Order Item, requested quantity exceeds available stock",
[
'product_id' => $productId,
'requested_quantity' => $requestedQuantity,
'available_quantity_cart' => $availableQuantity,
'available_quantity_product' => $productQuantity,
]
);
// Adjust requested quantity to max available or skip if none available
if ($maxAvailable > 0) {
$requestedQuantity = $maxAvailable;
} else {
continue;
}
}
if ($requestedQuantity === 0)
{
$this->logDebug(
"Get Valid Order Item, skipping zero quantity for product ID",
['product IDs' => $productId]
);
continue;
}
$validItems[] = [
'product' => $product,
'cart' => $item,
'quantity' => $requestedQuantity,
];
}
$this->logDebug("Get Valid Order Item, valided items", ['items' => $validItems]);
return $validItems;
}
Assistant
Yes, that clarification helps a lot!
To recap with your clarification:
$item is from the user cart (client state, e.g. session, saved cart).
$product is from the product inventory database (authoritative stock).
What you want:
Validate that the user is not requesting more than the true available stock.
Available stock is the current saved inventory quantity in $product['quantity'].
$item['available_quantity'] might reflect what the cart thinks is available, e.g. session or client-side cache, but is unreliable / non-authoritative.
So, you should trust $product['quantity'] as the "source of truth" for stock.
Adjusted suggestion based on that:
php
$requestedQuantity = max(1, (int) ($item['quantity'] ?? 1));
// Product quantity from inventory DB is authoritative
$productQuantity = (int) ($product['quantity'] ?? 0);
if ($requestedQuantity > $productQuantity)
{
$this->logDebug(
"Get Valid Order Item, requested quantity exceeds available stock",
[
'product_id' => $productId,
'requested_quantity' => $requestedQuantity,
'available_quantity_product' => $productQuantity,
]
);
if ($productQuantity > 0) {
$requestedQuantity = $productQuantity;
} else {
// No stock, skip this product
continue;
}
}
We only check requested quantity against $product['quantity'].
We ignore $item['available_quantity'] because it could be stale or tampered with.
If quantity requested exceeds the stock, we clamp it or skip.
Why ignore $item['available_quantity']?
User cart data can be stale or manipulated.
Only trust DB inventory, which is updated by your system.
You want to prevent overselling by enforcing this check on server side.
Summary
Your final inventory check in the validation should primarily rely on the stock in the database ($product['quantity']).
The $item from the cart provides the requestedQuantity (what the user wants).
If requestedQuantity > productQuantity, clamp the requested quantity or skip.
This makes the check robust and avoids depending on potentially incorrect cart-side stock info.
Let me know if you want me to revise the entire method or add anything else!
User
code
$requestedQuantity = max(1, (int) ($item['quantity'] ?? 1));
// Product quantity from inventory DB is authoritative
$productQuantity = (int) ($product['quantity'] ?? 0);
if ($requestedQuantity > $productQuantity)
{
$this->logDebug(
"Get Valid Order Item, requested quantity exceeds available stock",
[
'product_id' => $productId,
'requested_quantity' => $requestedQuantity,
'available_quantity_product' => $productQuantity,
]
);
if ($productQuantity > 0)
{
$requestedQuantity = $productQuantity;
}
else
{
// No stock, skip this product
continue;
}
}
should it not be >= ?
Assistant
Great question!
Let's carefully consider whether to use > or >= in this check:
php
if ($requestedQuantity > $productQuantity)
{
// ...
}
What does > mean here?
The condition triggers only if requested quantity is strictly greater than available stock.
That means if requested quantity equals available stock, it will not adjust the quantity.
What about >=?
php
if ($requestedQuantity >= $productQuantity)
{
// ...
}
This triggers if requested quantity is equal to or greater than available stock.
That means if requested quantity equals product stock, you enter the if-block.
Which check is correct?
Your goal is to allow orders up to and including the available stock.
So if requestedQuantityequals available stock (productQuantity), that should be valid and no adjustment needed.
For example, if you have 4 units in stock, ordering exactly 4 units is allowed.
Hence:
You do NOT want to clamp or skip when quantities are equal.
You only want to act when requested quantity exceeds stock.
Therefore
The existing check is correct:
php
if ($requestedQuantity > $productQuantity)
{
// Adjust or skip
}
Summary
Use > operator because you want to act only if requested quantity is greater than stock.
If requested quantity equals stock, it is valid.
Bonus: Ensure product quantity is never negative
Just make sure the $productQuantity is non-negative (which your cast (int) covers), so no edge cases.
Let me know if you'd like me to explain further or cover edge cases!
User
ahh because of the zero factor
Assistant
Exactly! The key point is that ordering exactly the amount available (say 4 units in stock, and user requests 4) is perfectly valid and should pass without adjustment.
The check:
php
if ($requestedQuantity > $productQuantity)
only triggers if the user asks for more than the available stock, e.g. requests 5 when only 4 are available.
If requestedQuantity == 0 or productQuantity == 0, your earlier logic catches that case separately (like skipping or adjusting). So this line only guards the scenario where the requested quantity is strictly too high.
Recap:
User requests 4, stock is 4 → allowed
User requests 5, stock is 4 → adjust to 4 or skip
User requests 0, stock is 4 → handled elsewhere (max(1, ...) usually sets to 1)
Stock is 0 → skip
So > is the right comparison here.
Let me know if you want to dive into other edge cases!
User
public function getStripeLineItems(): array
{
if (this->_cachedOrderItems === null)
{
// Lazy-load and cache
this->_cachedOrderItems = $this->orderItems;
code
$this->logDebug(
"Get Stripe Line Items, loaded orderItems",
['orderItems' => $this->_cachedOrderItems]
);
}
$lineItems = [];
foreach ($this->_cachedOrderItems as $orderItem)
{
$itemOrderId = $orderItem->order_id;
$itemQuantity = $orderItem->quantity;
$itemUnitPrice = $orderItem->unit_price;
$itemTitle = $orderItem->product_title;
$itemDescription = $orderItem->meta_description;
$itemPIO = $orderItem->product_image_one;
$this->logDebug("Get Stripe Line Items, processing orderItem ID", [
'order ID' => $itemOrderId,
'order quantity' => $itemQuantity,
'order unit price' => $itemUnitPrice
]);
if ($orderItem->quantity <= 0)
{
$this->logDebug("Get Stripe Line Items, skipped quantity <= 0");
continue;
}
// Calculate total price = quantity × unit price (products of your stored values)
$totalPrice = $itemUnitPrice * $itemQuantity;
$this->logDebug("Get Stripe Line Items, skipped total price", ['total price' => $totalPrice]);
if ($totalPrice <= 0)
{
$this->logDebug("Get Stripe Line Items, skip, total price <= 0");
continue;
}
// For Stripe, amount is in cents (integer)
$unitAmount = (int) round($totalPrice / $itemQuantity);
$this->logDebug(
"Get Stripe Line Items, unit amount(rounded)",
['unit amount(rounded)' => $unitAmount]
);
if ($unitAmount <= 0)
{
$this->logDebug("Get Stripe Line Items, skipped unit amount <= 0");
continue;
}
/**
* For currencies without cents
* Some currencies do not have minor units (e.g. Japanese Yen JPY).
* In that case, the amount is just the integer without multiplying by 100.
*
$formattedPrice = MoneyHelper::getIntl($totalPrice);
$this->logDebug("Get Stripe Line Items, formatted Price", ['price' => $formattedPrice]);//*/
$lineItems[] = [
'price_data' => [
'currency' => $this->_formatter->currencyCode(),
'unit_amount' => $unitAmount,
'product_data' => [
'name' => $itemTitle,
'description' => $itemDescription,
'images' => [$itemPIO],
],
],
'quantity' => $itemQuantity,
];
}
var_dump($lineItems);die;
$this->logDebug("Get Stripe Line Items, stripe line items", ['line items' => $lineItems]);
return $lineItems;
}
Assistant
Good observation!
The notation you see:
php
'product_data' =>
array (size=3)
...
is coming from your debugger or var_dump output indicating there is an array here with 3 elements, but it’s not printing the actual key=>value pairs in the snippet you posted (probably truncated or elided with ...).
So that ... means:
The debugger is summarizing and not showing the full content inside product_data in your snippet.
It's not a literal value in your data; it's just an incomplete sample in the output you pasted.
How to confirm:
You can try printing or logging the line items with more verbose output, e.g.:
From your code, it has 3 elements exactly, matching what the var_dump reports.
To summarize:
The ... is just shortened output caused by your output tool/truncation, not an actual value.
Your product_data array does exist with three keys as expected.
No issue with code or data structure here as per the snippet.
If the truncated output confuses you or you want to see full nested arrays in var_dump:
Try increasing your debug output depth (some PHP debuggers truncate deep output).
Alternatively, debug with print_r() or json_encode() as shown above.
Also, make sure no custom error handlers or log formatters sanitize/shorten array output.
If you want, I can help you format a debug print that ensures full output readability!
User
if (this->__sessionUser->writeSession([
'extra_data' => [
//'last_login_time' => time(),
'order_reference_id' => orderReferenceId,
'order_success_id' => orderSuccessId,′ordercancelid′=>orderCancelId,
],
// Optionally, you can pass existing cart_data to keep it synced.
]))
{
throw new YiiBaseException('Failed to store guest order IDs');
}
how do I add to array with removing other data?
Assistant
You have code that calls:
php
$this->__sessionUser->writeSession([
'extra_data' => [
//'last_login_time' => time(),
'order_reference_id' => $orderReferenceId,
'order_success_id' => $orderSuccessId,
'order_cancel_id' => $orderCancelId,
],
// Optionally, you can pass existing cart_data to keep it synced.
])
But you want to add/merge to the existing extra_data array in session, without removing other existing keys inside extra_data.
will overwrite the entire extra_data array in the session, removing any other keys that were previously stored under extra_data.
The solution
You need to:
Read the existing extra_data from the session first.
Merge your new keys in (adding or overwriting only these specific fields).
Write back the merged array to extra_data in the session.
Example:
php
// Step 1: Read existing extra_data or default to empty array
$existingExtraData = $this->__sessionUser->readSession('extra_data') ?? [];
// Step 2: Prepare new data you want to add
$newData = [
'order_reference_id' => $orderReferenceId,
'order_success_id' => $orderSuccessId,
'order_cancel_id' => $orderCancelId,
];
// Step 3: Merge new data into existing
$mergedExtraData = array_merge($existingExtraData, $newData);
// Step 4: Write back merged extra_data to session
if (!$this->__sessionUser->writeSession([
'extra_data' => $mergedExtraData,
])) {
throw new YiiBaseException('Failed to store guest order IDs');
}
User
so like:
sessionData=this->__sessionUser->readSession();
code
if ($sessionData !== null)
{
$newData = [
'order_reference_id' => $orderReferenceId,
'order_success_id' => $orderSuccessId,
'order_cancel_id' => $orderCancelId,
];
$mergedExtraData = array_merge($existingExtraData, $newData);
if ($this->__sessionUser->writeSession(['extra_data' => $mergedExtraData]))
{
throw new YiiBaseException('Failed to store guest order IDs');
}
}
Assistant
You're almost there — just a couple things to fix!
Your code here:
php
$sessionData = $this->__sessionUser->readSession();
if ($sessionData !== null)
{
$newData = [
'order_reference_id' => $orderReferenceId,
'order_success_id' => $orderSuccessId,
'order_cancel_id' => $orderCancelId,
];
$mergedExtraData = array_merge($existingExtraData, $newData);
if ($this->__sessionUser->writeSession(['extra_data' => $mergedExtraData]))
{
throw new YiiBaseException('Failed to store guest order IDs');
}
}
What to correct:
You used $existingExtraData but never defined it.
You need to extract existing extra_data from $sessionData:
protected function getValidOrderItems(array $cartItems): array
{
$productIds = array_column($cartItems, 'id');
$this->logDebug("Get Valid Order Item, product IDs extracted", ['product IDs' => $productIds]);
$products = Content::find()
->id($productIds)
->ofType('product')
->indexBy('id')
->asArray()
->all();
$this->logDebug("Get Valid Order Item, products fetched from DB", ['products' => $products]);
$validItems = [];
foreach ($cartItems as $item)
{
$productId = $item['id'] ?? null;
if (!$productId || !isset($products[$productId]))
{
$this->logDebug(
"Get Valid Order Item, skipping invalid or missing product ID",
['product IDs' => $productId]
);
continue;
}
$product = $products[$productId];
$requestedQuantity = max(1, (int) ($item['quantity'] ?? 1));
// Check available quantities in inventory
// available_quantity might come from cart or session or elsewhere and product['quantity'] is DB stock.
$availableQuantity = (int) ($item['available_quantity'] ?? 0);
$productQuantity = (int) ($product['quantity'] ?? 0);
$maxAvailable = min($availableQuantity, $productQuantity);
if ($requestedQuantity > $maxAvailable)
{
$this->logDebug(
"Get Valid Order Item, requested quantity exceeds available stock",
[
'product_id' => $productId,
'requested_quantity' => $requestedQuantity,
'available_quantity_cart' => $availableQuantity,
'available_quantity_product' => $productQuantity,
]
);
// Adjust requested quantity to max available or skip if none available
if ($maxAvailable > 0) {
$requestedQuantity = $maxAvailable;
} else {
continue;
}
}
if ($requestedQuantity === 0)
{
$this->logDebug(
"Get Valid Order Item, skipping zero quantity for product ID",
['product IDs' => $productId]
);
continue;
}
$validItems[] = [
'product' => $product,
'cart' => $item,
'quantity' => $requestedQuantity,
];
}
$this->logDebug("Get Valid Order Item, valided items", ['items' => $validItems]);
return $validItems;
}
Explanation
Extracts $availableQuantity from the cart item; if absent assumes 0.
Extracts $productQuantity from the DB product.
Computes the minimum of these as $maxAvailable.
If the requested quantity exceeds $maxAvailable, it either adjusts it (to $maxAvailable if > 0) or skips the item.
This way, you prevent overselling.
Logs info for debugging.
Other notes
Your $product['quantity'] seems to be the current stock.
$item['available_quantity'] presumably reflects what the cart or session believes is still available.
This code handles the case where either source limits the available amount.
Summary
Add inventory validation in getValidOrderItems().
Compare requested vs available stock.
Adjust or skip cart items accordingly.
Log any changes for audit/debug.
This way you prevent creating order items with invalid quantities exceeding current inventory.
code
$requestedQuantity = max(1, (int) ($item['quantity'] ?? 1));
// Check available quantities in inventory
// available_quantity might come from cart or session or elsewhere and product['quantity'] is DB stock.
$availableQuantity = (int) ($item['available_quantity'] ?? 0);
$productQuantity = (int) ($product['quantity'] ?? 0);
$maxAvailable = min($availableQuantity, $productQuantity);
looking at this snippet you suggested, itemisfromtheusercart.product = products[productId]; is from the product inventory.
hopefully that clears things up