44
55namespace Flow \Types \Type \Logical ;
66
7- use function Flow \Types \DSL \type_string ;
87use Flow \Types \Exception \{CastingException , InvalidTypeException };
98use Flow \Types \Type ;
9+ use Flow \Types \Value \HTMLDocument ;
1010
1111/**
12- * @implements Type<\DOMDocument >
12+ * @implements Type<HTMLDocument >
1313 */
1414final readonly class HTMLType implements Type
1515{
16- public function assert (mixed $ value ) : \ DOMDocument
16+ public function assert (mixed $ value ) : HTMLDocument
1717 {
1818 if ($ this ->isValid ($ value )) {
1919 return $ value ;
@@ -22,42 +22,30 @@ public function assert(mixed $value) : \DOMDocument
2222 throw InvalidTypeException::value ($ value , $ this );
2323 }
2424
25- public function cast (mixed $ value ) : \ DOMDocument
25+ public function cast (mixed $ value ) : HTMLDocument
2626 {
2727 if ($ this ->isValid ($ value )) {
2828 return $ value ;
2929 }
3030
31- $ document = new \DOMDocument ();
32-
3331 if (\is_string ($ value )) {
34- if (!$ this ->isHtml ($ document , $ value )) {
35- throw new CastingException ($ value , $ this );
36- }
37-
38- return $ document ;
32+ return new HTMLDocument ($ value );
3933 }
4034
41- try {
42- $ stringValue = type_string ()->cast ($ value );
43-
44- if (!$ this ->isHtml ($ document , $ stringValue )) {
45- throw new CastingException ($ stringValue , $ this );
46- }
35+ if ($ value instanceof \DOMDocument) {
36+ return new HTMLDocument ($ value );
37+ }
4738
48- return $ document ;
49- } catch (CastingException $ e ) {
50- throw new CastingException ($ value , $ this , $ e );
39+ if (\is_object ($ value ) && \is_a ($ value , 'Dom\HTMLDocument ' )) {
40+ return new HTMLDocument ($ value );
5141 }
42+
43+ throw new CastingException ($ value , $ this );
5244 }
5345
5446 public function isValid (mixed $ value ) : bool
5547 {
56- if ($ value instanceof \DOMDocument) {
57- return $ this ->isHtml ($ value , (string ) $ value ->saveHTML ());
58- }
59-
60- return false ;
48+ return $ value instanceof HTMLDocument;
6149 }
6250
6351 public function normalize () : array
@@ -71,13 +59,4 @@ public function toString() : string
7159 {
7260 return 'html ' ;
7361 }
74-
75- private function isHtml (\DOMDocument $ document , string $ value ) : bool
76- {
77- if (\preg_match ('/(<!doctype(.+?)>)?<html(.+?)>(.+?)<\/html>/im ' , $ value ) !== 1 ) {
78- return false ;
79- }
80-
81- return (bool ) @$ document ->loadHTML ($ value , \LIBXML_HTML_NOIMPLIED | \LIBXML_HTML_NODEFDTD );
82- }
8362}
0 commit comments