1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace VPA\Console\Glyphs; |
4
|
|
|
|
5
|
|
|
use VPA\Console\FrameConfigInterface; |
6
|
|
|
use VPA\Console\Symbol; |
7
|
|
|
|
8
|
|
|
class Text extends GlyphInline |
9
|
|
|
{ |
10
|
|
|
private string $text = ''; |
11
|
|
|
|
12
|
24 |
|
public function setValue(string $text): GlyphInline |
13
|
|
|
{ |
14
|
24 |
|
$this->text = $text; |
15
|
24 |
|
$batches = $this->splitText(); |
16
|
24 |
|
$lengths = array_map(function ($it) { |
17
|
24 |
|
return strlen($it); |
18
|
|
|
}, $batches); |
19
|
24 |
|
$this->width = max($lengths); |
20
|
24 |
|
$this->height = count($batches); |
21
|
24 |
|
$this->render(); |
22
|
24 |
|
return $this; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public function getValue(): string |
26
|
|
|
{ |
27
|
|
|
return $this->text; |
28
|
|
|
} |
29
|
|
|
|
30
|
24 |
|
public function render(): GlyphInline |
31
|
|
|
{ |
32
|
24 |
|
$batches = $this->splitText(); |
33
|
24 |
|
$lengths = array_map(function ($it) { |
34
|
24 |
|
return strlen($it); |
35
|
|
|
}, $batches); |
36
|
24 |
|
$this->height = count($batches); |
37
|
24 |
|
$maxLength = max($lengths); |
38
|
24 |
|
$parent = $this->getParent(); |
39
|
24 |
|
$contentWidth = $parent && $parent instanceof GlyphBlock ? $parent->getContentWidth() : 0; |
40
|
24 |
|
$this->width = $contentWidth > 0 ? $contentWidth : min($maxLength, $this->__get('maxWidth')); |
41
|
24 |
|
$this->__set('maxWidth', max($this->width, $this->__get('maxWidth'))); |
42
|
24 |
|
$padding = match ($this->__get('textAlign')) { |
43
|
22 |
|
default => STR_PAD_RIGHT, |
44
|
1 |
|
'right' => STR_PAD_LEFT, |
45
|
1 |
|
'center' => STR_PAD_BOTH, |
46
|
|
|
}; |
47
|
24 |
|
$resultString = ''; |
48
|
24 |
|
foreach ($batches as $batch) { |
49
|
24 |
|
$resultString .= str_pad(ltrim($batch), $this->getWidth(), ' ', $padding); |
50
|
|
|
} |
51
|
24 |
|
$symbols = str_split($resultString); |
52
|
|
|
|
53
|
24 |
|
$this->renderMap = $this->getWidth() ? array_chunk(array_map(function ($value) { |
54
|
24 |
|
return new Symbol($value); |
55
|
24 |
|
}, $symbols), $this->getWidth()) : []; |
|
|
|
|
56
|
24 |
|
$this->height = count($this->renderMap); |
57
|
24 |
|
return $this; |
58
|
|
|
} |
59
|
|
|
|
60
|
24 |
|
private function splitText(): array |
61
|
|
|
{ |
62
|
24 |
|
$parent = $this->getParent(); |
63
|
24 |
|
$deltaWidth = $parent && $parent instanceof GlyphBlock ? $parent->getDeltaWidth() : 0; |
64
|
24 |
|
$result = []; |
65
|
24 |
|
$batches = explode("\n", $this->text); |
66
|
24 |
|
foreach ($batches as $batch) { |
67
|
24 |
|
$chunks = str_split(ltrim($batch), $this->__get('maxWidth') - $deltaWidth); |
68
|
24 |
|
foreach ($chunks as $chunk) { |
69
|
24 |
|
$result[] = $chunk; |
70
|
|
|
} |
71
|
|
|
} |
72
|
24 |
|
return $result; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|