| 1 |
<?php |
| 2 |
|
| 3 |
namespace SyncBasalam\Admin\Product\Data; |
| 4 |
|
| 5 |
use SyncBasalam\Admin\Product\Data\Validators\ValidatorChain; |
| 6 |
use SyncBasalam\Admin\Product\Data\Validators\ImageValidator; |
| 7 |
use SyncBasalam\Admin\Product\Data\Validators\ProductExistenceValidator; |
| 8 |
use SyncBasalam\Admin\Product\Data\Validators\ProductStatusValidator; |
| 9 |
use SyncBasalam\Admin\Product\Data\Validators\WeightValidator; |
| 10 |
use SyncBasalam\Admin\Product\ProductDataFactory; |
| 11 |
use SyncBasalam\Admin\Settings\SettingsConfig; |
| 12 |
use SyncBasalam\Admin\Settings\SettingsManager; |
| 13 |
use SyncBasalam\Jobs\Exceptions\NonRetryableException; |
| 14 |
use SyncBasalam\Utilities\ProductMetaKey; |
| 15 |
|
| 16 |
defined('ABSPATH') || exit; |
| 17 |
|
| 18 |
class ProductDataFacade |
| 19 |
{ |
| 20 |
private static $builder = null; |
| 21 |
private static $factory = null; |
| 22 |
private static $validator = null; |
| 23 |
|
| 24 |
private static function initialize(): void |
| 25 |
{ |
| 26 |
if (self::$builder === null) { |
| 27 |
self::$factory = new ProductDataFactory(); |
| 28 |
self::$validator = new ValidatorChain(); |
| 29 |
|
| 30 |
self::$validator->add(new ProductExistenceValidator()) |
| 31 |
->add(new ProductStatusValidator()) |
| 32 |
->add(new ImageValidator()) |
| 33 |
->add(new WeightValidator()); |
| 34 |
|
| 35 |
self::$builder = new ProductDataBuilder(self::$validator, self::$factory); |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
public static function get(int $productId, ?array $categoryIds = null): array |
| 40 |
{ |
| 41 |
self::initialize(); |
| 42 |
|
| 43 |
$product = wc_get_product($productId); |
| 44 |
if (!$product) throw new \InvalidArgumentException(esc_html("Product with ID {$productId} not found")); |
| 45 |
|
| 46 |
$basalamProductId = get_post_meta($productId, ProductMetaKey::basalamProductId(), true); |
| 47 |
$isUpdate = !empty($basalamProductId); |
| 48 |
|
| 49 |
$settings = SettingsManager::getSettings(); |
| 50 |
$syncFields = $settings[SettingsConfig::SYNC_PRODUCT_FIELDS] ?? 'all'; |
| 51 |
|
| 52 |
if ($isUpdate && !SettingsManager::isProductUpdateSelectionValid($settings)) { |
| 53 |
throw NonRetryableException::invalidData(SettingsConfig::CUSTOM_PRODUCT_UPDATE_REQUIRED_MESSAGE); |
| 54 |
} |
| 55 |
|
| 56 |
$strategy = 'create'; |
| 57 |
if ($isUpdate) { |
| 58 |
if ($syncFields === 'price_stock') $strategy = 'quick_update'; |
| 59 |
elseif ($syncFields === 'custom') $strategy = 'custom_update'; |
| 60 |
else $strategy = 'update'; |
| 61 |
} |
| 62 |
|
| 63 |
return self::$builder |
| 64 |
->reset() |
| 65 |
->setStrategy(self::$factory->createStrategy($strategy)) |
| 66 |
->fromWooProduct($productId) |
| 67 |
->withCategoryIds($categoryIds) |
| 68 |
->build(); |
| 69 |
} |
| 70 |
|
| 71 |
public static function validateProduct($product): void |
| 72 |
{ |
| 73 |
self::initialize(); |
| 74 |
self::$validator->validate($product); |
| 75 |
} |
| 76 |
} |
| 77 |
|