1<?php
2
3namespace ComboStrap\Xml;
4
5
6use ComboStrap\ExceptionBadSyntax;
7
8
9/**
10 * Class HtmlUtility
11 * Static HTML utility
12 *
13 * On HTML as string, if you want to work on HTML as XML, see the {@link XmlSystems} class
14 *
15 * @package ComboStrap
16 *
17 * This class is based on {@link XmlDocument}
18 *
19 */
20class XhtmlUtility
21{
22
23
24    /**
25     * Return a diff
26     * @param string $left
27     * @param string $right
28     * @param bool $xhtml
29     * @param null $excludedAttributes
30     * @return string
31     * DOMDocument supports formatted XML while SimpleXMLElement does not.
32     * @throws ExceptionBadSyntax
33     */
34    public static function diffMarkup(string $left, string $right, $xhtml = true, $excludedAttributes = null): string
35    {
36        if (empty($right)) {
37            throw new \RuntimeException("The right text should not be empty");
38        }
39        if (empty($left)) {
40            throw new \RuntimeException("The left text should not be empty");
41        }
42        $loading = XmlDocument::XML_TYPE;
43        if (!$xhtml) {
44            $loading = XmlDocument::HTML_TYPE;
45        }
46        $leftDocument = (new XmlDocument($left, $loading))->getDomDocument();
47        $rightDocument = (new XmlDocument($right, $loading))->getDomDocument();
48
49        $error = "";
50        XmlSystems::diffNode(
51            $leftDocument,
52            $rightDocument,
53            $error,
54            $excludedAttributes
55        );
56
57        return $error;
58
59    }
60
61    /**
62     * @param $text
63     * @return int the number of lines estimated
64     */
65    public static function countLines($text)
66    {
67        return count(preg_split("/<\/p>|<\/h[1-9]{1}>|<br|<\/tr>|<\/li>|<hr>|<\/pre>/", $text)) - 1;
68    }
69
70
71    /**
72     * @throws ExceptionBadSyntax
73     */
74    public static function normalize($htmlText)
75    {
76        if (empty($htmlText)) {
77            throw new \RuntimeException("The text should not be empty");
78        }
79        $xmlDoc = new XmlDocument($htmlText, XmlDocument::HTML_TYPE);
80        return $xmlDoc->toXmlNormalized();
81    }
82
83
84
85
86}
87