-
Notifications
You must be signed in to change notification settings - Fork 10.9k
/
InteractsWithRedis.php
113 lines (97 loc) · 2.87 KB
/
InteractsWithRedis.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
namespace Illuminate\Foundation\Testing\Concerns;
use Exception;
use Illuminate\Foundation\Application;
use Illuminate\Redis\RedisManager;
use Illuminate\Support\Env;
trait InteractsWithRedis
{
/**
* Indicate connection failed if redis is not available.
*
* @var bool
*/
private static $connectionFailedOnceWithDefaultsSkip = false;
/**
* Redis manager instance.
*
* @var \Illuminate\Redis\RedisManager[]
*/
private $redis;
/**
* Setup redis connection.
*
* @return void
*/
public function setUpRedis()
{
if (! extension_loaded('redis')) {
$this->markTestSkipped('The redis extension is not installed. Please install the extension to enable '.__CLASS__);
}
if (static::$connectionFailedOnceWithDefaultsSkip) {
$this->markTestSkipped('Trying default host/port failed, please set environment variable REDIS_HOST & REDIS_PORT to enable '.__CLASS__);
}
$app = $this->app ?? new Application;
$host = Env::get('REDIS_HOST', '127.0.0.1');
$port = Env::get('REDIS_PORT', 6379);
foreach ($this->redisDriverProvider() as $driver) {
$this->redis[$driver[0]] = new RedisManager($app, $driver[0], [
'cluster' => false,
'options' => [
'prefix' => 'test_',
],
'default' => [
'host' => $host,
'port' => $port,
'database' => 5,
'timeout' => 0.5,
'name' => 'default',
],
]);
}
try {
$this->redis['phpredis']->connection()->flushdb();
} catch (Exception $e) {
if ($host === '127.0.0.1' && $port === 6379 && Env::get('REDIS_HOST') === null) {
static::$connectionFailedOnceWithDefaultsSkip = true;
$this->markTestSkipped('Trying default host/port failed, please set environment variable REDIS_HOST & REDIS_PORT to enable '.__CLASS__);
}
}
}
/**
* Teardown redis connection.
*
* @return void
*/
public function tearDownRedis()
{
$this->redis['phpredis']->connection()->flushdb();
foreach ($this->redisDriverProvider() as $driver) {
$this->redis[$driver[0]]->connection()->disconnect();
}
}
/**
* Get redis driver provider.
*
* @return array
*/
public function redisDriverProvider()
{
return [
['predis'],
['phpredis'],
];
}
/**
* Run test if redis is available.
*
* @param callable $callback
* @return void
*/
public function ifRedisAvailable($callback)
{
$this->setUpRedis();
$callback();
$this->tearDownRedis();
}
}