RedisCanBeAccessed::check()   B
last analyzed

Complexity

Conditions 6
Paths 22

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 14
cts 14
cp 1
rs 8.8977
c 0
b 0
f 0
cc 6
nc 22
nop 1
crap 6
1
<?php
2
3
namespace BeyondCode\SelfDiagnosis\Checks;
4
5
use Illuminate\Support\Arr;
6
use Illuminate\Support\Facades\Redis;
7
8
class RedisCanBeAccessed implements Check
9
{
10
    private $message;
11
12
    /**
13
     * The name of the check.
14
     *
15
     * @param array $config
16
     * @return string
17
     */
18
    public function name(array $config): string
19
    {
20
        return trans('self-diagnosis::checks.redis_can_be_accessed.name');
21
    }
22
23
    /**
24
     * Perform the actual verification of this check.
25
     *
26
     * @param array $config
27
     * @return bool
28
     */
29 16
    public function check(array $config): bool
30
    {
31
        try {
32 16
            if (Arr::get($config, 'default_connection', true)) {
33 8
                if (!$this->testConnection()) {
34 4
                    $this->message = trans('self-diagnosis::checks.redis_can_be_accessed.message.default_cache');
35 4
                    return false;
36
                }
37
            }
38
39 12
            foreach (Arr::get($config, 'connections', []) as $connection) {
40 8
                if (!$this->testConnection($connection)) {
41 4
                    $this->message = trans('self-diagnosis::checks.redis_can_be_accessed.message.named_cache', [
42 4
                        'name' => $connection,
43
                    ]);
44 8
                    return false;
45
                }
46
            }
47 16
        } catch (\Exception $e) {
48 16
            $this->message = $e->getMessage();
49 16
            return false;
50
        }
51
52 8
        return true;
53
    }
54
55
    /**
56
     * The error message to display in case the check does not pass.
57
     *
58
     * @param array $config
59
     * @return string
60
     */
61 8
    public function message(array $config): string
62
    {
63 8
        return trans('self-diagnosis::checks.redis_can_be_accessed.message.not_accessible', [
64 8
            'error' => $this->message,
65
        ]);
66
    }
67
68
    /**
69
     * Tests a redis connection and returns whether the connection is opened or not.
70
     *
71
     * @param string|null $name
72
     * @return bool
73
     */
74 16
    private function testConnection(string $name = null): bool
75
    {
76 16
        $connection = Redis::connection($name);
77 16
        $connection->connect();
78 16
        return $connection->isConnected();
79
    }
80
}
81