|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Setono\SyliusReserveStockPlugin\Repository; |
|
6
|
|
|
|
|
7
|
|
|
use Doctrine\ORM\QueryBuilder; |
|
8
|
|
|
use Sylius\Component\Core\Model\ProductVariantInterface; |
|
9
|
|
|
use Sylius\Component\Order\Model\OrderInterface; |
|
10
|
|
|
|
|
11
|
|
|
trait ProductVariantCartOrderItem |
|
12
|
|
|
{ |
|
13
|
|
|
/** |
|
14
|
|
|
* @see InCartQuantityForProductVariantOrderItemRepositoryAwareInterface::inCartQuantityForProductVariantExcludingOrder() |
|
15
|
|
|
*/ |
|
16
|
|
|
public function inCartQuantityForProductVariantExcludingOrder( |
|
17
|
|
|
ProductVariantInterface $productVariant, |
|
18
|
|
|
int $ttl, |
|
19
|
|
|
?OrderInterface $order |
|
20
|
|
|
): int { |
|
21
|
|
|
$qb = $this->createOrderItemVariantQueryBuilder($productVariant); |
|
22
|
|
|
|
|
23
|
|
|
if (null !== $order && null !== $order->getId()) { |
|
24
|
|
|
$qb = $qb |
|
25
|
|
|
->andWhere('o.order != :order') |
|
26
|
|
|
->setParameter('order', $order); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
if ($ttl > 0) { |
|
30
|
|
|
$qb = $qb |
|
31
|
|
|
->andWhere('cart.updatedAt > :expireDate') |
|
32
|
|
|
->setParameter('expireDate', new \DateTime(sprintf('-%d second', $ttl))); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
return $this->produceSingleScalarQueryIntegerResult($qb); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* Create the base query without taking in account any order. It looks for order items from orders |
|
40
|
|
|
* that are marked as a 'cart' and where the product variant is the same as requested. |
|
41
|
|
|
*/ |
|
42
|
|
|
private function createOrderItemVariantQueryBuilder(ProductVariantInterface $productVariant): QueryBuilder |
|
43
|
|
|
{ |
|
44
|
|
|
/** @var QueryBuilder $qb */ |
|
45
|
|
|
$qb = $this->createQueryBuilder('o'); |
|
|
|
|
|
|
46
|
|
|
|
|
47
|
|
|
return $qb |
|
48
|
|
|
->select('SUM(o.quantity) AS quantity') |
|
49
|
|
|
->innerJoin('o.order', 'cart') |
|
50
|
|
|
->andWhere('cart.state = :state') |
|
51
|
|
|
->andWhere('o.variant = :variant') |
|
52
|
|
|
->setParameter('state', OrderInterface::STATE_CART) |
|
53
|
|
|
->setParameter('variant', $productVariant); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* Takes the query builder, transform it into a query and makes sure in all situations |
|
58
|
|
|
* an integer is being returned. In case the query does not result anything, `null` is returned |
|
59
|
|
|
* which will be transformed into the integer 0. |
|
60
|
|
|
*/ |
|
61
|
|
|
private function produceSingleScalarQueryIntegerResult(QueryBuilder $queryBuilder): int |
|
62
|
|
|
{ |
|
63
|
|
|
$result = $queryBuilder->getQuery()->getSingleScalarResult(); |
|
64
|
|
|
|
|
65
|
|
|
if (null === $result) { |
|
66
|
|
|
return 0; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
return (int) $result; |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|