Completed
Push — master ( a43619...64668c )
by Marcel
08:39 queued 07:03
created

RedisCanBeAccessed::testConnection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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