Passed
Push — master ( fe6e36...db6c3d )
by Alec
02:25
created

ConsoleColour   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Test Coverage

Coverage 95.83%

Importance

Changes 0
Metric Value
eloc 23
dl 0
loc 70
ccs 23
cts 24
cp 0.9583
rs 10
c 0
b 0
f 0
wmc 12

7 Methods

Rating   Name   Duplication   Size   Complexity  
A applyEscaped() 0 7 1
A force256Colors() 0 6 3
A are256ColorsSupported() 0 4 3
A are256ColorsForced() 0 3 1
A areInDocker256ColorsSupported() 0 3 1
A __construct() 0 4 1
A apply() 0 10 2
1
<?php
2
/**
3
 * User: alec
4
 * Date: 15.10.18
5
 * Time: 21:33
6
 */
7
8
namespace AlecRabbit\ConsoleColour;
9
10
use AlecRabbit\ConsoleColour\Exception\InvalidStyleException;
11
use AlecRabbit\Traits\DoesProcessException;
12
13
class ConsoleColour extends ConsoleColor
14
{
15
    use DoesProcessException;
16
17
    public const ESC_CHAR = "\033";
18
19
    /** @var bool */
20
    protected $force256Colors;
21
22 52
    public function __construct(?bool $force256Colors = null)
23
    {
24 52
        parent::__construct();
25 52
        $this->force256Colors = $force256Colors ?? false;
26 52
    }
27
28 2
    public function force256Colors(): ConsoleColour
29
    {
30 2
        if (!$this->are256ColorsForced()) {
31 2
            $this->force256Colors = $this->are256ColorsSupported() ? false : true;
32
        }
33 2
        return $this;
34
    }
35
36 2
    public function are256ColorsForced(): bool
37
    {
38 2
        return $this->force256Colors;
39
    }
40
41 2
    public function are256ColorsSupported(): bool
42
    {
43
        return
44 2
            $this->force256Colors ?: (parent::are256ColorsSupported() || $this->areInDocker256ColorsSupported());
45
    }
46
47 2
    protected function areInDocker256ColorsSupported(): bool
48
    {
49 2
        return (strpos((string)getenv('DOCKER_TERM'), '256color') !== false);
50
    }
51
52
    /**
53
     * @param array|string $style
54
     * @param string $text
55
     * @return string
56
     * @throws \Throwable
57
     */
58 2
    public function applyEscaped($style, $text): string
59
    {
60
        return
61 2
            str_replace(
62 2
                self::ESC_CHAR,
63 2
                '\033',
64 2
                $this->apply($style, $text)
65
            );
66
    }
67
68
    /**
69
     * @param array|string $styles
70
     * @param string $text
71
     * @return string
72
     */
73 38
    public function apply($styles, $text): string
74
    {
75
        try {
76 38
            return parent::apply($styles, $text);
77 6
        } catch (InvalidStyleException $e) {
78
            // Do nothing
79
            // or
80 4
             $this->processException($e);
81
        }
82
        return $text;
83
    }
84
}
85