OutputHelper::indentText()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 4
dl 0
loc 11
rs 10
1
<?php
2
3
namespace Startwind\Forrest\Util;
4
5
use Symfony\Component\Console\Output\OutputInterface;
6
7
abstract class OutputHelper
8
{
9
    /**
10
     * Show a blue output box with a info message.
11
     */
12
    public static function writeInfoBox(OutputInterface $output, string|array $message): void
13
    {
14
        self::writeMessage($output, $message, '<fg=black;bg=cyan>', '</></>');
15
    }
16
17
    /**
18
     * Show a red output box with a error message.
19
     */
20
    public static function writeErrorBox(OutputInterface $output, string|array $message): void
21
    {
22
        self::writeMessage($output, $message, '<error>', '</error>');
23
    }
24
25
    /**
26
     * Show a red output box with a warning message.
27
     */
28
    public static function writeWarningBox(OutputInterface $output, string|array $message): void
29
    {
30
        self::writeMessage($output, $message, '<fg=black;bg=yellow>', '</>');
31
    }
32
33
    public static function writeMessage(OutputInterface $output, string|array $message, string $prefix = '', string $postfix = ''): void
34
    {
35
        $maxLength = 0;
36
37
        $messages = self::prepareMessages($message);
38
39
        foreach ($messages as $singleMessage) {
40
            $maxLength = max($maxLength, strlen($singleMessage));
41
        }
42
43
        $output->writeln("");
44
45
        foreach ($messages as $singleMessage) {
46
            $output->writeln($prefix . "  " . self::getPreparedMessage($singleMessage, $maxLength, 2) . $postfix);
47
        }
48
49
        $output->writeln("");
50
    }
51
52
    private static function prepareMessages(string|array $message): array
53
    {
54
        if (!is_array($message)) {
0 ignored issues
show
introduced by
The condition is_array($message) is always true.
Loading history...
55
            $message = [$message];
56
        }
57
58
        array_unshift($message, '');
59
        $message[] = '';
60
61
        return $message;
62
    }
63
64
    /**
65
     * Add whitespaces to the message of needed to fit to the box.
66
     */
67
    private static function getPreparedMessage(string $message, int $maxLength, int $additionalSpaces = 0): string
68
    {
69
        return $message . str_repeat(' ', $maxLength - strlen($message) + $additionalSpaces);
70
    }
71
72
    public static function indentText(string $text, int $indent = 2, int $width = 100, $prefix = ''): array
73
    {
74
        $wrapped = explode("\n", wordwrap($text, $width));
75
76
        $result = [];
77
78
        foreach ($wrapped as $line) {
79
            $result[] = $prefix . str_repeat(' ', $indent) . $line;
80
        }
81
82
        return $result;
83
    }
84
}
85