| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCart\App\Modules\Data; |
| 4 |
|
| 5 |
use FluentCart\App\CPT\FluentProducts; |
| 6 |
use FluentCart\App\Models\Product; |
| 7 |
|
| 8 |
class ProductDataSetup |
| 9 |
{ |
| 10 |
|
| 11 |
protected static $productsCache = []; |
| 12 |
|
| 13 |
public function boot() |
| 14 |
{ |
| 15 |
static $booted = false; |
| 16 |
|
| 17 |
if ($booted) { |
| 18 |
return; |
| 19 |
} |
| 20 |
|
| 21 |
add_action('the_post', [$this, 'maybeSetupProductData'], 1); |
| 22 |
$booted = true; |
| 23 |
} |
| 24 |
|
| 25 |
public function maybeSetupProductData($post) |
| 26 |
{ |
| 27 |
unset($GLOBALS['fct_product']); |
| 28 |
|
| 29 |
if (is_int($post)) { |
| 30 |
$post = get_post($post); |
| 31 |
} |
| 32 |
|
| 33 |
if (empty($post->post_type) || $post->post_type !== FluentProducts::CPT_NAME) { |
| 34 |
return $post; |
| 35 |
} |
| 36 |
|
| 37 |
$GLOBALS['fct_product'] = self::getProductModel($post->ID); |
| 38 |
|
| 39 |
return $post; |
| 40 |
} |
| 41 |
|
| 42 |
public static function getProductModel($postId) |
| 43 |
{ |
| 44 |
if (isset(self::$productsCache[$postId])) { |
| 45 |
return self::$productsCache[$postId]; |
| 46 |
} |
| 47 |
|
| 48 |
$product = Product::query()->find($postId); |
| 49 |
|
| 50 |
if ($product) { |
| 51 |
self::$productsCache[$postId] = $product; |
| 52 |
} |
| 53 |
|
| 54 |
return $product; |
| 55 |
} |
| 56 |
|
| 57 |
public static function setProductsCache($products) |
| 58 |
{ |
| 59 |
foreach ($products as $product) { |
| 60 |
self::$productsCache[$product->ID] = $product; |
| 61 |
} |
| 62 |
} |
| 63 |
} |
| 64 |
|