Passed
Push — master ( f388ca...51208f )
by Alexander
09:46
created

MysqlMutex::prepareName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 0
dl 0
loc 9
ccs 7
cts 7
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\mutex;
9
10
use yii\base\InvalidConfigException;
11
use yii\db\Expression;
12
13
/**
14
 * MysqlMutex implements mutex "lock" mechanism via MySQL locks.
15
 *
16
 * Application configuration example:
17
 *
18
 * ```
19
 * [
20
 *     'components' => [
21
 *         'db' => [
22
 *             'class' => 'yii\db\Connection',
23
 *             'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
24
 *         ]
25
 *         'mutex' => [
26
 *             'class' => 'yii\mutex\MysqlMutex',
27
 *         ],
28
 *     ],
29
 * ]
30
 * ```
31
 *
32
 * @see Mutex
33
 *
34
 * @author resurtm <[email protected]>
35
 * @since 2.0
36
 */
37
class MysqlMutex extends DbMutex
38
{
39
    /**
40
     * @var Expression|string|null prefix value. If null (by default) then connection's current database name is used.
41
     * @since 2.0.47
42
     */
43
    public $keyPrefix = null;
44
45
46
    /**
47
     * Initializes MySQL specific mutex component implementation.
48
     * @throws InvalidConfigException if [[db]] is not MySQL connection.
49
     */
50 26
    public function init()
51
    {
52 26
        parent::init();
53 26
        if ($this->db->driverName !== 'mysql') {
54
            throw new InvalidConfigException('In order to use MysqlMutex connection must be configured to use MySQL database.');
55
        }
56 26
        if ($this->keyPrefix === null) {
57 13
            $this->keyPrefix = new Expression('DATABASE()');
58
        }
59 26
    }
60
61
    /**
62
     * Acquires lock by given name.
63
     * @param string $name of the lock to be acquired.
64
     * @param int $timeout time (in seconds) to wait for lock to become released.
65
     * @return bool acquiring result.
66
     * @see https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_get-lock
67
     */
68 25
    protected function acquireLock($name, $timeout = 0)
69
    {
70
        return $this->db->useMaster(function ($db) use ($name, $timeout) {
71
            /** @var \yii\db\Connection $db */
72 25
            $nameData = $this->prepareName();
73 25
            return (bool)$db->createCommand(
74 25
                'SELECT GET_LOCK(' . $nameData[0] . ', :timeout), :prefix',
75 25
                array_merge(
76 25
                    [':name' => $this->hashLockName($name), ':timeout' => $timeout, ':prefix' => $this->keyPrefix],
77 25
                    $nameData[1]
78
                )
79 25
            )->queryScalar();
80 25
        });
81
    }
82
83
    /**
84
     * Releases lock by given name.
85
     * @param string $name of the lock to be released.
86
     * @return bool release result.
87
     * @see https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_release-lock
88
     */
89
    protected function releaseLock($name)
90
    {
91 25
        return $this->db->useMaster(function ($db) use ($name) {
92
            /** @var \yii\db\Connection $db */
93 25
            $nameData = $this->prepareName();
94 25
            return (bool)$db->createCommand(
95 25
                'SELECT RELEASE_LOCK(' . $nameData[0] . '), :prefix',
96 25
                array_merge(
97 25
                    [':name' => $this->hashLockName($name), ':prefix' => $this->keyPrefix],
98 25
                    $nameData[1]
99
                )
100 25
            )->queryScalar();
101 25
        });
102
    }
103
104
    /**
105
     * Prepare lock name
106
     * @return array expression and params
107
     * @since 2.0.48
108
     */
109 25
    protected function prepareName()
110
    {
111 25
        $params = [];
112 25
        $expression = "SUBSTRING(CONCAT(:prefix, :name), 1, 64)";
113 25
        if ($this->keyPrefix instanceof Expression) {
114 19
            $expression = strtr($expression, [':prefix' => $this->keyPrefix->expression]);
115 19
            $params = $this->keyPrefix->params;
116
        }
117 25
        return [$expression, $params];
118
    }
119
120
    /**
121
     * Generate hash for lock name to avoid exceeding lock name length limit.
122
     *
123
     * @param string $name
124
     * @return string
125
     * @since 2.0.16
126
     * @see https://github.com/yiisoft/yii2/pull/16836
127
     */
128 25
    protected function hashLockName($name)
129
    {
130 25
        return sha1($name);
131
    }
132
}
133