| 1 |
<?php |
| 2 |
|
| 3 |
namespace StoreEngine\Classes; |
| 4 |
|
| 5 |
use StoreEngine\Classes\Product\BundledProduct; |
| 6 |
use StoreEngine\Classes\Product\SimpleProduct; |
| 7 |
use StoreEngine\Classes\Product\VariableProduct; |
| 8 |
|
| 9 |
if ( ! defined( 'ABSPATH' ) ) { |
| 10 |
exit; |
| 11 |
} |
| 12 |
|
| 13 |
class ProductFactory { |
| 14 |
|
| 15 |
/** |
| 16 |
* @param int $product_id |
| 17 |
* |
| 18 |
* @return false|SimpleProduct|VariableProduct|BundledProduct |
| 19 |
*/ |
| 20 |
public function get_product( int $product_id = 0 ) { |
| 21 |
try { |
| 22 |
$product_type = get_post_meta( $product_id, '_storeengine_product_type', true ) ?? 'simple'; |
| 23 |
$classname = self::get_product_classname( $product_id, $product_type ); |
| 24 |
$product = new $classname( $product_id ); |
| 25 |
|
| 26 |
return $product->get_id() ? $product : false; |
| 27 |
} catch ( \Exception $e ) { |
| 28 |
return false; |
| 29 |
} |
| 30 |
} |
| 31 |
|
| 32 |
/** |
| 33 |
* @param int $product_id |
| 34 |
* @param string|null $product_type |
| 35 |
* |
| 36 |
* @return AbstractProduct |
| 37 |
*/ |
| 38 |
public static function getProduct( int $product_id = 0, string $product_type = null ) { |
| 39 |
if ( ! $product_type ) { |
| 40 |
$product_type = get_post_meta( $product_id, '_storeengine_product_type', true ) ?? 'simple'; |
| 41 |
} |
| 42 |
|
| 43 |
$classname = self::get_product_classname( $product_id, $product_type ); |
| 44 |
|
| 45 |
return new $classname( $product_id ); |
| 46 |
} |
| 47 |
|
| 48 |
public function get_product_by_price_id( int $price_id ) { |
| 49 |
global $wpdb; |
| 50 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching |
| 51 |
$product_id = $wpdb->get_var( $wpdb->prepare( "SELECT product_id FROM {$wpdb->prefix}storeengine_product_price WHERE id = %d", $price_id ) ); |
| 52 |
if ( ! $product_id ) { |
| 53 |
return false; |
| 54 |
} |
| 55 |
|
| 56 |
return $this->get_product( $product_id ); |
| 57 |
} |
| 58 |
|
| 59 |
public static function get_product_classname( $product_id, $product_type ) { |
| 60 |
$class_names = apply_filters( 'storeengine/product_classes', [ |
| 61 |
'simple' => SimpleProduct::class, |
| 62 |
'variable' => VariableProduct::class, |
| 63 |
'bundled' => BundledProduct::class, |
| 64 |
] ); |
| 65 |
|
| 66 |
$classname = apply_filters( 'storeengine/product/get_classname', $class_names[ $product_type ] ?? null, $product_id, $product_type ); |
| 67 |
|
| 68 |
if ( ! $classname || ! class_exists( $classname ) ) { |
| 69 |
$classname = SimpleProduct::class; |
| 70 |
} |
| 71 |
|
| 72 |
return $classname; |
| 73 |
} |
| 74 |
} |
| 75 |
|