Passed
Push — master ( 6c42be...776013 )
by Igor
02:03
created

MySQLLock::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
/**
3
 * PHP version 5.4 and 7
4
 *
5
 * @package   Payever\Core
6
 * @author    Hennadii.Shymanskyi <[email protected]>
7
 * @copyright 2017-2019 payever GmbH
8
 * @license   MIT <https://opensource.org/licenses/MIT>
9
 */
10
11
namespace Payever\ExternalIntegration\Core\Lock;
12
13
/**
14
 * PHP version 5.4 and 7
15
 *
16
 * @package   Payever\Core
17
 * @author    Hennadii.Shymanskyi <[email protected]>
18
 * @copyright 2017-2019 payever GmbH
19
 * @license   MIT <https://opensource.org/licenses/MIT>
20
 */
21
class MySQLLock implements LockInterface
22
{
23
    /** @var \PDO */
24
    private $pdo;
25
26
    /** @var string|null */
27
    private $currentDatabase;
28
29
    public function __construct(\PDO $pdo)
30
    {
31
        $this->pdo = $pdo;
32
    }
33
34
    /**
35
     * @inheritdoc
36
     *
37
     * @throws \RuntimeException
38
     */
39
    public function acquireLock($lockName, $timeout)
40
    {
41
        $statement = $this->pdo->prepare("SELECT GET_LOCK(?,?)");
42
43
        $statement->execute(array(
44
            $this->prepareLockName($lockName),
45
            $timeout,
46
        ));
47
48
        $result = $statement->fetch(\PDO::FETCH_NUM);
49
50
        if ($result[0] !== 1) {
51
            throw new \RuntimeException(sprintf('Unable to acquire lock with name %s', $lockName));
52
        }
53
    }
54
55
    /**
56
     * @inheritdoc
57
     */
58
    public function releaseLock($lockName)
59
    {
60
        $statement = "SELECT RELEASE_LOCK({$this->prepareLockName($lockName)})";
61
62
        $this->pdo->exec($statement);
63
    }
64
65
    /**
66
     * @param string $lockName
67
     * @return string
68
     */
69
    private function prepareLockName($lockName)
70
    {
71
        return $this->pdo->quote("{$this->getCurrentDatabase()}.{$lockName}");
72
    }
73
74
    /**
75
     * @return string|null
76
     */
77
    private function getCurrentDatabase()
78
    {
79
        if (null === $this->currentDatabase) {
80
            $this->currentDatabase = $this->pdo->query('SELECT DATABASE()')->fetchColumn();
81
        }
82
83
        return $this->currentDatabase;
84
    }
85
}
86