Passed
Push — master ( aa8b2f...66cf9e )
by Sebastian
04:39
created

HTMLHelper::injectAtEnd()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
c 0
b 0
f 0
dl 0
loc 18
rs 9.9332
cc 3
nc 3
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AppUtils;
6
7
class HTMLHelper
8
{
9
    public static function stripComments(string $html) : string
10
    {
11
        return preg_replace('/<!--(?!<!)[^\[>].*?-->/si', '', $html);
12
    }
13
14
    private static $newParaTags = array(
15
        'ul',
16
        'ol',
17
        'iframe',
18
        'table'
19
    );
20
21
    /**
22
     * Injects the target text at the end of an HTML snippet,
23
     * either in an existing <p> tag, or in a new <p> tag if
24
     * the last block tag cannot be used (<ul> for example).
25
     *
26
     * NOTE: Assumes that it is not a whole HTML document.
27
     *
28
     * @param string $text
29
     * @param string $html
30
     * @return string
31
     */
32
    public static function injectAtEnd(string $text, string $html) : string
33
    {
34
        preg_match_all('%<([A-Z][A-Z0-9]*)\b[^>]*>(.*?)</\1>%si', $html, $result, PREG_PATTERN_ORDER);
35
36
        if(empty($result[1])) {
37
            return '<p>'.$text.'</p>';
38
        }
39
40
        $tagName = array_pop($result[1]);
41
        $pos = strrpos($html, '</'.$tagName.'>');
42
43
        if(in_array(strtolower($tagName), self::$newParaTags)) {
44
            $replace = '</'.$tagName.'><p>'.$text.'</p>';
45
        } else {
46
            $replace = $text.'</'.$tagName.'>';
47
        }
48
49
        return substr_replace($html, $replace, $pos, strlen($html));
0 ignored issues
show
Bug Best Practice introduced by
The expression return substr_replace($h...e, $pos, strlen($html)) could return the type array which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
50
    }
51
}
52