Passed
Push — master ( 7d8507...0b4741 )
by Paweł
11:07
created

MysqlMutex::init()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 0
dl 0
loc 8
ccs 5
cts 6
cp 0.8333
crap 3.0416
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
     * Initializes MySQL specific mutex component implementation.
47
     * @throws InvalidConfigException if [[db]] is not MySQL connection.
48
     */
49 19
    public function init()
50
    {
51 19
        parent::init();
52 19
        if ($this->db->driverName !== 'mysql') {
53
            throw new InvalidConfigException('In order to use MysqlMutex connection must be configured to use MySQL database.');
54
        }
55 19
        if ($this->keyPrefix === null) {
56 13
            $this->keyPrefix = new Expression('DATABASE()');
57
        }
58 19
    }
59
60
    /**
61
     * Acquires lock by given name.
62
     * @param string $name of the lock to be acquired.
63
     * @param int $timeout time (in seconds) to wait for lock to become released.
64
     * @return bool acquiring result.
65
     * @see https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_get-lock
66
     */
67 19
    protected function acquireLock($name, $timeout = 0)
68
    {
69
        return $this->db->useMaster(function ($db) use ($name, $timeout) {
70
            /** @var \yii\db\Connection $db */
71 19
            return (bool) $db->createCommand(
72 19
                'SELECT GET_LOCK(CONCAT(:prefix, :name), :timeout)',
73 19
                [':name' => $this->hashLockName($name), ':timeout' => $timeout, ':prefix' => $this->keyPrefix]
74 19
            )->queryScalar();
75 19
        });
76
    }
77
78
    /**
79
     * Releases lock by given name.
80
     * @param string $name of the lock to be released.
81
     * @return bool release result.
82
     * @see https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_release-lock
83
     */
84
    protected function releaseLock($name)
85
    {
86 19
        return $this->db->useMaster(function ($db) use ($name) {
87
            /** @var \yii\db\Connection $db */
88 19
            return (bool) $db->createCommand(
89 19
                'SELECT RELEASE_LOCK(CONCAT(:prefix, :name))',
90 19
                [':name' => $this->hashLockName($name), ':prefix' => $this->keyPrefix]
91 19
            )->queryScalar();
92 19
        });
93
    }
94
95
    /**
96
     * Generate hash for lock name to avoid exceeding lock name length limit.
97
     *
98
     * @param string $name
99
     * @return string
100
     * @since 2.0.16
101
     * @see https://github.com/yiisoft/yii2/pull/16836
102
     */
103 19
    protected function hashLockName($name) {
104 19
        return sha1($name);
105
    }
106
}
107