| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCart\App\Services; |
| 4 |
|
| 5 |
use FluentCart\App\Helpers\CartHelper; |
| 6 |
use FluentCart\App\Models\OrderItem; |
| 7 |
use FluentCart\App\Models\Product; |
| 8 |
use FluentCart\App\Models\ProductVariation; |
| 9 |
use FluentCart\Framework\Support\Arr; |
| 10 |
|
| 11 |
class ProductItemService |
| 12 |
{ |
| 13 |
/** |
| 14 |
* Return product and variation item (custom or normal) |
| 15 |
* |
| 16 |
* @param array $data |
| 17 |
* @return object|null |
| 18 |
*/ |
| 19 |
public static function getItem(array $data) |
| 20 |
{ |
| 21 |
$orderId = Arr::get($data, 'order_id'); |
| 22 |
$variationId = Arr::get($data, 'variation_id'); |
| 23 |
$productId = Arr::get($data, 'product_id'); |
| 24 |
|
| 25 |
if (!$orderId || !$productId || !$variationId) { |
| 26 |
return null; |
| 27 |
} |
| 28 |
|
| 29 |
$orderItem = OrderItem::query() |
| 30 |
->where('order_id', $orderId) |
| 31 |
->where('post_id', $productId) |
| 32 |
->where('object_id', $variationId) |
| 33 |
->first(); |
| 34 |
|
| 35 |
$isCustom = $orderItem |
| 36 |
? in_array( |
| 37 |
strtolower((string) $orderItem->is_custom), |
| 38 |
['1', 'true'], |
| 39 |
true |
| 40 |
) |
| 41 |
: false; |
| 42 |
|
| 43 |
// Custom item from external source |
| 44 |
if ($orderItem && $isCustom) { |
| 45 |
$product = (object) [ |
| 46 |
'ID' => $productId, |
| 47 |
'post_title' => Arr::get($orderItem, 'post_title', ''), |
| 48 |
]; |
| 49 |
|
| 50 |
$variation = $orderItem; |
| 51 |
$variation->id = $orderItem->object_id; |
| 52 |
|
| 53 |
[$product, $variation] = apply_filters( |
| 54 |
'fluent_cart/payment/validate_custom_item', |
| 55 |
[$product, $variation], |
| 56 |
$data |
| 57 |
); |
| 58 |
|
| 59 |
if (!is_object($product) || !is_object($variation)) { |
| 60 |
return null; |
| 61 |
} |
| 62 |
|
| 63 |
$variation = CartHelper::normalizeCustomFields($variation); |
| 64 |
|
| 65 |
} |
| 66 |
else { |
| 67 |
$variation = ProductVariation::query()->find($variationId); |
| 68 |
$variation = apply_filters('fluent_cart/cart/item_modify', $variation, [ |
| 69 |
'item_id' => $variationId, |
| 70 |
'quantity' => $orderItem ? $orderItem->quantity : 0, |
| 71 |
]); |
| 72 |
$product = Product::query()->find($productId); |
| 73 |
} |
| 74 |
|
| 75 |
if (!$product || !$variation) { |
| 76 |
return null; |
| 77 |
} |
| 78 |
|
| 79 |
return (object) [ |
| 80 |
'product' => $product, |
| 81 |
'variation' => $variation, |
| 82 |
'is_custom' => $isCustom, |
| 83 |
]; |
| 84 |
} |
| 85 |
} |
| 86 |
|