Test Failed
Pull Request — master (#12)
by wujunze
03:09
created

WebsocketTarget::export()   F

Complexity

Conditions 22
Paths 142

Size

Total Lines 62
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 22
eloc 50
c 1
b 0
f 1
nc 142
nop 1
dl 0
loc 62
rs 3.8166

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
declare(strict_types=1);
3
4
namespace Seasx\SeasLogger\Targets;
5
6
use Exception;
7
use Psr\Log\LogLevel;
8
use Seasx\SeasLogger\ArrayHelper;
9
use Seasx\SeasLogger\HtmlColor;
10
use Swoole\Server;
11
12
/**
13
 * Class WebsocketTarget
14
 * @package Seasx\SeasLogger\Targets
15
 */
16
class WebsocketTarget extends AbstractTarget
17
{
18
    const COLOR_RANDOM = 'random';
19
    const COLOR_LEVEL = 'level';
20
    const COLOR_DEFAULT = 'default';
21
22
    /** @var array */
23
    private $colorTemplate = [
24
        'Magenta',
25
        self::COLOR_LEVEL,
26
        self::COLOR_LEVEL,
27
        'DarkGray',
28
        'DarkGray',
29
        self::COLOR_RANDOM,
30
        self::COLOR_LEVEL,
31
        'DarkGray',
32
        self::COLOR_LEVEL,
33
        self::COLOR_LEVEL
34
    ];
35
    /** @var string */
36
    private $default = 'LightGray';
37
    /** @var callable */
38
    private $getServer;
39
40
    /**
41
     * @param callable $function
42
     */
43
    public function setGetServer(callable $function): void
44
    {
45
        $this->getServer = $function;
46
    }
47
48
    /**
49
     * @param array $messages
50
     * @throws Exception
51
     */
52
    public function export(array $messages): void
53
    {
54
        if (!is_callable($this->getServer)) {
55
            return;
56
        }
57
        /** @var Server $server */
58
        $swooleServer = call_user_func($this->getServer);
59
        if (!$swooleServer || !$swooleServer instanceof Server) {
60
            return;
61
        }
62
        foreach ($swooleServer->connections as $fd) {
63
            if ($swooleServer->isEstablished($fd)) {
0 ignored issues
show
Bug introduced by
The method isEstablished() does not exist on Swoole\Server. It seems like you code against a sub-type of Swoole\Server such as Swoole\WebSocket\Server. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

63
            if ($swooleServer->/** @scrutinizer ignore-call */ isEstablished($fd)) {
Loading history...
64
                foreach ($messages as $message) {
65
                    foreach ($message as $msg) {
66
                        if (is_string($msg)) {
67
                            switch (ini_get('seaslog.appender')) {
68
                                case '2':
69
                                case '3':
70
                                    $msg = trim(substr($msg, $this->str_n_pos($msg, ' ', 6)));
71
                                    break;
72
                            }
73
                            $msg = explode($this->split, trim($msg));
74
                            $ranColor = $this->default;
75
                        } else {
76
                            $ranColor = ArrayHelper::remove($msg, '%c');
77
                        }
78
                        if (!empty($this->levelList) && !in_array(strtolower($msg[$this->levelIndex]),
79
                                $this->levelList)) {
80
                            continue;
81
                        }
82
                        if (empty($ranColor)) {
83
                            $ranColor = $this->default;
84
                        } elseif (is_array($ranColor) && isset($ranColor['websocket'])) {
85
                            $ranColor = $ranColor['websocket'];
86
                        } else {
87
                            $ranColor = $this->default;
88
                        }
89
                        foreach ($msg as $index => $msgValue) {
90
                            $msg[$index] = is_string($msgValue) ? trim($msgValue) : (string)$msgValue;
91
                            $level = $this->getLevelColor(trim($msg[$this->levelIndex]));
92
                            if (isset($this->colorTemplate[$index])) {
93
                                $color = $this->colorTemplate[$index];
94
                                switch ($color) {
95
                                    case self::COLOR_LEVEL:
96
                                        $colors[] = HtmlColor::getColor($level);
97
                                        break;
98
                                    case self::COLOR_RANDOM:
99
                                        $colors[] = HtmlColor::getColor($ranColor);
100
                                        break;
101
                                    case self::COLOR_DEFAULT:
102
                                        $colors[] = $this->default;
103
                                        break;
104
                                    default:
105
                                        $colors[] = HtmlColor::getColor($color);
106
                                }
107
                            } else {
108
                                $colors[] = $level;
109
                            }
110
                        }
111
                        $msg = json_encode([$msg, $colors], JSON_UNESCAPED_UNICODE);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $colors does not seem to be defined for all execution paths leading up to this point.
Loading history...
112
                        rgo(function () use ($swooleServer, $fd, $msg) {
113
                            $swooleServer->push($fd, $msg);
0 ignored issues
show
Bug introduced by
The method push() does not exist on Swoole\Server. It seems like you code against a sub-type of Swoole\Server such as Swoole\WebSocket\Server. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

113
                            $swooleServer->/** @scrutinizer ignore-call */ 
114
                                           push($fd, $msg);
Loading history...
114
                        });
115
                    }
116
                }
117
            }
118
        }
119
    }
120
121
    /**
122
     * @param string $level
123
     * @return string
124
     */
125
    private function getLevelColor(string $level): string
126
    {
127
        switch (strtolower($level)) {
128
            case LogLevel::INFO:
129
                return "Green";
130
            case LogLevel::DEBUG:
131
                return 'DarkGray';
132
            case LogLevel::ERROR:
133
                return "Red";
134
            case LogLevel::WARNING:
135
                return 'Yellow';
136
            default:
137
                return 'DarkRed';
138
        }
139
    }
140
141
}