Completed
Push — master ( d97347...aed183 )
by Aydin
13s queued 11s
created

SelectableItemRenderer::getAvailableTextWidth()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 5
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpSchool\CliMenu\MenuItem;
6
7
use PhpSchool\CliMenu\MenuStyle;
8
use PhpSchool\CliMenu\Style\ItemStyle;
9
use PhpSchool\CliMenu\Style\Selectable;
10
use PhpSchool\CliMenu\Util\StringUtil as s;
11
use function PhpSchool\CliMenu\Util\mapWithKeys;
12
13
class SelectableItemRenderer
14
{
15
    public function render(MenuStyle $menuStyle, MenuItemInterface $item, bool $selected, bool $disabled) : array
16
    {
17
        $itemStyle = $item->getStyle();
18
        $marker = $itemStyle->getMarker($item, $selected);
19
        $availableTextWidth = $this->getAvailableTextWidth($menuStyle, $itemStyle);
20
21
        return mapWithKeys(
22
            $this->wrapAndIndentText($marker, $item->getText(), $availableTextWidth),
23
            function (int $key, string $row) use ($menuStyle, $itemStyle, $availableTextWidth, $disabled) {
24
                $text = $disabled ? $menuStyle->getDisabledItemText($row) : $row;
25
26
                return $key === 0 && $itemStyle->getDisplaysExtra()
27
                    ? $this->lineWithExtra($text, $availableTextWidth, $itemStyle)
28
                    : $text;
29
            }
30
        );
31
    }
32
33
    public function wrapAndIndentText(string $marker, string $text, int $availableWidth) : array
34
    {
35
        return explode(
36
            "\n",
37
            s::wordwrap(
38
                "{$marker}{$text}",
39
                $availableWidth,
40
                sprintf("\n%s", $this->emptyString(mb_strlen($marker)))
41
            )
42
        );
43
    }
44
45
    public function lineWithExtra(string $text, int $availableWidth, ItemStyle $itemStyle) : string
46
    {
47
        return sprintf(
48
            '%s%s  %s',
49
            $text,
50
            $this->emptyString($availableWidth - s::length($text)),
51
            $itemStyle->getItemExtra()
52
        );
53
    }
54
55
    public function emptyString(int $numCharacters) : string
56
    {
57
        return str_repeat(' ', $numCharacters);
58
    }
59
60
    public function getAvailableTextWidth(MenuStyle $menuStyle, ItemStyle $itemStyle) : int
61
    {
62
        return $itemStyle->getDisplaysExtra()
63
            ? $menuStyle->getContentWidth() - (mb_strlen($itemStyle->getItemExtra()) + 2)
64
            : $menuStyle->getContentWidth();
65
    }
66
}
67