Passed
Push — master ( d2a986...963355 )
by Biao
04:05
created

LogTrait   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 41
dl 0
loc 70
rs 10
c 0
b 0
f 0
wmc 12

6 Methods

Rating   Name   Duplication   Size   Complexity  
A logException() 0 14 1
B log() 0 25 6
A warning() 0 3 1
A error() 0 3 1
A callWithCatchException() 0 7 2
A info() 0 3 1
1
<?php
2
3
namespace Hhxsv5\LaravelS\Swoole\Traits;
4
5
use Hhxsv5\LaravelS\LaravelS;
6
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
7
8
trait LogTrait
9
{
10
    public function logException(\Exception $e)
11
    {
12
        $this->log(
13
            sprintf(
14
                'Uncaught exception \'%s\': [%d]%s called in %s:%d%s%s',
15
                get_class($e),
16
                $e->getCode(),
17
                $e->getMessage(),
18
                $e->getFile(),
19
                $e->getLine(),
20
                PHP_EOL,
21
                $e->getTraceAsString()
22
            ),
23
            'ERROR'
24
        );
25
    }
26
27
    public function log($msg, $type = 'INFO')
28
    {
29
        $outputStyle = LaravelS::getOutputStyle();
30
        $msg = sprintf('[%s] [%s] %s', date('Y-m-d H:i:s'), $type, $msg);
31
        if ($outputStyle) {
0 ignored issues
show
introduced by
$outputStyle is of type Symfony\Component\Console\Style\OutputStyle, thus it always evaluated to true.
Loading history...
32
            switch (strtoupper($type)) {
33
                case 'WARN':
34
                    if (!$outputStyle->getFormatter()->hasStyle('warning')) {
35
                        $style = new OutputFormatterStyle('yellow');
36
                        $outputStyle->getFormatter()->setStyle('warning', $style);
37
                    }
38
                    $outputStyle->writeln("<warning>$msg</warning>");
39
                    break;
40
                case 'ERROR':
41
                    $outputStyle->writeln("<error>$msg</error>");
42
                    break;
43
                case 'INFO':
44
                    $outputStyle->writeln("<info>$msg</info>");
45
                    break;
46
                default:
47
                    $outputStyle->writeln($msg);
48
                    break;
49
            }
50
        } else {
51
            echo $msg, PHP_EOL;
52
        }
53
    }
54
55
    public function info($msg)
56
    {
57
        $this->log($msg, 'INFO');
58
    }
59
60
    public function warning($msg)
61
    {
62
        $this->log($msg, 'WARN');
63
    }
64
65
    public function error($msg)
66
    {
67
        $this->log($msg, 'ERROR');
68
    }
69
70
71
    public function callWithCatchException(callable $callback)
72
    {
73
        try {
74
            return $callback();
75
        } catch (\Exception $e) {
76
            $this->logException($e);
77
            return false;
78
        }
79
    }
80
}