Skip to content

Commit d31d8db

Browse files
committed
Adjust string type casting with HTML data
1 parent 80fdd27 commit d31d8db

2 files changed

Lines changed: 27 additions & 1 deletion

File tree

src/lib/types/src/Flow/Types/Type/Native/StringType.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
namespace Flow\Types\Type\Native;
66

77
use function Flow\Types\DSL\dom_element_to_string;
8+
use Dom\{HTMLDocument, HTMLElement};
89
use Flow\Types\Exception\{CastingException, InvalidTypeException};
910
use Flow\Types\Type;
1011

@@ -57,6 +58,14 @@ public function cast(mixed $value) : string
5758
return (string) dom_element_to_string($value);
5859
}
5960

61+
if ($value instanceof HTMLDocument) {
62+
return $value->saveHtml();
63+
}
64+
65+
if ($value instanceof HTMLElement) {
66+
return $value->innerHTML;
67+
}
68+
6069
if (null === $value) {
6170
return '';
6271
}

src/lib/types/tests/Flow/Types/Tests/Unit/Type/Native/StringTypeTest.php

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55
namespace Flow\Types\Tests\Unit\Type\Native;
66

77
use function Flow\Types\DSL\{type_from_array, type_string};
8+
use Dom\HTMLDocument;
89
use Flow\Types\Exception\InvalidTypeException;
910
use Flow\Types\Tests\Unit\Type\Fixtures\StringableObject;
10-
use PHPUnit\Framework\Attributes\DataProvider;
11+
use PHPUnit\Framework\Attributes\{DataProvider, RequiresPhp};
1112
use PHPUnit\Framework\TestCase;
1213

1314
final class StringTypeTest extends TestCase
@@ -215,6 +216,22 @@ public function test_cast(mixed $value, mixed $expected, ?string $exceptionClass
215216
}
216217
}
217218

219+
#[RequiresPhp('>= 8.4')]
220+
public function test_cast_html_document() : void
221+
{
222+
$element = HTMLDocument::createFromString('<p><span>foobar</span></p>', \LIBXML_HTML_NOIMPLIED | \LIBXML_NOERROR);
223+
224+
self::assertSame('<p><span>foobar</span></p>', type_string()->cast($element));
225+
}
226+
227+
#[RequiresPhp('>= 8.4')]
228+
public function test_cast_html_element() : void
229+
{
230+
$element = HTMLDocument::createFromString('<p><span>foobar</span></p>', \LIBXML_HTML_NOIMPLIED | \LIBXML_NOERROR);
231+
232+
self::assertSame('<span>foobar</span>', type_string()->cast($element->documentElement));
233+
}
234+
218235
#[DataProvider('is_stringable_data_provider')]
219236
public function test_is_stringable(mixed $value, bool $expected) : void
220237
{

0 commit comments

Comments
 (0)