Passed
Push — master ( c0fc71...d8bdb7 )
by Peter
02:23
created

StringHelper::wrapByLines()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 4
nop 2
dl 0
loc 18
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AbterPhp\Framework\Html\Helper;
6
7
use AbterPhp\Framework\Constant\Html5;
8
use AbterPhp\Framework\Html\IComponent;
9
10
class StringHelper
11
{
12
    /**
13
     * @param string|IComponent $content
14
     * @param string|null       $tag
15
     * @param array             $attributes
16
     *
17
     * @return string
18
     */
19
    public static function wrapInTag($content, string $tag = null, array $attributes = [])
20
    {
21
        if (null === $tag) {
22
            return (string)$content;
23
        }
24
25
        $attributeHtml = ArrayHelper::toAttributes($attributes);
26
27
        return sprintf('<%1$s%3$s>%2$s</%1$s>', $tag, (string)$content, $attributeHtml);
28
    }
29
30
    /**
31
     * @param string $tag
32
     * @param array  $attributes
33
     *
34
     * @return string
35
     */
36
    public static function createTag(string $tag, array $attributes = [])
37
    {
38
        $attributeHtml = ArrayHelper::toAttributes($attributes);
39
40
        return sprintf('<%1$s%2$s>', $tag, $attributeHtml);
41
    }
42
43
    /**
44
     * @param string $text
45
     * @param string $tag
46
     *
47
     * @return string
48
     */
49
    public static function wrapByLines(string $text, string $tag): string
50
    {
51
        if (empty($text)) {
52
            return '';
53
        }
54
55
        $paragraphs = explode(PHP_EOL, $text);
56
57
        $lines = [];
58
        foreach ($paragraphs as $paragraph) {
59
            if (empty($paragraph)) {
60
                continue;
61
            }
62
63
            $lines[] = static::wrapInTag(trim($paragraph), $tag);
64
        }
65
66
        return implode(PHP_EOL, $lines);
67
    }
68
}
69