TextElement::__construct()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 12
ccs 5
cts 6
cp 0.8333
rs 9.4285
cc 3
eloc 6
nc 3
nop 1
crap 3.0416
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