PluginProbe
DecaLog / 4.4.0
DecaLog v4.4.0
3.0.2 3.1.0 3.10.0 3.2.0 3.3.0 3.4.0 3.4.1 3.5.0 3.5.1 3.6.0 3.6.1 3.6.2 3.6.3 3.7.0 3.7.1 3.8.0 3.9.0 3.9.1 4.0.0 4.1.0 4.2.0 4.3.0 4.3.1 4.4.0 4.5.0 All 75 releases
decalog / includes / libraries / lock / mutex / MySQLMutex.php

MySQLMutex.php in DecaLog 4.4.0, at includes/libraries/lock/mutex/MySQLMutex.php

79 lines 1.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 declare(strict_types=1);
4
5 namespace malkusch\lock\mutex;
6
7 use InvalidArgumentException;
8 use malkusch\lock\exception\LockAcquireException;
9 use malkusch\lock\exception\TimeoutException;
10
11 class MySQLMutex extends LockMutex
12 {
13 /**
14 * @var \PDO
15 */
16 private $pdo;
17
18 /**
19 * @var string
20 */
21 private $name;
22 /**
23 * @var int
24 */
25 private $timeout;
26
27 public function __construct(\PDO $PDO, string $name, int $timeout = 0)
28 {
29 $this->pdo = $PDO;
30
31 if (\strlen($name) > 64) {
32 throw new InvalidArgumentException('The maximum length of the lock name is 64 characters.');
33 }
34
35 $this->name = $name;
36 $this->timeout = $timeout;
37 }
38
39 /**
40 * @throws LockAcquireException
41 */
42 public function lock(): void
43 {
44 $statement = $this->pdo->prepare('SELECT GET_LOCK(?,?)');
45
46 $statement->execute([
47 $this->name,
48 $this->timeout,
49 ]);
50
51 $statement->setFetchMode(\PDO::FETCH_NUM);
52 $row = $statement->fetch();
53
54 if ($row[0] == 1) {
55 /*
56 * Returns 1 if the lock was obtained successfully.
57 */
58 return;
59 }
60
61 if ($row[0] === null) {
62 /*
63 * NULL if an error occurred (such as running out of memory or the thread was killed with mysqladmin kill).
64 */
65 throw new LockAcquireException('An error occurred while acquiring the lock');
66 }
67
68 throw TimeoutException::create($this->timeout);
69 }
70
71 public function unlock(): void
72 {
73 $statement = $this->pdo->prepare('DO RELEASE_LOCK(?)');
74 $statement->execute([
75 $this->name
76 ]);
77 }
78 }
79