1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace QB\MySQL\Clause; |
6
|
|
|
|
7
|
|
|
class Lock |
8
|
|
|
{ |
9
|
|
|
public const LOCK_IN_SHARE_MODE = 'LOCK IN SHARE MODE'; |
10
|
|
|
|
11
|
|
|
public const FOR_UPDATE = 'UPDATE'; |
12
|
|
|
public const FOR_SHARE = 'SHARE'; |
13
|
|
|
|
14
|
|
|
public const MODIFIER_NOWAIT = 'NOWAIT'; |
15
|
|
|
public const MODIFIER_SKIP_LOCKED = 'SKIP LOCKED'; |
16
|
|
|
|
17
|
|
|
protected const VALID_FOR = [null, self::LOCK_IN_SHARE_MODE, self::FOR_UPDATE, self::FOR_SHARE]; |
18
|
|
|
protected const VALID_MODIFIERS = [null, self::MODIFIER_NOWAIT, self::MODIFIER_SKIP_LOCKED]; |
19
|
|
|
|
20
|
|
|
protected string $for = self::LOCK_IN_SHARE_MODE; |
21
|
|
|
|
22
|
|
|
/** @var string[] */ |
23
|
|
|
protected array $tables = []; |
24
|
|
|
|
25
|
|
|
protected ?string $modifier = null; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Lock constructor. |
29
|
|
|
* |
30
|
|
|
* @param string|null $for |
31
|
|
|
* @param string[] $tables |
32
|
|
|
* @param string|null $modifier |
33
|
|
|
*/ |
34
|
27 |
|
public function __construct(?string $for = null, array $tables = [], ?string $modifier = null) |
35
|
|
|
{ |
36
|
27 |
|
if (!$this->isValid($for, $modifier)) { |
37
|
5 |
|
throw new \InvalidArgumentException( |
38
|
5 |
|
sprintf('invalid arguments for %s. arguments: %s', __CLASS__, print_r(func_get_args(), true)) |
|
|
|
|
39
|
|
|
); |
40
|
|
|
} |
41
|
|
|
|
42
|
22 |
|
if ($for === null) { |
43
|
1 |
|
return; |
44
|
|
|
} |
45
|
|
|
|
46
|
21 |
|
$this->for = $for; |
47
|
21 |
|
$this->tables = $tables; |
48
|
21 |
|
$this->modifier = $modifier; |
49
|
21 |
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @param string|null $for |
53
|
|
|
* @param string|null $modifier |
54
|
|
|
* |
55
|
|
|
* @return bool |
56
|
|
|
*/ |
57
|
27 |
|
private function isValid(?string $for = null, ?string $modifier = null): bool |
58
|
|
|
{ |
59
|
27 |
|
if (!in_array($for, static::VALID_FOR, true)) { |
60
|
3 |
|
return false; |
61
|
|
|
} |
62
|
|
|
|
63
|
24 |
|
if (!in_array($modifier, static::VALID_MODIFIERS, true)) { |
64
|
2 |
|
return false; |
65
|
|
|
} |
66
|
|
|
|
67
|
22 |
|
return true; |
68
|
|
|
} |
69
|
|
|
|
70
|
22 |
|
public function __toString(): string |
71
|
|
|
{ |
72
|
22 |
|
if ($this->for === self::LOCK_IN_SHARE_MODE) { |
73
|
2 |
|
return self::LOCK_IN_SHARE_MODE; |
74
|
|
|
} |
75
|
|
|
|
76
|
20 |
|
$parts = []; |
77
|
20 |
|
$parts[] = 'FOR ' . $this->for; |
78
|
20 |
|
if (count($this->tables) > 0) { |
79
|
5 |
|
$parts[] = 'OF ' . implode(', ', $this->tables); |
80
|
|
|
} |
81
|
20 |
|
if ($this->modifier) { |
82
|
11 |
|
$parts[] = $this->modifier; |
83
|
|
|
} |
84
|
|
|
|
85
|
20 |
|
return implode(' ', $parts); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|