| 1 |
<?php |
| 2 |
|
| 3 |
namespace SyncBasalam\Admin\Product\Data; |
| 4 |
|
| 5 |
use SyncBasalam\Admin\Product\Data\Strategies\DataStrategyInterface; |
| 6 |
use SyncBasalam\Admin\Product\Data\Validators\ValidatorChain; |
| 7 |
use SyncBasalam\Admin\Product\ProductDataFactory; |
| 8 |
|
| 9 |
defined('ABSPATH') || exit; |
| 10 |
|
| 11 |
class ProductDataBuilder |
| 12 |
{ |
| 13 |
private array $data = []; |
| 14 |
private $validator; |
| 15 |
private $factory; |
| 16 |
private DataStrategyInterface $strategy; |
| 17 |
|
| 18 |
public function __construct( |
| 19 |
?ValidatorChain $validator, |
| 20 |
ProductDataFactory $factory |
| 21 |
) { |
| 22 |
$this->validator = $validator; |
| 23 |
$this->factory = $factory; |
| 24 |
$this->initializeData(); |
| 25 |
} |
| 26 |
|
| 27 |
public function setStrategy(DataStrategyInterface $strategy): self |
| 28 |
{ |
| 29 |
$this->strategy = $strategy; |
| 30 |
return $this; |
| 31 |
} |
| 32 |
|
| 33 |
public function fromWooProduct(int $productId): self |
| 34 |
{ |
| 35 |
$product = wc_get_product($productId); |
| 36 |
|
| 37 |
if (!$product) throw new \InvalidArgumentException(esc_html("Product with ID {$productId} not found")); |
| 38 |
|
| 39 |
// Validate product first |
| 40 |
if ($this->validator) $this->validator->validate($product); |
| 41 |
|
| 42 |
// Use factory to get appropriate data handler |
| 43 |
$handler = $this->factory->createHandler($product); |
| 44 |
|
| 45 |
// Apply strategy to collect data |
| 46 |
$this->data = $this->strategy->collect($product, $handler); |
| 47 |
|
| 48 |
return $this; |
| 49 |
} |
| 50 |
|
| 51 |
public function withCategoryIds(array $categoryIds = null): self |
| 52 |
{ |
| 53 |
if ($categoryIds !== null) $this->data['category_ids'] = $categoryIds; |
| 54 |
return $this; |
| 55 |
} |
| 56 |
|
| 57 |
public function build(): array |
| 58 |
{ |
| 59 |
return $this->data; |
| 60 |
} |
| 61 |
|
| 62 |
public function reset(): self |
| 63 |
{ |
| 64 |
$this->initializeData(); |
| 65 |
return $this; |
| 66 |
} |
| 67 |
|
| 68 |
private function initializeData(): void |
| 69 |
{ |
| 70 |
$this->data = [ |
| 71 |
'name' => '', |
| 72 |
'sku' => null, |
| 73 |
'description' => '', |
| 74 |
'category_id' => null, |
| 75 |
'category_ids' => [], |
| 76 |
'primary_price' => null, |
| 77 |
'stock' => null, |
| 78 |
'weight' => null, |
| 79 |
'package_weight' => null, |
| 80 |
'photo' => null, |
| 81 |
'photos' => [], |
| 82 |
'preparation_days' => null, |
| 83 |
'unit_type' => 6304, |
| 84 |
'unit_quantity' => 1, |
| 85 |
'is_wholesale' => false, |
| 86 |
'variants' => [], |
| 87 |
'product_attribute' => [], |
| 88 |
]; |
| 89 |
} |
| 90 |
} |
| 91 |
|