Passed
Push — master ( 302660...3652f8 )
by payever
04:19 queued 01:32
created

MySQLLock   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 17
c 1
b 0
f 0
dl 0
loc 66
rs 10

5 Methods

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