TextElement   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 85
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 96.43%

Importance

Changes 2
Bugs 1 Features 1
Metric Value
wmc 11
c 2
b 1
f 1
lcom 1
cbo 4
dl 0
loc 85
ccs 27
cts 28
cp 0.9643
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 3
A __toString() 0 4 1
A getText() 0 4 1
B render() 0 26 5
A containsEscapeCharacters() 0 7 1
1
<?php
2
3
namespace Matks\Vivian\Output;
4
5
use Exception;
6
7
/**
8
 * Text Element
9
 *
10
 * String to be echoed
11
 */
12
class TextElement extends Element
13
{
14
15
    /**
16
     * @var string
17
     */
18
    private $text;
19
20
    /**
21
     * @param string $text
22
     */
23
    public function __construct($text)
24
    {
25 1
        if (!$text) {
26
            throw new Exception('No text provided');
27
        }
28
29 1
        if ($this->containsEscapeCharacters($text)) {
30 1
            throw new Exception('Given text contains an escape code');
31
        }
32
33 1
        $this->text = $text;
34 1
    }
35
36
    /**
37
     * @return string
38
     */
39
    public function __toString()
40
    {
41 1
        return $this->text;
42
    }
43
44
    /**
45
     * @return string
46
     */
47
    public function getText()
48
    {
49 1
        return $this->text;
50
    }
51
52
    /**
53
     * @return string
54
     */
55
    public function render()
56
    {
57 1
        $textIsColored       = ($this->getTextColor() !== null);
58 1
        $backgroundIsColored = ($this->getBackgroundColor() !== null);
59
60 1
        $styles          = $this->getStyles();
61 1
        $stringHasStyles = (!empty($styles));
62
63 1
        $text = $this->getText();
64
65 1
        if ($textIsColored) {
66 1
            $text = $this->frame($text, $this->getTextColor()->getEscapeCharacter());
67 1
        }
68
69 1
        if ($backgroundIsColored) {
70 1
            $text = $this->frame($text, $this->getBackgroundColor()->getEscapeCharacter());
71 1
        }
72
73 1
        if ($stringHasStyles) {
74 1
            foreach ($styles as $style) {
75 1
                $text = $this->frame($text, $style->getEscapeCharacter());
76 1
            }
77 1
        }
78
79 1
        return $text;
80
    }
81
82
    /**
83
     * Check if given string contains color escape code
84
     *
85
     * @param string $string
86
     *
87
     * @return boolean
88
     */
89
    private static function containsEscapeCharacters($string)
90
    {
91 1
        $escapeCodePattern = '#' . static::ANSI_ESCAPE_CODE_REGEX . '#';
92 1
        $result            = preg_match($escapeCodePattern, $string);
93
94 1
        return (boolean) $result;
95
    }
96
}
97