Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
couponlocker.php
1<?php
2
4
6
7final class CouponLocker
8{
9 private const STATUS_LOCKED = 1;
10 private const STATUS_NOT_LOCKED = 0;
11 private const STATUS_EMPTY = -1;
12
13 private static null|self $instance;
14
15 private array $couponState;
16
17 public static function getInstance(): self
18 {
19 if (!isset(self::$instance))
20 {
21 self::$instance = new self();
22 }
23
24 return self::$instance;
25 }
26
27 public function __construct()
28 {
29 $this->clear();
30 }
31
32 public function __destruct()
33 {
34 $this->unlockAll();
35 self::$instance = null;
36 }
37
38 private function getUniqueLockName(string $coupon): string
39 {
40 return 'sale_coupon_' . md5($coupon);
41 }
42
43 private function clear(): void
44 {
45 $this->couponState = [];
46 }
47
48 private function setLockState(string $coupon, int $state): void
49 {
50 $this->couponState[$coupon] = $state;
51 }
52
53 private function getLockState(string $coupon): int
54 {
55 return $this->couponState[$coupon] ?? self::STATUS_EMPTY;
56 }
57
58 public function isNotLocked(string $coupon): bool
59 {
60 return $this->getLockState($coupon) === self::STATUS_NOT_LOCKED;
61 }
62
63 public function isLocked(string $coupon): bool
64 {
65 return $this->getLockState($coupon) === self::STATUS_LOCKED;
66 }
67
68 public function lock(string $coupon): void
69 {
70 $coupon = trim($coupon);
71 if ($coupon === '')
72 {
73 return;
74 }
75
76 $connection = Main\Application::getConnection();
77 if ($connection->lock($this->getUniqueLockName($coupon)))
78 {
79 $this->setLockState($coupon, self::STATUS_LOCKED);
80 }
81 unset($connection);
82 }
83
84 public function unlock(string $coupon): void
85 {
86 $coupon = trim($coupon);
87 if ($coupon === '')
88 {
89 return;
90 }
91
92 $connection = Main\Application::getConnection();
93 if ($connection->unlock($this->getUniqueLockName($coupon)))
94 {
95 $this->setLockState($coupon, self::STATUS_NOT_LOCKED);
96 }
97 unset($connection);
98 }
99
100 public function unlockAll(): void
101 {
102 if (empty($this->couponState))
103 {
104 return;
105 }
106
107 $connection = Main\Application::getConnection();
108
109 foreach (array_keys($this->couponState) as $coupon)
110 {
111 if (!$this->isLocked($coupon))
112 {
113 continue;
114 }
115 $connection->unlock($this->getUniqueLockName($coupon));
116 }
117
118 unset($connection);
119
120 $this->clear();
121 }
122}