FleetCart/Themes/Storefront/Http/Controllers/ProductIndexController.php

89 lines
2.5 KiB
PHP
Raw Normal View History

2023-06-11 12:14:03 +00:00
<?php
namespace Themes\Storefront\Http\Controllers;
use Illuminate\Support\Collection;
use Modules\Product\RecentlyViewed;
use Modules\Product\Entities\Product;
use Modules\Category\Entities\Category;
class ProductIndexController
{
private $recentlyViewed;
2023-12-03 14:07:47 +00:00
2023-06-11 12:14:03 +00:00
public function __construct(RecentlyViewed $recentlyViewed)
{
$this->recentlyViewed = $recentlyViewed;
}
2023-12-03 14:07:47 +00:00
2023-06-11 12:14:03 +00:00
protected function getProducts($settingPrefix)
{
$type = setting("{$settingPrefix}_product_type", 'custom_products');
$limit = setting("{$settingPrefix}_products_limit");
if ($type === 'category_products') {
2023-12-03 14:07:47 +00:00
return $this->categoryProducts($settingPrefix, $limit);
2023-06-11 12:14:03 +00:00
}
if ($type === 'recently_viewed_products') {
return $this->recentlyViewedProducts($limit);
}
return Product::forCard()
->when($type === 'latest_products', $this->latestProductsCallback($limit))
->when($type === 'custom_products', $this->customProductsCallback($settingPrefix))
->get()
->map
->clean();
}
2023-12-03 14:07:47 +00:00
private function categoryProducts($settingPrefix, $limit)
2023-06-11 12:14:03 +00:00
{
return Category::findOrNew(setting("{$settingPrefix}_category_id"))
->products()
->forCard()
->take($limit)
->get();
}
2023-12-03 14:07:47 +00:00
2023-06-11 12:14:03 +00:00
private function recentlyViewedProducts($limit)
{
return collect($this->recentlyViewed->products())
->reverse()
2023-12-03 14:07:47 +00:00
->when(!is_null($limit), function (Collection $products) use ($limit) {
2023-06-11 12:14:03 +00:00
return $products->take($limit);
})
->values();
}
2023-12-03 14:07:47 +00:00
2023-06-11 12:14:03 +00:00
private function latestProductsCallback($limit)
{
return function ($query) use ($limit) {
$query->latest()
2023-12-03 14:07:47 +00:00
->when(!is_null($limit), function ($q) use ($limit) {
2023-06-11 12:14:03 +00:00
$q->limit($limit);
});
};
}
2023-12-03 14:07:47 +00:00
2023-06-11 12:14:03 +00:00
private function customProductsCallback($settingPrefix)
{
return function ($query) use ($settingPrefix) {
$productIds = setting("{$settingPrefix}_products", []);
$query->whereIn('id', $productIds)
2023-12-03 14:07:47 +00:00
->when(!empty($productIds), function ($q) use ($productIds) {
2023-06-11 12:14:03 +00:00
$productIdsString = collect($productIds)->filter()->implode(',');
$q->orderByRaw("FIELD(id, {$productIdsString})");
});
};
}
}