|
- <?php
-
- namespace common\logic\Distribution\ProductDistribution;
-
- use common\logic\BaseService;
- use common\logic\BuilderInterface;
- use common\logic\Distribution\Distribution\Distribution;
- use common\logic\Distribution\Distribution\DistributionSolver;
- use common\logic\Product\Product\Product;
-
- class ProductDistributionBuilder extends BaseService implements BuilderInterface
- {
- protected ProductDistributionRepository $productDistributionRepository;
- protected DistributionSolver $distributionSolver;
-
- public function __construct()
- {
- $this->productDistributionRepository = $this->loadService(ProductDistributionRepository::class);
- $this->distributionSolver = $this->loadService(DistributionSolver::class);
- }
-
- public function instanciate(Distribution $distribution, Product $product): ProductDistribution
- {
- $productDistribution = new ProductDistribution();
-
- $productDistribution->populateRelation('distribution', $distribution);
- $productDistribution->id_distribution = $distribution->id;
-
- $productDistribution->populateRelation('product', $product);
- $productDistribution->id_product = $product->id;
-
- return $productDistribution;
- }
-
- public function create(Distribution $distribution, Product $product): ProductDistribution
- {
- $productDistribution = $this->instanciate($distribution, $product);
-
- $this
- ->initActive($productDistribution)
- ->initQuantityMax($productDistribution);
-
- $productDistribution->save();
-
- return $productDistribution;
- }
-
- public function createIfNotExist(Distribution $distribution, Product $product): ProductDistribution
- {
- $productDistribution = $this->productDistributionRepository->getOne($distribution, $product);
-
- if(!$productDistribution) {
- $productDistribution = $this->create($distribution, $product);
- }
-
- return $productDistribution;
- }
-
- public function initActive(ProductDistribution $productDistribution): ProductDistribution
- {
- $day = $this->distributionSolver->getDayAsString($productDistribution->distribution);
-
- $productDistribution->active = 0;
- if ($productDistribution->product->active && $productDistribution->product->$day) {
- $productDistribution->active = 1;
- }
-
- return $productDistribution;
- }
-
- public function initQuantityMax(ProductDistribution $productDistribution): ProductDistribution
- {
- $product = $productDistribution->product;
- $day = $this->distributionSolver->getDayAsString($productDistribution->distribution);
-
- $productDistribution->quantity_max = $product->quantity_max;
- $fieldQuantityMax = 'quantity_max_' . $day;
- if (isset($product->$fieldQuantityMax) && $product->$fieldQuantityMax > 0) {
- $productDistribution->quantity_max = $product->$fieldQuantityMax;
- }
-
- return $productDistribution;
- }
-
- }
|