diff --git a/src/BindFilter.php b/src/BindFilter.php new file mode 100644 index 0000000..31dbd16 --- /dev/null +++ b/src/BindFilter.php @@ -0,0 +1,43 @@ + */ + private array $dependencies = []; + + public function setDependency(object $dependency):void { + unset($this->dependencies[$dependency::class]); + $this->dependencies[$dependency::class] = $dependency; + } + + /** + * @template T of object + * @param class-string $class + * @return T|null + */ + public function getDependency(string $class):?object { + foreach(array_reverse($this->dependencies) as $dependency) { + if($dependency instanceof $class) { + return $dependency; + } + } + + return null; + } + + public function getFilter(string $name):?Closure { + if(method_exists(self::class, $name) || !method_exists($this, $name)) { + return null; + } + + $method = new ReflectionMethod($this, $name); + if(!$method->isPublic() || $method->isStatic()) { + return null; + } + + return $method->getClosure($this); + } +} diff --git a/src/BindFilterException.php b/src/BindFilterException.php new file mode 100644 index 0000000..fa8961e --- /dev/null +++ b/src/BindFilterException.php @@ -0,0 +1,12 @@ +, BindFilter> */ + private array $filters = []; + + public function register(BindFilter $filter):void { + unset($this->filters[$filter::class]); + $this->filters[$filter::class] = $filter; + } + + /** @return array{0:string, 1:mixed} */ + public function apply(string $expression, mixed $value):array { + $parts = explode(" ", $expression, 2); + if(isset($parts[1]) && str_starts_with(ltrim($parts[1]), "|")) { + throw new InvalidBindFilterExpressionException("", $expression); + } + $binding = explode("=", $parts[0], 2); + $chain = explode("|", $binding[0]); + $bindKey = array_shift($chain); + if($value instanceof BindableValue) { + $value = $chain ? $value->rawValue : $value->getBindingValue(); + } + $callbacks = []; + foreach($chain as $filterName) { + if(!preg_match('/^[a-z][a-z0-9_]*$/iD', $filterName)) { + throw new InvalidBindFilterExpressionException($filterName, $expression); + } + if(!$this->filters) { + throw new BindFilterNotRegisteredException($filterName, $expression); + } + $callback = $this->getFilter($filterName); + if(!$callback) { + throw new BindFilterNotFoundException($filterName, $expression); + } + $callbacks[] = $callback; + } + + foreach($callbacks as $callback) { + $value = $callback($value); + } + + $unfilteredExpression = $bindKey; + if(isset($binding[1])) { + $unfilteredExpression .= "=" . $binding[1]; + } + if(isset($parts[1])) { + $unfilteredExpression .= " " . $parts[1]; + } + + return [$unfilteredExpression, $value]; + } + + private function getFilter(string $name):?Closure { + foreach(array_reverse($this->filters) as $filter) { + if($callback = $filter->getFilter($name)) { + return $callback; + } + } + + return null; + } +} diff --git a/src/BindableCache.php b/src/BindableCache.php index 4570ab0..ab6cc47 100644 --- a/src/BindableCache.php +++ b/src/BindableCache.php @@ -10,7 +10,6 @@ use ReflectionProperty as RefProperty; use ReflectionProperty; use stdClass; -use Stringable; class BindableCache { /** @@ -119,8 +118,8 @@ private function addMethodBindings( $methodName = $reflectionMethod->getName(); foreach($this->getBindAttributes($reflectionMethod) as $reflectionAttribute) { $bindKey = $this->getBindKey($reflectionAttribute, $reflectionMethod); - $attributeCache[$bindKey] = fn(object $object):null|iterable|string - => $this->nullableStringOrIterable($object, $methodName); + $attributeCache[$bindKey] = fn(object $object):mixed + => $this->readBindableValue($object, $methodName); $this->cacheNestedClassName( $objectKeys, $bindKey, @@ -144,8 +143,8 @@ private function addPropertyBindings( if(!empty($attributeList)) { foreach($attributeList as $reflectionAttribute) { $bindKey = $this->getBindKey($reflectionAttribute); - $attributeCache[$bindKey] = fn(object $object):null|iterable|string - => $this->nullableStringOrIterable($object, $propertyName); + $attributeCache[$bindKey] = fn(object $object):mixed + => $this->readBindableValue($object, $propertyName); $this->cacheNestedClassName( $objectKeys, $bindKey, @@ -160,9 +159,9 @@ private function addPropertyBindings( return; } - $attributeCache[$propertyName] = fn(object $object):null|iterable|string + $attributeCache[$propertyName] = fn(object $object):mixed => isset($object->$propertyName) - ? $this->nullableStringOrIterable($object, $propertyName) + ? $this->readBindableValue($object, $propertyName) : null; $this->cacheNestedClassName( $objectKeys, @@ -249,8 +248,8 @@ private function appendNestedBindableKeys( } /** - * @param object|array $object - * @return array + * @param object|array $object + * @return array */ public function convertToKvp(object|array $object):array { if(is_array($object)) { @@ -261,25 +260,42 @@ public function convertToKvp(object|array $object):array { return $this->stringifyMap(get_object_vars($object)); } + return array_map( + fn(mixed $value):mixed => $value instanceof BindableValue ? $value->getBindingValue() : $value, + $this->convertToBindableValues($object), + ); + } + + /** + * Retain original values alongside their ordinary binding representation. + * @param object|array $object + * @return array + */ + public function convertToBindableValues(object|array $object):array { + if(is_array($object)) { + return $object; + } + + if($object instanceof stdClass) { + return array_map($this->preserveValue(...), get_object_vars($object)); + } + if(!$this->isBindable($object)) { return []; } - return $this->convertBindableObjectToKvp($object); - } - - /** @return array> */ - private function convertBindableObjectToKvp(object $object):array { - $kvp = []; + $values = []; foreach($this->bindableClassMap[$object::class] as $key => $valueGetter) { $targetObject = $this->resolveTargetObject($object, $key); - $value = $targetObject - ? $valueGetter($targetObject) - : null; - $kvp[$key] = $this->normalizeValue($value); + $value = $targetObject ? $valueGetter($targetObject) : null; + $values[$key] = $this->preserveValue($value); } - return $kvp; + return $values; + } + + private function preserveValue(mixed $value):mixed { + return is_iterable($value) ? $value : new BindableValue($value); } private function resolveTargetObject(object $object, string $key):?object { @@ -392,31 +408,13 @@ private function isAttribute( return strcasecmp($reflectionAttribute->getName(), $className) === 0; } - /** @return null|string|array */ - private function nullableStringOrIterable( - object $object, - string $keyOrMethod, - ):null|iterable|string { + private function readBindableValue(object $object, string $keyOrMethod):mixed { if(method_exists($object, $keyOrMethod)) { - $value = $object->$keyOrMethod(); - } - elseif(property_exists($object, $keyOrMethod)) { - $value = $object->$keyOrMethod; - } - else { - return null; + return $object->$keyOrMethod(); } - if(is_scalar($value)) { - return $value; - } - elseif(is_iterable($value)) { - return $value; - } - elseif(is_object($value)) { - if($value instanceof Stringable || method_exists($value, "__toString")) { - return (string)$value; - } + if(property_exists($object, $keyOrMethod)) { + return $object->$keyOrMethod; } return null; diff --git a/src/BindableValue.php b/src/BindableValue.php new file mode 100644 index 0000000..c818a89 --- /dev/null +++ b/src/BindableValue.php @@ -0,0 +1,25 @@ +resolved) { + $this->bindingValue = match(true) { + is_iterable($this->rawValue), is_null($this->rawValue) => $this->rawValue, + is_scalar($this->rawValue), $this->rawValue instanceof Stringable => (string)$this->rawValue, + default => null, + }; + $this->resolved = true; + } + + return $this->bindingValue; + } +} diff --git a/src/Binder.php b/src/Binder.php index 888c14c..4f9fd59 100644 --- a/src/Binder.php +++ b/src/Binder.php @@ -4,6 +4,8 @@ use GT\Dom\Element; abstract class Binder { + abstract public function registerBindFilter(BindFilter $filter):void; + abstract public function bindValue( mixed $value, null|string|Element $context = null diff --git a/src/DocumentBinder.php b/src/DocumentBinder.php index e9f981e..4f5be2a 100644 --- a/src/DocumentBinder.php +++ b/src/DocumentBinder.php @@ -35,6 +35,10 @@ public function setDependencies( $this->bindableCache = $bindableCache; } + public function registerBindFilter(BindFilter $filter):void { + $this->elementBinder->registerBindFilter($filter); + } + /** * Applies the string value of $value anywhere within $context that * has a data-bind attribute with no specified key. @@ -101,7 +105,7 @@ public function bindData( if(is_object($kvp)) { if($this->bindableCache->isBindable($kvp)) { $object = $kvp; - $kvp = $this->bindableCache->convertToKvp($kvp); + $kvp = $this->bindableCache->convertToBindableValues($kvp); } } diff --git a/src/ElementBinder.php b/src/ElementBinder.php index fc5dd46..cc42c20 100644 --- a/src/ElementBinder.php +++ b/src/ElementBinder.php @@ -8,6 +8,10 @@ class ElementBinder { private HTMLAttributeCollection $htmlAttributeCollection; private PlaceholderBinder $placeholderBinder; + public function registerBindFilter(BindFilter $filter):void { + $this->htmlAttributeBinder->registerBindFilter($filter); + } + public function setDebugSource(?string $debugSource):void { $this->htmlAttributeBinder->setDebugSource($debugSource); } @@ -31,16 +35,17 @@ public function bind( mixed $value, Element $context ):void { - if(!is_null($value) && !is_scalar($value) && !is_iterable($value)) { - $value = new BindValue($value); - } - /** @var Element $element */ foreach($this->htmlAttributeCollection->find($context) as $element) { $this->htmlAttributeBinder->expandAttributes($element); $this->htmlAttributeBinder->bind($key, $value, $element); } + if(!is_null($value) && !is_scalar($value) && !is_iterable($value) + && !$value instanceof BindableValue) { + $value = new BindValue($value); + } + $this->placeholderBinder->bind($key, $value, $context); } } diff --git a/src/HTMLAttributeBinder.php b/src/HTMLAttributeBinder.php index d7df557..ab52aaf 100644 --- a/src/HTMLAttributeBinder.php +++ b/src/HTMLAttributeBinder.php @@ -10,6 +10,12 @@ class HTMLAttributeBinder { private ListBinder $listBinder; private TableBinder $tableBinder; private ?string $debugSource = null; + private ?BindFilterPipeline $filterPipeline = null; + + public function registerBindFilter(BindFilter $filter):void { + $this->filterPipeline ??= new BindFilterPipeline(); + $this->filterPipeline->register($filter); + } public function setDependencies(ListBinder $listBinder, TableBinder $tableBinder):void { $this->listBinder = $listBinder; @@ -25,30 +31,42 @@ public function bind( mixed $value, Document|Element $element ):void { - if(is_null($value)) { - return; - } - if($element instanceof Document) { $element = $element->documentElement; } - $bindValue = $this->standardiseBindValue($value); $attributesToRemove = []; $attributeUpdates = []; foreach($element->attributes as $attributeName => $attribute) { /** @var Attr $attribute */ - $this->markBoundElement($element, $attribute, $key, $bindValue); + $this->markBoundElement($element, $attribute, $key, $value); if(!$this->shouldHandleAttribute($attributeName)) { continue; } + if((is_null($value) || ($value instanceof BindableValue && is_null($value->rawValue))) + && !str_contains($attribute->value, "|")) { + continue; + } + $bindProperty = $this->getBindProperty($element, $attributeName); - [$modifier, $remainingExpressions] = $this->resolveModifier($key, $attribute->value); + [$modifier, $remainingExpressions, $expression] = $this->resolveModifier( + $key, $attribute->value, + ); if($modifier === false) { continue; } + $this->filterPipeline ??= new BindFilterPipeline(); + [$unfilteredExpression, $filteredValue] = $this->filterPipeline->apply($expression, $value); + if(is_null($filteredValue)) { + continue; + } + if(is_string($modifier)) { + $modifier = $unfilteredExpression; + } + $bindValue = $this->standardiseBindValue($filteredValue); + $this->setBindProperty( $element, $bindProperty, @@ -124,6 +142,13 @@ private function markBoundElement( return; } + if($value instanceof BindableValue) { + $value = $value->getBindingValue(); + } + if(is_null($value)) { + return; + } + $bindKey = $attribute->value; if(str_starts_with($bindKey, "!")) { $bindKey = substr($bindKey, 1); @@ -174,17 +199,18 @@ private function getBindProperty( return substr($attributeName, strpos($attributeName, ":") + 1); } - /** @return array{0:string|false|null, 1:array} */ + /** @return array{0:string|false|null, 1:array, 2:string} */ private function resolveModifier( ?string $key, string $attributeValue, ):array { - if(is_null($key)) { + if(is_null($key) && !str_starts_with($attributeValue, "|")) { return [ $attributeValue === "" ? null : false, [], + $attributeValue, ]; } @@ -194,7 +220,8 @@ private function resolveModifier( $trimmedExpression = ltrim($expression, ":!?"); $trimmedExpression = strtok($trimmedExpression, " "); $bindKey = $this->extractBindKey($trimmedExpression); - if(is_null($matchingExpression) && ($key === $bindKey || $bindKey === "@")) { + if(is_null($matchingExpression) + && (($key ?? "") === $bindKey || ($key !== null && $bindKey === "@"))) { $matchingExpression = $expression; continue; } @@ -203,7 +230,7 @@ private function resolveModifier( } if(is_null($matchingExpression)) { - return [false, []]; + return [false, [], ""]; } return [ @@ -211,6 +238,7 @@ private function resolveModifier( ? $matchingExpression : null, $remainingExpressions, + $matchingExpression, ]; } @@ -470,6 +498,7 @@ function(array $matches)use($element):string { private function extractBindKey(string $bindExpression):string { [$bindKey] = explode("=", $bindExpression, 2); + [$bindKey] = explode("|", $bindKey, 2); return $bindKey; } diff --git a/src/InvalidBindFilterExpressionException.php b/src/InvalidBindFilterExpressionException.php new file mode 100644 index 0000000..c45cfd8 --- /dev/null +++ b/src/InvalidBindFilterExpressionException.php @@ -0,0 +1,12 @@ +canNormalizeObject($listValue); $listValue = $this->normalizeListValue($listValue); if($callback) { - $callbackValue = $callback($template, $listValue, $listKey); + $callbackInput = is_array($listValue) + ? array_map(fn(mixed $value):mixed => $value instanceof BindableValue + ? $value->getBindingValue() : $value, $listValue) + : $listValue; + $callbackValue = $callback($template, $callbackInput, $listKey); if(!is_null($callbackValue)) { $listValue = $callbackValue; } @@ -141,7 +145,7 @@ private function bindNestedListItem( ):int { $this->elementBinder->bind(null, $listKey, $template); $this->bindListData($listValue, $template); - foreach($this->bindableCache->convertToKvp($listValue) as $key => $value) { + foreach($this->bindableCache->convertToBindableValues($listValue) as $key => $value) { $this->elementBinder->bind($key, $value, $template); } @@ -154,7 +158,7 @@ private function normalizeListValue(mixed $listValue):mixed { } if(is_object($listValue) && $this->bindableCache->isBindable($listValue)) { - return $this->bindableCache->convertToKvp($listValue); + return $this->bindableCache->convertToBindableValues($listValue); } return $listValue; diff --git a/src/PlaceholderBinder.php b/src/PlaceholderBinder.php index bd67393..26ce801 100644 --- a/src/PlaceholderBinder.php +++ b/src/PlaceholderBinder.php @@ -49,9 +49,10 @@ public function bind( continue; } + $bindValue = $value instanceof BindableValue ? $value->getBindingValue() : $value; $valueToUse = $matches["DEFAULT"][$i]; - if(!is_null($value) && $value !== "") { - $valueToUse = $value; + if(!is_null($bindValue) && $bindValue !== "") { + $valueToUse = $bindValue; } $nodeValue = str_replace( diff --git a/src/TableBinder.php b/src/TableBinder.php index 72d3e46..53b589d 100644 --- a/src/TableBinder.php +++ b/src/TableBinder.php @@ -290,7 +290,7 @@ private function resolveCellElement( int $headerIndex, string $cellType, ):Element { - if($headerIndex < $tableRow->cells->length - 1) { + if($headerIndex < $tableRow->cells->length) { return $tableRow->cells[$headerIndex]; } diff --git a/test/phpunit/BindFilterTest.php b/test/phpunit/BindFilterTest.php new file mode 100644 index 0000000..17b52e7 --- /dev/null +++ b/test/phpunit/BindFilterTest.php @@ -0,0 +1,46 @@ +getDependency(Countable::class)); + $first = new ArrayObject([1]); + $sut->setDependency($first); + self::assertSame($first, $sut->getDependency(Countable::class)); + self::assertSame($first, $sut->getDependency(ArrayObject::class)); + self::assertNull($sut->getDependency(stdClass::class)); + + $second = new ArrayObject([1, 2]); + $sut->setDependency($second); + self::assertSame($second, $sut->getDependency(Countable::class)); + } + + public function testGetFilter_exposesPublicInstanceMethods():void { + $sut = new class extends BindFilter { + public function upper(string $value):string { + return strtoupper($value); + } + protected function hidden(string $value):string { + return $value; + } + public static function static(string $value):string { + return $value; + } + public function helper(string $value):string { + return $value; + } + }; + self::assertSame("HELLO", $sut->getFilter("upper")("hello")); + self::assertSame("hello", $sut->getFilter("helper")("hello")); + foreach(["hidden", "static", "setDependency", "getDependency", "getFilter", "missing"] as $name) { + self::assertNull($sut->getFilter($name)); + } + } +} diff --git a/test/phpunit/BindableCacheTest.php b/test/phpunit/BindableCacheTest.php index 95c5bee..2969b55 100644 --- a/test/phpunit/BindableCacheTest.php +++ b/test/phpunit/BindableCacheTest.php @@ -42,6 +42,41 @@ public function getName():string { self::assertTrue($sut->isBindable($obj2)); } + public function testConvertToKvp_associativeArrayRetainsOriginalValues():void { + $date = new \DateTimeImmutable("2026-11-07"); + $data = ["amount" => 12345.5, "date" => $date, "available" => false, "description" => null]; + $sut = new BindableCache(); + + $result = $sut->convertToKvp($data); + + self::assertSame($data, $result); + self::assertSame($date, $result["date"]); + } + + public function testConvertToKvp_stdClassKeepsItsExistingPresentationContract():void { + $label = new class implements \Stringable { + public function __toString():string { + return "Invoice"; + } + }; + $data = (object)[ + "amount" => 12345.5, + "available" => false, + "description" => null, + "items" => [["name" => "First"]], + "label" => $label, + ]; + $sut = new BindableCache(); + + self::assertSame([ + "amount" => "12345.5", + "available" => "", + "description" => null, + "items" => [["name" => "First"]], + "label" => "Invoice", + ], $sut->convertToKvp($data)); + } + public function testConvertToKvp_getter():void { $obj = new class { #[BindGetter] @@ -266,12 +301,12 @@ public function testReadNestedObjectValue_missingPropertyReturnsNull():void { ); } - public function testNullableStringOrIterable_missingMemberReturnsNull():void { + public function testReadBindableValue_missingMemberReturnsNull():void { $sut = new BindableCache(); $object = new class {}; self::assertNull( - $this->invokeBindableCacheMethod($sut, "nullableStringOrIterable", $object, "missing"), + $this->invokeBindableCacheMethod($sut, "readBindableValue", $object, "missing"), ); } diff --git a/test/phpunit/DocumentBinderTest.php b/test/phpunit/DocumentBinderTest.php index 8085189..d9619bc 100644 --- a/test/phpunit/DocumentBinderTest.php +++ b/test/phpunit/DocumentBinderTest.php @@ -43,6 +43,15 @@ use Traversable; use ArrayIterator; +use GT\DomTemplate\BindFilter; +use GT\DomTemplate\BindFilterException; +use GT\DomTemplate\BindFilterNotFoundException; +use GT\DomTemplate\BindFilterNotRegisteredException; +use GT\DomTemplate\InvalidBindFilterExpressionException; +use DateTimeImmutable; +use DateTimeInterface; +use RuntimeException; + class DocumentBinderTest extends PartialContentTestCase { /** * If the developer forgets to add a bind property (the bit after the @@ -2247,6 +2256,450 @@ public function testBindListCallback_bindGetter():void { } } + public function testBindKeyValue_chainsFiltersWithoutChangingOtherBindings():void { + $document = new HTMLDocument('

' + . '

'); + $sut = $this->createFilterBinder($document); + $sut->registerBindFilter(new class extends BindFilter { + public function numericOutput(float $value):string { + return number_format($value, 2); + } + public function currency(string $value):string { + return "£" . $value; + } + }); + + $sut->bindKeyValue("amount", 12345); + + self::assertSame("£12,345.00", $document->querySelector("#formatted")->textContent); + self::assertSame("12345", $document->querySelector("#raw")->textContent); + } + + public function testRegisterBindFilter_laterOverridesAndEarlierFallbacks():void { + $document = new HTMLDocument('

' + . ''); + $sut = $this->createFilterBinder($document); + $sut->registerBindFilter(new class extends BindFilter { + public function number(int $value):string { + return number_format($value, 2); + } + public function currency(string $value):string { + return "£" . $value; + } + }); + $application = new class extends BindFilter { + public function currency(string $value):string { + return ($this->getDependency(stdClass::class)?->symbol ?? "€") . $value; + } + }; + $application->setDependency((object)["symbol" => "$"]); + $sut->registerBindFilter($application); + $sut->bindKeyValue("amount", 12345); + + self::assertSame("$12,345.00", $document->querySelector("p")->textContent); + self::assertSame("12,345.00", $document->querySelector("b")->textContent); + } + + public function testRegisterBindFilter_replacesSameClassAndUpdatesPrecedence():void { + $document = new HTMLDocument('

'); + $sut = $this->createFilterBinder($document); + $first = new class extends BindFilter { + public string $prefix = "first "; + public function label(string $value):string { + return $this->prefix . $value; + } + }; + $sut->registerBindFilter($first); + $sut->registerBindFilter(new class extends BindFilter { + public function label(string $value):string { + return "second " . $value; + } + }); + $sut->bindKeyValue("name", "hello"); + self::assertSame("second hello", $document->querySelector("p")->textContent); + $replacement = clone $first; + $replacement->prefix = "replacement "; + $sut->registerBindFilter($replacement); + $sut->bindKeyValue("name", "hello"); + self::assertSame("replacement hello", $document->querySelector("p")->textContent); + } + + public function testBindKeyValue_filtersRawObjectsBeforeConversion():void { + $document = new HTMLDocument('

'); + $sut = $this->createFilterBinder($document); + $sut->registerBindFilter(new class extends BindFilter { + public function date(DateTimeInterface $value):string { + return $value->format("Y-m-d"); + } + }); + $sut->bindKeyValue("date", new DateTimeImmutable("2026-11-06")); + self::assertSame("2026-11-06", $document->querySelector("p")->textContent); + } + + public function testBindData_preservesFilterInputTypes():void { + $value = new class { + #[BindGetter] + public function getDate():DateTimeImmutable { + return new DateTimeImmutable("2026-11-06"); + } + #[BindGetter] + public function getAmount():int { + return 12345; + } + }; + $document = new HTMLDocument('

  • ' + . '
'); + $sut = $this->createFilterBinder($document); + $sut->registerBindFilter(new class extends BindFilter { + public function date(DateTimeInterface $value):string { + return $value->format("Y-m-d"); + } + public function type(mixed $value):string { + return get_debug_type($value); + } + }); + $sut->bindData($value, "p"); + $sut->bindList([$value]); + self::assertSame("2026-11-06", $document->querySelector("p")->textContent); + self::assertSame("2026-11-06", $document->querySelector("li span")->textContent); + self::assertSame("int", $document->querySelector("li b")->textContent); + } + + public function testBindKeyValue_filtersNullAndSkipsNullResults():void { + $document = new HTMLDocument('

Original

' + . '

Original

' + . '

Original

'); + $sut = $this->createFilterBinder($document); + $sut->registerBindFilter(new class extends BindFilter { + public function fallback(mixed $value):string { + return $value ?? "Default"; + } + public function ignore(mixed $value):mixed { + return null; + } + }); + $sut->bindKeyValue("value", null); + self::assertSame("Default", $document->querySelector("#fallback")->textContent); + self::assertFalse($document->querySelector("#fallback")->hasAttribute("data-bind:text")); + self::assertSame("Original", $document->querySelector("#ignored")->textContent); + self::assertTrue($document->querySelector("#ignored")->hasAttribute("data-bind:text")); + self::assertSame("Original", $document->querySelector("#raw")->textContent); + } + + public function testBindKeyValue_filtersWithModifiersAndRebinding():void { + $document = new HTMLDocument('
' + . ''); + $sut = $this->createFilterBinder($document); + $sut->registerBindFilter(new class extends BindFilter { + public function positive(int $value):bool { + return $value > 0; + } + public function lower(string $value):string { + return strtolower($value); + } + }); + $div = $document->querySelector("div"); + $sut->bindKeyValue("amount", 5); + self::assertSame("active", $div->className); + $sut->bindKeyValue("hidden", 1); + self::assertTrue($div->classList->contains("active")); + self::assertTrue($div->classList->contains("hidden")); + $sut->bindKeyValue("amount", -1); + self::assertSame("hidden", $div->className); + $sut->bindKeyValue("status", "BLOCKED"); + self::assertTrue($document->querySelector("button")->hasAttribute("disabled")); + $sut->bindKeyValue("status", "READY"); + self::assertFalse($document->querySelector("button")->hasAttribute("disabled")); + } + + public function testBindKeyValue_keepsRemainingFilterExpressions():void { + $document = new HTMLDocument('
'); + $sut = $this->createFilterBinder($document); + $sut->registerBindFilter(new class extends BindFilter { + public function positive(int $value):bool { + return $value > 0; + } + }); + $sut->bindKeyValue("one", 1); + self::assertSame(":two|positive second", $document->querySelector("div")->getAttribute("data-bind:class")); + $sut->bindKeyValue("two", 2); + self::assertSame("first second", $document->querySelector("div")->className); + self::assertFalse($document->querySelector("div")->hasAttribute("data-bind:class")); + } + + public function testRegisterBindFilter_sharesProviderWithComponentsAndLists():void { + $document = new HTMLDocument('

' + . '

'); + $dependencies = $this->documentBinderDependencies($document); + $sut = new DocumentBinder($document); + $sut->setDependencies(...$dependencies); + $component = new ComponentBinder($document); + $component->setDependencies(...$dependencies); + $component->setComponentBinderDependencies($document->querySelector("section")); + $filter = new class extends BindFilter { + public int $calls = 0; + public function label(string $value):string { + $this->calls++; + return ($this->getDependency(stdClass::class)?->prefix ?? "") . $value; + } + }; + $sut->registerBindFilter($filter); + $filter->setDependency((object)["prefix" => "Hello "]); + $sut->bindKeyValue("name", "Page", "#page"); + $component->bindKeyValue("name", "Component", "p"); + $component->bindList([["name" => "One"], ["name" => "Two"]]); + self::assertSame("Hello Page", $document->querySelector("#page")->textContent); + self::assertSame("Hello Component", $document->querySelector("section p")->textContent); + self::assertSame("Hello One", $document->querySelectorAll("li")[0]->textContent); + self::assertSame("Hello Two", $document->querySelectorAll("li")[1]->textContent); + self::assertSame(4, $filter->calls); + } + + public function testBindValue_filtersAnonymousBindings():void { + $document = new HTMLDocument('

{{}}'); + $sut = $this->createFilterBinder($document); + $sut->registerBindFilter(new class extends BindFilter { + public function upper(string $value):string { + return strtoupper($value); + } + }); + $sut->bindValue("hello"); + self::assertSame("HELLO", $document->querySelector("p")->textContent); + self::assertSame("hello", $document->querySelector("span")->textContent); + } + + public function testBindKeyValue_unmatchedFiltersDoNotRequireRegistration():void { + $document = new HTMLDocument('

Original

'); + $sut = $this->createFilterBinder($document); + $sut->bindKeyValue("name", "hello"); + self::assertSame("Original", $document->querySelector("p")->textContent); + self::assertSame("hello", $document->querySelector("span")->textContent); + } + + #[DataProvider("invalidExpressions")] + public function testBindKeyValue_invalidFiltersExposeExpression(string $expression, string $exceptionClass, bool $registered):void { + $document = new HTMLDocument('

Original

'); + $sut = $this->createFilterBinder($document); + if($registered) { + $sut->registerBindFilter(new class extends BindFilter {}); + } + try { + $sut->bindKeyValue("name", "hello"); + self::fail("Expected a filter exception"); + } + catch(BindFilterException $exception) { + self::assertInstanceOf($exceptionClass, $exception); + self::assertSame($expression, $exception->expression); + self::assertStringContainsString($expression, $exception->getMessage()); + self::assertSame("Original", $document->querySelector("p")->textContent); + self::assertSame($expression, $document->querySelector("p")->getAttribute("data-bind:text")); + } + } + + public static function invalidExpressions():iterable { + yield ["name|upper", BindFilterNotRegisteredException::class, false]; + yield ["name|upper", BindFilterNotFoundException::class, true]; + yield ["name|", InvalidBindFilterExpressionException::class, true]; + yield ["name||upper", InvalidBindFilterExpressionException::class, true]; + yield ["name |upper", InvalidBindFilterExpressionException::class, true]; + yield ["name|upper()", InvalidBindFilterExpressionException::class, true]; + yield ["name|setDependency", BindFilterNotFoundException::class, true]; + } + + public function testBindKeyValue_filtersListsAndTheirRows():void { + $document = new HTMLDocument('
    ' + . '
'); + $sut = $this->createFilterBinder($document); + $sut->registerBindFilter(new class extends BindFilter { + public function reverse(array $value):array { + return array_reverse($value); + } + public function upper(string $value):string { + return strtoupper($value); + } + }); + $sut->bindKeyValue("items", [["name" => "one"], ["name" => "two"]]); + self::assertSame("TWO", $document->querySelectorAll("li")[0]->textContent); + self::assertSame("ONE", $document->querySelectorAll("li")[1]->textContent); + } + + public function testBindData_doesNotStringifyFilterInput():void { + $value = new class implements \Stringable { + public string $label = "raw"; + public function __toString():string { + throw new RuntimeException("Do not stringify before filtering"); + } + }; + $document = new HTMLDocument('

'); + $sut = $this->createFilterBinder($document); + $sut->registerBindFilter(new class extends BindFilter { + public function label(object $value):string { + return $value->label; + } + }); + $sut->bindData((object)["value" => $value]); + self::assertSame("raw", $document->querySelector("p")->textContent); + } + + public function testBindData_convertsOrdinaryValuesOnce():void { + $value = new class implements \Stringable { + public int $calls = 0; + public function __toString():string { + $this->calls++; + return "hello"; + } + }; + $document = new HTMLDocument('

{{value}}'); + $sut = $this->createFilterBinder($document); + $sut->bindData((object)["value" => $value]); + self::assertSame("hello", $document->querySelector("p")->textContent); + self::assertSame("hello", $document->querySelector("b")->textContent); + self::assertSame("hello", $document->querySelector("span")->textContent); + self::assertSame(1, $value->calls); + } + + public function testBindListCallback_keepsOrdinaryValues():void { + $document = new HTMLDocument('
  • ' + . '{{amount}}
'); + $sut = $this->createFilterBinder($document); + $sut->registerBindFilter(new class extends BindFilter { + public function type(mixed $value):string { + return get_debug_type($value); + } + }); + $sut->bindListCallback([(object)["amount" => 25]], function($element, $value):void { + self::assertSame(["amount" => "25"], $value); + }); + self::assertSame("int", $document->querySelector("b")->textContent); + self::assertSame("25", $document->querySelector("span")->textContent); + } + + public function testRegisterBindFilter_doesNotAffectIndependentDocuments():void { + $firstDocument = new HTMLDocument('

'); + $otherBinder = $this->createFilterBinder($firstDocument); + $otherBinder->registerBindFilter(new class extends BindFilter { + public function upper(string $value):string { + return strtoupper($value); + } + }); + $sut = $this->createFilterBinder(new HTMLDocument('

')); + $this->expectException(BindFilterNotRegisteredException::class); + $sut->bindKeyValue("name", "hello"); + } + + public function testBindKeyValue_retainsOriginalFilterExceptions():void { + $document = new HTMLDocument('

Original

'); + $sut = $this->createFilterBinder($document); + $failure = new RuntimeException("Filter failed"); + $sut->registerBindFilter(new class($failure) extends BindFilter { + public function __construct(private RuntimeException $failure) {} + public function broken(mixed $value):mixed { + throw $this->failure; + } + }); + try { + $sut->bindKeyValue("name", "hello"); + self::fail("Expected the original exception"); + } + catch(RuntimeException $exception) { + self::assertSame($failure, $exception); + self::assertSame("Original", $document->querySelector("p")->textContent); + } + } + + #[DataProvider("filteredOptionalElementStates")] + public function testBindData_filtersWithinOptionalElements(?bool $visible, ?string $expectedId):void { + $document = new HTMLDocument('
' + . '
' + . '
'); + $sut = $this->createFilterBinder($document); + $sut->registerBindFilter(new class extends BindFilter { + public function upper(string $value):string { + return strtoupper($value); + } + }); + + $sut->bindData((object)["visible" => $visible, "label" => "hello"]); + $sut->cleanupDocument(); + + if($expectedId === null) { + self::assertCount(0, $document->querySelectorAll("section")); + return; + } + + self::assertCount(1, $document->querySelectorAll("section")); + self::assertSame($expectedId, $document->querySelector("section")->id); + self::assertSame("HELLO", $document->querySelector("section span")->textContent); + } + + public static function filteredOptionalElementStates():iterable { + yield "visible" => [true, "visible"]; + yield "inverse" => [false, "hidden"]; + yield "not supplied" => [null, null]; + } + + public function testBindListCallback_filtersTheReturnedScalarValue():void { + $document = new HTMLDocument('
'); + $sut = $this->createFilterBinder($document); + $sut->registerBindFilter(new class extends BindFilter { + public function upper(string $value):string { + return strtoupper($value); + } + }); + $seen = []; + + $count = $sut->bindListCallback(["first", "second"], function(Element $element, string $value, int $key)use(&$seen):string { + $seen[] = [$key, $value]; + return "item $key: $value"; + }); + $sut->cleanupDocument(); + + self::assertSame(2, $count); + self::assertSame([[0, "first"], [1, "second"]], $seen); + self::assertSame("ITEM 0: FIRST", $document->querySelectorAll("li")[0]->textContent); + self::assertSame("ITEM 1: SECOND", $document->querySelectorAll("li")[1]->textContent); + } + + public function testBindTable_chainsFiltersFromSharedProvidersInRowTemplates():void { + $document = new HTMLDocument('' + . '' + . '' + . '
CustomerTotal
'); + $sut = $this->createFilterBinder($document); + $sut->registerBindFilter(new class extends BindFilter { + public function upper(string $value):string { + return strtoupper($value); + } + public function decimal(float $value):string { + return number_format($value, 2); + } + }); + $applicationFilters = new class extends BindFilter { + public function currency(string $value):string { + return $this->getDependency(stdClass::class)->symbol . $value; + } + }; + $applicationFilters->setDependency((object)["symbol" => "€"]); + $sut->registerBindFilter($applicationFilters); + + $sut->bindTable([["name" => "Ada", "amount" => 12345.5], ["name" => "Grace", "amount" => 25]]); + $sut->cleanupDocument(); + + $rows = $document->querySelectorAll("tbody tr"); + self::assertCount(2, $rows); + self::assertCount(2, $rows[0]->cells); + self::assertSame("ADA", $rows[0]->cells[0]->textContent); + self::assertSame("€12,345.50", $rows[0]->cells[1]->textContent); + self::assertSame("GRACE", $rows[1]->cells[0]->textContent); + self::assertSame("€25.00", $rows[1]->cells[1]->textContent); + } + + private function createFilterBinder(HTMLDocument $document):DocumentBinder { + $binder = new DocumentBinder($document); + $binder->setDependencies(...$this->documentBinderDependencies($document)); + return $binder; + } + private function documentBinderDependencies(HTMLDocument $document, mixed...$otherObjectList):array { $htmlAttributeBinder = new HTMLAttributeBinder(); $htmlAttributeCollection = new HTMLAttributeCollection();