From 92991ab2f3d2812b7a1e9add5b4ef35edec43fa2 Mon Sep 17 00:00:00 2001
From: Greg Bowler
Date: Fri, 6 Nov 2026 12:30:41 +0000
Subject: [PATCH 1/7] test: cover bind filter chains, shared providers and
optional dependencies
---
test/phpunit/BindFilterBindingTest.php | 351 +++++++++++++++++++++++++
test/phpunit/BindFilterTest.php | 45 ++++
2 files changed, 396 insertions(+)
create mode 100644 test/phpunit/BindFilterBindingTest.php
create mode 100644 test/phpunit/BindFilterTest.php
diff --git a/test/phpunit/BindFilterBindingTest.php b/test/phpunit/BindFilterBindingTest.php
new file mode 100644
index 0000000..f0e5217
--- /dev/null
+++ b/test/phpunit/BindFilterBindingTest.php
@@ -0,0 +1,351 @@
+
'
+ . '
');
+ $binder = $this->createBinder($document);
+ $binder->registerBindFilter(new class extends BindFilter {
+ public function filterNumericOutput(float $value):string {
+ return number_format($value, 2);
+ }
+ public function filterCurrency(string $value):string {
+ return "£" . $value;
+ }
+ });
+
+ $binder->bindKeyValue("amount", 12345);
+
+ self::assertSame("£12,345.00", $document->querySelector("#formatted")->textContent);
+ self::assertSame("12345", $document->querySelector("#raw")->textContent);
+ }
+
+ public function testRawObjectsAreFilteredBeforeStringConversion():void {
+ $document = new HTMLDocument('
');
+ $binder = $this->createBinder($document);
+ $binder->registerBindFilter(new class extends BindFilter {
+ public function filterDate(DateTimeInterface $value):string {
+ return $value->format("Y-m-d");
+ }
+ });
+ $binder->bindKeyValue("date", new DateTimeImmutable("2026-11-06"));
+ self::assertSame("2026-11-06", $document->querySelector("p")->textContent);
+ }
+
+ public function testBindGettersAndListObjectsPreserveInputTypes():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('
');
+ $binder = $this->createBinder($document);
+ $binder->registerBindFilter(new class extends BindFilter {
+ public function filterDate(DateTimeInterface $value):string {
+ return $value->format("Y-m-d");
+ }
+ public function filterType(mixed $value):string {
+ return get_debug_type($value);
+ }
+ });
+ $binder->bindData($value, "p");
+ $binder->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 testNullCanBeFilteredAndNullResultsRemainUnbound():void {
+ $document = new HTMLDocument('Original
'
+ . 'Original
'
+ . 'Original
');
+ $binder = $this->createBinder($document);
+ $binder->registerBindFilter(new class extends BindFilter {
+ public function filterFallback(mixed $value):string {
+ return $value ?? "Default";
+ }
+ public function filterIgnore(mixed $value):mixed {
+ return null;
+ }
+ });
+ $binder->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 testFiltersWorkWithModifiersEqualityReferencesAndRebinding():void {
+ $document = new HTMLDocument('
'
+ . ' ');
+ $binder = $this->createBinder($document);
+ $binder->registerBindFilter(new class extends BindFilter {
+ public function filterPositive(int $value):bool {
+ return $value > 0;
+ }
+ public function filterLower(string $value):string {
+ return strtolower($value);
+ }
+ });
+ $div = $document->querySelector("div");
+ $binder->bindKeyValue("amount", 5);
+ self::assertSame("active", $div->className);
+ $binder->bindKeyValue("hidden", 1);
+ self::assertTrue($div->classList->contains("active"));
+ self::assertTrue($div->classList->contains("hidden"));
+ $binder->bindKeyValue("amount", -1);
+ self::assertSame("hidden", $div->className);
+ $binder->bindKeyValue("status", "BLOCKED");
+ self::assertTrue($document->querySelector("button")->hasAttribute("disabled"));
+ $binder->bindKeyValue("status", "READY");
+ self::assertFalse($document->querySelector("button")->hasAttribute("disabled"));
+ }
+
+ public function testRemainingExpressionsKeepTheirFilters():void {
+ $document = new HTMLDocument('
');
+ $binder = $this->createBinder($document);
+ $binder->registerBindFilter(new class extends BindFilter {
+ public function filterPositive(int $value):bool {
+ return $value > 0;
+ }
+ });
+ $binder->bindKeyValue("one", 1);
+ self::assertSame(":two|positive second", $document->querySelector("div")->getAttribute("data-bind:class"));
+ $binder->bindKeyValue("two", 2);
+ self::assertSame("first second", $document->querySelector("div")->className);
+ self::assertFalse($document->querySelector("div")->hasAttribute("data-bind:class"));
+ }
+
+ public function testOneProviderAndItsDependenciesAreSharedWithComponentsAndLists():void {
+ $document = new HTMLDocument('
'
+ . '');
+ $page = $this->createBinder($document);
+ $component = new ComponentBinder($document);
+ $component->setDependencies(...$this->dependencies);
+ $component->setComponentBinderDependencies($document->querySelector("section"));
+ $filter = new class extends BindFilter {
+ public int $calls = 0;
+ public function filterLabel(string $value):string {
+ $this->calls++;
+ return ($this->getDependency(stdClass::class)?->prefix ?? "") . $value;
+ }
+ };
+ $page->registerBindFilter($filter);
+ $filter->setDependency((object)["prefix" => "Hello "]);
+ $page->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 testAnonymousBindingsAndPlainPlaceholders():void {
+ $document = new HTMLDocument('
{{}} ');
+ $binder = $this->createBinder($document);
+ $binder->registerBindFilter(new class extends BindFilter {
+ public function filterUpper(string $value):string {
+ return strtoupper($value);
+ }
+ });
+ $binder->bindValue("hello");
+ self::assertSame("HELLO", $document->querySelector("p")->textContent);
+ self::assertSame("hello", $document->querySelector("span")->textContent);
+ }
+
+ public function testUnmatchedExpressionsDoNotRequireRegistration():void {
+ $document = new HTMLDocument('Original
');
+ $binder = $this->createBinder($document);
+ $binder->bindKeyValue("name", "hello");
+ self::assertSame("Original", $document->querySelector("p")->textContent);
+ self::assertSame("hello", $document->querySelector("span")->textContent);
+ }
+
+ #[DataProvider("invalidExpressions")]
+ public function testInvalidFiltersExposeTheNameAndExpression(string $expression, string $exceptionClass, bool $registered):void {
+ $document = new HTMLDocument('Original
');
+ $binder = $this->createBinder($document);
+ if($registered) {
+ $binder->registerBindFilter(new class extends BindFilter {});
+ }
+ try {
+ $binder->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 testFilteredListsUseTheSharedProviderForRows():void {
+ $document = new HTMLDocument('');
+ $binder = $this->createBinder($document);
+ $binder->registerBindFilter(new class extends BindFilter {
+ public function filterReverse(array $value):array {
+ return array_reverse($value);
+ }
+ public function filterUpper(string $value):string {
+ return strtoupper($value);
+ }
+ });
+ $binder->bindKeyValue("items", [["name" => "one"], ["name" => "two"]]);
+ self::assertSame("TWO", $document->querySelectorAll("li")[0]->textContent);
+ self::assertSame("ONE", $document->querySelectorAll("li")[1]->textContent);
+ }
+
+ public function testFilteringDoesNotStringifyTheInputObject():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('
');
+ $binder = $this->createBinder($document);
+ $binder->registerBindFilter(new class extends BindFilter {
+ public function filterLabel(object $value):string {
+ return $value->label;
+ }
+ });
+ $binder->bindData((object)["value" => $value]);
+ self::assertSame("raw", $document->querySelector("p")->textContent);
+ }
+
+ public function testOrdinaryObjectValuesAreConvertedOnlyOnce():void {
+ $value = new class implements \Stringable {
+ public int $calls = 0;
+ public function __toString():string {
+ $this->calls++;
+ return "hello";
+ }
+ };
+ $document = new HTMLDocument('
{{value}} ');
+ $binder = $this->createBinder($document);
+ $binder->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 testListCallbacksKeepTheirOrdinaryObjectValues():void {
+ $document = new HTMLDocument('');
+ $binder = $this->createBinder($document);
+ $binder->registerBindFilter(new class extends BindFilter {
+ public function filterType(mixed $value):string {
+ return get_debug_type($value);
+ }
+ });
+ $binder->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 testUnregisteredDocumentDoesNotInheritAnotherProvider():void {
+ $firstDocument = new HTMLDocument('
');
+ $first = $this->createBinder($firstDocument);
+ $first->registerBindFilter(new class extends BindFilter {
+ public function filterUpper(string $value):string {
+ return strtoupper($value);
+ }
+ });
+ $first->bindKeyValue("name", "hello");
+ self::assertSame("HELLO", $firstDocument->querySelector("p")->textContent);
+ $second = $this->createBinder(new HTMLDocument('
'));
+ $this->expectException(BindFilterNotRegisteredException::class);
+ $second->bindKeyValue("name", "hello");
+ }
+
+ public function testFilterFailuresRetainTheOriginalException():void {
+ $document = new HTMLDocument('Original
');
+ $binder = $this->createBinder($document);
+ $failure = new RuntimeException("Filter failed");
+ $binder->registerBindFilter(new class($failure) extends BindFilter {
+ public function __construct(private RuntimeException $failure) {}
+ public function filterBroken(mixed $value):mixed {
+ throw $this->failure;
+ }
+ });
+ try {
+ $binder->bindKeyValue("name", "hello");
+ self::fail("Expected the original exception");
+ }
+ catch(RuntimeException $exception) {
+ self::assertSame($failure, $exception);
+ self::assertSame("Original", $document->querySelector("p")->textContent);
+ }
+ }
+
+ private array $dependencies;
+
+ private function createBinder(HTMLDocument $document, ?ElementBinder $elementBinder = null):DocumentBinder {
+ $elementBinder ??= new ElementBinder();
+ $attributes = new HTMLAttributeBinder();
+ $collection = new HTMLAttributeCollection();
+ $placeholders = new PlaceholderBinder();
+ $table = new TableBinder();
+ $list = new ListBinder();
+ $templates = new ListElementCollection($document);
+ $cache = new BindableCache();
+ $attributes->setDependencies($list, $table);
+ $elementBinder->setDependencies($attributes, $collection, $placeholders);
+ $table->setDependencies($list, $templates, $elementBinder, $attributes, $collection, $placeholders);
+ $list->setDependencies($elementBinder, $templates, $cache, $table);
+ $binder = new DocumentBinder($document);
+ $this->dependencies = [$elementBinder, $placeholders, $table, $list, $templates, $cache];
+ $binder->setDependencies(...$this->dependencies);
+ return $binder;
+ }
+}
diff --git a/test/phpunit/BindFilterTest.php b/test/phpunit/BindFilterTest.php
new file mode 100644
index 0000000..897ad50
--- /dev/null
+++ b/test/phpunit/BindFilterTest.php
@@ -0,0 +1,45 @@
+getDependency(Countable::class));
+ $first = new ArrayObject([1]);
+ $filter->setDependency($first);
+ self::assertSame($first, $filter->getDependency(Countable::class));
+ self::assertSame($first, $filter->getDependency(ArrayObject::class));
+ self::assertNull($filter->getDependency(stdClass::class));
+
+ $second = new ArrayObject([1, 2]);
+ $filter->setDependency($second);
+ self::assertSame($second, $filter->getDependency(Countable::class));
+ }
+
+ public function testOnlyPublicInstanceFilterMethodsAreExposed():void {
+ $filter = new class extends BindFilter {
+ public function filterUpper(string $value):string {
+ return strtoupper($value);
+ }
+ protected function filterHidden(string $value):string {
+ return $value;
+ }
+ public static function filterStatic(string $value):string {
+ return $value;
+ }
+ public function helper(string $value):string {
+ return $value;
+ }
+ };
+ self::assertSame("HELLO", $filter->getFilter("upper")("hello"));
+ foreach(["hidden", "static", "helper", "setDependency", "getDependency", "missing"] as $name) {
+ self::assertNull($filter->getFilter($name));
+ }
+ }
+}
From 9fe8593cfdf4b45f6e964f7731959eccd1e1e750 Mon Sep 17 00:00:00 2001
From: Greg Bowler
Date: Fri, 6 Nov 2026 12:30:46 +0000
Subject: [PATCH 2/7] feat: add explicitly registered bind value filters
---
src/BindFilter.php | 44 +++++++++++++++++
src/BindFilterException.php | 12 +++++
src/BindFilterNotFoundException.php | 12 +++++
src/BindFilterNotRegisteredException.php | 11 +++++
src/BindFilterPipeline.php | 52 ++++++++++++++++++++
src/BindableCache.php | 44 ++++++++++-------
src/BindableValue.php | 25 ++++++++++
src/Binder.php | 2 +
src/DocumentBinder.php | 6 ++-
src/ElementBinder.php | 13 +++--
src/HTMLAttributeBinder.php | 51 ++++++++++++++-----
src/InvalidBindFilterExpressionException.php | 12 +++++
src/ListBinder.php | 10 ++--
src/PlaceholderBinder.php | 5 +-
14 files changed, 260 insertions(+), 39 deletions(-)
create mode 100644 src/BindFilter.php
create mode 100644 src/BindFilterException.php
create mode 100644 src/BindFilterNotFoundException.php
create mode 100644 src/BindFilterNotRegisteredException.php
create mode 100644 src/BindFilterPipeline.php
create mode 100644 src/BindableValue.php
create mode 100644 src/InvalidBindFilterExpressionException.php
diff --git a/src/BindFilter.php b/src/BindFilter.php
new file mode 100644
index 0000000..d6f21be
--- /dev/null
+++ b/src/BindFilter.php
@@ -0,0 +1,44 @@
+ */
+ 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 {
+ $methodName = "filter" . ucfirst($name);
+ if(!method_exists($this, $methodName)) {
+ return null;
+ }
+
+ $method = new ReflectionMethod($this, $methodName);
+ 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 @@
+filter = $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->filter) {
+ throw new BindFilterNotRegisteredException($filterName, $expression);
+ }
+ $callback = $this->filter->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];
+ }
+}
diff --git a/src/BindableCache.php b/src/BindableCache.php
index 4570ab0..756dba8 100644
--- a/src/BindableCache.php
+++ b/src/BindableCache.php
@@ -119,8 +119,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, bool $preserveTypes = false):mixed
+ => $this->nullableStringOrIterable($object, $methodName, $preserveTypes);
$this->cacheNestedClassName(
$objectKeys,
$bindKey,
@@ -144,8 +144,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, bool $preserveTypes = false):mixed
+ => $this->nullableStringOrIterable($object, $propertyName, $preserveTypes);
$this->cacheNestedClassName(
$objectKeys,
$bindKey,
@@ -160,9 +160,9 @@ private function addPropertyBindings(
return;
}
- $attributeCache[$propertyName] = fn(object $object):null|iterable|string
+ $attributeCache[$propertyName] = fn(object $object, bool $preserveTypes = false):mixed
=> isset($object->$propertyName)
- ? $this->nullableStringOrIterable($object, $propertyName)
+ ? $this->nullableStringOrIterable($object, $propertyName, $preserveTypes)
: null;
$this->cacheNestedClassName(
$objectKeys,
@@ -249,39 +249,47 @@ private function appendNestedBindableKeys(
}
/**
- * @param object|array $object
- * @return array
+ * @param object|array $object
+ * @return array
+ * @param bool $preserveTypes Retain original values alongside ordinary object binding values.
*/
- public function convertToKvp(object|array $object):array {
+ public function convertToKvp(object|array $object, bool $preserveTypes = false):array {
if(is_array($object)) {
return $object;
}
if($object instanceof stdClass) {
- return $this->stringifyMap(get_object_vars($object));
+ $values = get_object_vars($object);
+ return $preserveTypes
+ ? array_map(fn(mixed $value):mixed => $this->preserveValue($value), $values)
+ : $this->stringifyMap($values);
}
if(!$this->isBindable($object)) {
return [];
}
- return $this->convertBindableObjectToKvp($object);
+ return $this->convertBindableObjectToKvp($object, $preserveTypes);
}
- /** @return array> */
- private function convertBindableObjectToKvp(object $object):array {
+ /** @return array */
+ private function convertBindableObjectToKvp(object $object, bool $preserveTypes):array {
$kvp = [];
foreach($this->bindableClassMap[$object::class] as $key => $valueGetter) {
$targetObject = $this->resolveTargetObject($object, $key);
$value = $targetObject
- ? $valueGetter($targetObject)
+ ? $valueGetter($targetObject, $preserveTypes)
: null;
- $kvp[$key] = $this->normalizeValue($value);
+ $kvp[$key] = $preserveTypes ? $this->preserveValue($value) : $this->normalizeValue($value);
}
return $kvp;
}
+ private function preserveValue(mixed $value):mixed {
+ return is_iterable($value) ? $value : new BindableValue($value);
+ }
+
private function resolveTargetObject(object $object, string $key):?object {
$targetObject = $object;
$segments = explode(".", $key);
@@ -392,11 +400,11 @@ private function isAttribute(
return strcasecmp($reflectionAttribute->getName(), $className) === 0;
}
- /** @return null|string|array */
private function nullableStringOrIterable(
object $object,
string $keyOrMethod,
- ):null|iterable|string {
+ bool $preserveTypes = false,
+ ):mixed {
if(method_exists($object, $keyOrMethod)) {
$value = $object->$keyOrMethod();
}
@@ -407,7 +415,7 @@ private function nullableStringOrIterable(
return null;
}
- if(is_scalar($value)) {
+ if($preserveTypes || is_scalar($value)) {
return $value;
}
elseif(is_iterable($value)) {
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..4d341b3 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->convertToKvp($kvp, preserveTypes: true);
}
}
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->convertToKvp($listValue, preserveTypes: true) 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->convertToKvp($listValue, preserveTypes: true);
}
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(
From a46be7819f215914448a62e3727215432c2d3dd2 Mon Sep 17 00:00:00 2001
From: Greg Bowler
Date: Fri, 6 Nov 2026 12:36:33 +0000
Subject: [PATCH 3/7] feat: support multiple bind filter providers with ordered
overrides
---
src/BindFilterNotFoundException.php | 2 +-
src/BindFilterPipeline.php | 22 +++++++++---
test/phpunit/BindFilterBindingTest.php | 49 ++++++++++++++++++++++++++
3 files changed, 68 insertions(+), 5 deletions(-)
diff --git a/src/BindFilterNotFoundException.php b/src/BindFilterNotFoundException.php
index 3d5fdf3..6779782 100644
--- a/src/BindFilterNotFoundException.php
+++ b/src/BindFilterNotFoundException.php
@@ -6,7 +6,7 @@ public function __construct(string $filterName, string $expression) {
$methodName = "filter" . ucfirst($filterName);
parent::__construct($filterName, $expression,
"Bind filter \"$filterName\" could not be found for expression \"$expression\". "
- . "Define a public instance method named $methodName on the registered BindFilter.",
+ . "Define a public instance method named $methodName on a registered BindFilter class.",
);
}
}
diff --git a/src/BindFilterPipeline.php b/src/BindFilterPipeline.php
index 1250f04..8449397 100644
--- a/src/BindFilterPipeline.php
+++ b/src/BindFilterPipeline.php
@@ -1,11 +1,15 @@
, BindFilter> */
+ private array $filters = [];
public function register(BindFilter $filter):void {
- $this->filter = $filter;
+ unset($this->filters[$filter::class]);
+ $this->filters[$filter::class] = $filter;
}
/** @return array{0:string, 1:mixed} */
@@ -25,10 +29,10 @@ public function apply(string $expression, mixed $value):array {
if(!preg_match('/^[a-z][a-z0-9_]*$/iD', $filterName)) {
throw new InvalidBindFilterExpressionException($filterName, $expression);
}
- if(!$this->filter) {
+ if(!$this->filters) {
throw new BindFilterNotRegisteredException($filterName, $expression);
}
- $callback = $this->filter->getFilter($filterName);
+ $callback = $this->getFilter($filterName);
if(!$callback) {
throw new BindFilterNotFoundException($filterName, $expression);
}
@@ -49,4 +53,14 @@ public function apply(string $expression, mixed $value):array {
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/test/phpunit/BindFilterBindingTest.php b/test/phpunit/BindFilterBindingTest.php
index f0e5217..19a5df0 100644
--- a/test/phpunit/BindFilterBindingTest.php
+++ b/test/phpunit/BindFilterBindingTest.php
@@ -45,6 +45,55 @@ public function filterCurrency(string $value):string {
self::assertSame("12345", $document->querySelector("#raw")->textContent);
}
+ public function testMultipleProvidersChainWithLaterOverridesAndEarlierFallbacks():void {
+ $document = new HTMLDocument('
'
+ . ' ');
+ $binder = $this->createBinder($document);
+ $binder->registerBindFilter(new class extends BindFilter {
+ public function filterNumber(int $value):string {
+ return number_format($value, 2);
+ }
+ public function filterCurrency(string $value):string {
+ return "£" . $value;
+ }
+ });
+ $application = new class extends BindFilter {
+ public function filterCurrency(string $value):string {
+ return ($this->getDependency(stdClass::class)?->symbol ?? "€") . $value;
+ }
+ };
+ $application->setDependency((object)["symbol" => "$"]);
+ $binder->registerBindFilter($application);
+ $binder->bindKeyValue("amount", 12345);
+
+ self::assertSame("$12,345.00", $document->querySelector("p")->textContent);
+ self::assertSame("12,345.00", $document->querySelector("b")->textContent);
+ }
+
+ public function testRegisteringTheSameClassReplacesItAndUpdatesPrecedence():void {
+ $document = new HTMLDocument('
');
+ $binder = $this->createBinder($document);
+ $first = new class extends BindFilter {
+ public string $prefix = "first ";
+ public function filterLabel(string $value):string {
+ return $this->prefix . $value;
+ }
+ };
+ $binder->registerBindFilter($first);
+ $binder->registerBindFilter(new class extends BindFilter {
+ public function filterLabel(string $value):string {
+ return "second " . $value;
+ }
+ });
+ $binder->bindKeyValue("name", "hello");
+ self::assertSame("second hello", $document->querySelector("p")->textContent);
+ $replacement = clone $first;
+ $replacement->prefix = "replacement ";
+ $binder->registerBindFilter($replacement);
+ $binder->bindKeyValue("name", "hello");
+ self::assertSame("replacement hello", $document->querySelector("p")->textContent);
+ }
+
public function testRawObjectsAreFilteredBeforeStringConversion():void {
$document = new HTMLDocument('
');
$binder = $this->createBinder($document);
From f679dad4545e0e95585306d2299325e52df3482a Mon Sep 17 00:00:00 2001
From: Greg Bowler
Date: Sat, 7 Nov 2026 14:29:04 +0000
Subject: [PATCH 4/7] code quality: clarify binding conversion and consolidate
filter tests
---
src/BindableCache.php | 82 +++--
src/DocumentBinder.php | 2 +-
src/ListBinder.php | 4 +-
test/phpunit/BindFilterBindingTest.php | 400 -------------------------
test/phpunit/BindFilterTest.php | 26 +-
test/phpunit/BindableCacheTest.php | 4 +-
test/phpunit/DocumentBinderTest.php | 366 ++++++++++++++++++++++
7 files changed, 420 insertions(+), 464 deletions(-)
delete mode 100644 test/phpunit/BindFilterBindingTest.php
diff --git a/src/BindableCache.php b/src/BindableCache.php
index 756dba8..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, bool $preserveTypes = false):mixed
- => $this->nullableStringOrIterable($object, $methodName, $preserveTypes);
+ $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, bool $preserveTypes = false):mixed
- => $this->nullableStringOrIterable($object, $propertyName, $preserveTypes);
+ $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, bool $preserveTypes = false):mixed
+ $attributeCache[$propertyName] = fn(object $object):mixed
=> isset($object->$propertyName)
- ? $this->nullableStringOrIterable($object, $propertyName, $preserveTypes)
+ ? $this->readBindableValue($object, $propertyName)
: null;
$this->cacheNestedClassName(
$objectKeys,
@@ -251,39 +250,48 @@ private function appendNestedBindableKeys(
/**
* @param object|array $object
* @return array
- * @param bool $preserveTypes Retain original values alongside ordinary object binding values.
*/
- public function convertToKvp(object|array $object, bool $preserveTypes = false):array {
+ public function convertToKvp(object|array $object):array {
if(is_array($object)) {
return $object;
}
if($object instanceof stdClass) {
- $values = get_object_vars($object);
- return $preserveTypes
- ? array_map(fn(mixed $value):mixed => $this->preserveValue($value), $values)
- : $this->stringifyMap($values);
+ 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, $preserveTypes);
- }
-
- /** @return array */
- private function convertBindableObjectToKvp(object $object, bool $preserveTypes):array {
- $kvp = [];
+ $values = [];
foreach($this->bindableClassMap[$object::class] as $key => $valueGetter) {
$targetObject = $this->resolveTargetObject($object, $key);
- $value = $targetObject
- ? $valueGetter($targetObject, $preserveTypes)
- : null;
- $kvp[$key] = $preserveTypes ? $this->preserveValue($value) : $this->normalizeValue($value);
+ $value = $targetObject ? $valueGetter($targetObject) : null;
+ $values[$key] = $this->preserveValue($value);
}
- return $kvp;
+ return $values;
}
private function preserveValue(mixed $value):mixed {
@@ -400,31 +408,13 @@ private function isAttribute(
return strcasecmp($reflectionAttribute->getName(), $className) === 0;
}
- private function nullableStringOrIterable(
- object $object,
- string $keyOrMethod,
- bool $preserveTypes = false,
- ):mixed {
+ 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($preserveTypes || 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/DocumentBinder.php b/src/DocumentBinder.php
index 4d341b3..4f5be2a 100644
--- a/src/DocumentBinder.php
+++ b/src/DocumentBinder.php
@@ -105,7 +105,7 @@ public function bindData(
if(is_object($kvp)) {
if($this->bindableCache->isBindable($kvp)) {
$object = $kvp;
- $kvp = $this->bindableCache->convertToKvp($kvp, preserveTypes: true);
+ $kvp = $this->bindableCache->convertToBindableValues($kvp);
}
}
diff --git a/src/ListBinder.php b/src/ListBinder.php
index 0948fec..bccf65a 100644
--- a/src/ListBinder.php
+++ b/src/ListBinder.php
@@ -145,7 +145,7 @@ private function bindNestedListItem(
):int {
$this->elementBinder->bind(null, $listKey, $template);
$this->bindListData($listValue, $template);
- foreach($this->bindableCache->convertToKvp($listValue, preserveTypes: true) as $key => $value) {
+ foreach($this->bindableCache->convertToBindableValues($listValue) as $key => $value) {
$this->elementBinder->bind($key, $value, $template);
}
@@ -158,7 +158,7 @@ private function normalizeListValue(mixed $listValue):mixed {
}
if(is_object($listValue) && $this->bindableCache->isBindable($listValue)) {
- return $this->bindableCache->convertToKvp($listValue, preserveTypes: true);
+ return $this->bindableCache->convertToBindableValues($listValue);
}
return $listValue;
diff --git a/test/phpunit/BindFilterBindingTest.php b/test/phpunit/BindFilterBindingTest.php
deleted file mode 100644
index 19a5df0..0000000
--- a/test/phpunit/BindFilterBindingTest.php
+++ /dev/null
@@ -1,400 +0,0 @@
-'
- . '
');
- $binder = $this->createBinder($document);
- $binder->registerBindFilter(new class extends BindFilter {
- public function filterNumericOutput(float $value):string {
- return number_format($value, 2);
- }
- public function filterCurrency(string $value):string {
- return "£" . $value;
- }
- });
-
- $binder->bindKeyValue("amount", 12345);
-
- self::assertSame("£12,345.00", $document->querySelector("#formatted")->textContent);
- self::assertSame("12345", $document->querySelector("#raw")->textContent);
- }
-
- public function testMultipleProvidersChainWithLaterOverridesAndEarlierFallbacks():void {
- $document = new HTMLDocument('
'
- . ' ');
- $binder = $this->createBinder($document);
- $binder->registerBindFilter(new class extends BindFilter {
- public function filterNumber(int $value):string {
- return number_format($value, 2);
- }
- public function filterCurrency(string $value):string {
- return "£" . $value;
- }
- });
- $application = new class extends BindFilter {
- public function filterCurrency(string $value):string {
- return ($this->getDependency(stdClass::class)?->symbol ?? "€") . $value;
- }
- };
- $application->setDependency((object)["symbol" => "$"]);
- $binder->registerBindFilter($application);
- $binder->bindKeyValue("amount", 12345);
-
- self::assertSame("$12,345.00", $document->querySelector("p")->textContent);
- self::assertSame("12,345.00", $document->querySelector("b")->textContent);
- }
-
- public function testRegisteringTheSameClassReplacesItAndUpdatesPrecedence():void {
- $document = new HTMLDocument('
');
- $binder = $this->createBinder($document);
- $first = new class extends BindFilter {
- public string $prefix = "first ";
- public function filterLabel(string $value):string {
- return $this->prefix . $value;
- }
- };
- $binder->registerBindFilter($first);
- $binder->registerBindFilter(new class extends BindFilter {
- public function filterLabel(string $value):string {
- return "second " . $value;
- }
- });
- $binder->bindKeyValue("name", "hello");
- self::assertSame("second hello", $document->querySelector("p")->textContent);
- $replacement = clone $first;
- $replacement->prefix = "replacement ";
- $binder->registerBindFilter($replacement);
- $binder->bindKeyValue("name", "hello");
- self::assertSame("replacement hello", $document->querySelector("p")->textContent);
- }
-
- public function testRawObjectsAreFilteredBeforeStringConversion():void {
- $document = new HTMLDocument('
');
- $binder = $this->createBinder($document);
- $binder->registerBindFilter(new class extends BindFilter {
- public function filterDate(DateTimeInterface $value):string {
- return $value->format("Y-m-d");
- }
- });
- $binder->bindKeyValue("date", new DateTimeImmutable("2026-11-06"));
- self::assertSame("2026-11-06", $document->querySelector("p")->textContent);
- }
-
- public function testBindGettersAndListObjectsPreserveInputTypes():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('
');
- $binder = $this->createBinder($document);
- $binder->registerBindFilter(new class extends BindFilter {
- public function filterDate(DateTimeInterface $value):string {
- return $value->format("Y-m-d");
- }
- public function filterType(mixed $value):string {
- return get_debug_type($value);
- }
- });
- $binder->bindData($value, "p");
- $binder->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 testNullCanBeFilteredAndNullResultsRemainUnbound():void {
- $document = new HTMLDocument('Original
'
- . 'Original
'
- . 'Original
');
- $binder = $this->createBinder($document);
- $binder->registerBindFilter(new class extends BindFilter {
- public function filterFallback(mixed $value):string {
- return $value ?? "Default";
- }
- public function filterIgnore(mixed $value):mixed {
- return null;
- }
- });
- $binder->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 testFiltersWorkWithModifiersEqualityReferencesAndRebinding():void {
- $document = new HTMLDocument('
'
- . ' ');
- $binder = $this->createBinder($document);
- $binder->registerBindFilter(new class extends BindFilter {
- public function filterPositive(int $value):bool {
- return $value > 0;
- }
- public function filterLower(string $value):string {
- return strtolower($value);
- }
- });
- $div = $document->querySelector("div");
- $binder->bindKeyValue("amount", 5);
- self::assertSame("active", $div->className);
- $binder->bindKeyValue("hidden", 1);
- self::assertTrue($div->classList->contains("active"));
- self::assertTrue($div->classList->contains("hidden"));
- $binder->bindKeyValue("amount", -1);
- self::assertSame("hidden", $div->className);
- $binder->bindKeyValue("status", "BLOCKED");
- self::assertTrue($document->querySelector("button")->hasAttribute("disabled"));
- $binder->bindKeyValue("status", "READY");
- self::assertFalse($document->querySelector("button")->hasAttribute("disabled"));
- }
-
- public function testRemainingExpressionsKeepTheirFilters():void {
- $document = new HTMLDocument('
');
- $binder = $this->createBinder($document);
- $binder->registerBindFilter(new class extends BindFilter {
- public function filterPositive(int $value):bool {
- return $value > 0;
- }
- });
- $binder->bindKeyValue("one", 1);
- self::assertSame(":two|positive second", $document->querySelector("div")->getAttribute("data-bind:class"));
- $binder->bindKeyValue("two", 2);
- self::assertSame("first second", $document->querySelector("div")->className);
- self::assertFalse($document->querySelector("div")->hasAttribute("data-bind:class"));
- }
-
- public function testOneProviderAndItsDependenciesAreSharedWithComponentsAndLists():void {
- $document = new HTMLDocument('
'
- . '');
- $page = $this->createBinder($document);
- $component = new ComponentBinder($document);
- $component->setDependencies(...$this->dependencies);
- $component->setComponentBinderDependencies($document->querySelector("section"));
- $filter = new class extends BindFilter {
- public int $calls = 0;
- public function filterLabel(string $value):string {
- $this->calls++;
- return ($this->getDependency(stdClass::class)?->prefix ?? "") . $value;
- }
- };
- $page->registerBindFilter($filter);
- $filter->setDependency((object)["prefix" => "Hello "]);
- $page->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 testAnonymousBindingsAndPlainPlaceholders():void {
- $document = new HTMLDocument('
{{}} ');
- $binder = $this->createBinder($document);
- $binder->registerBindFilter(new class extends BindFilter {
- public function filterUpper(string $value):string {
- return strtoupper($value);
- }
- });
- $binder->bindValue("hello");
- self::assertSame("HELLO", $document->querySelector("p")->textContent);
- self::assertSame("hello", $document->querySelector("span")->textContent);
- }
-
- public function testUnmatchedExpressionsDoNotRequireRegistration():void {
- $document = new HTMLDocument('Original
');
- $binder = $this->createBinder($document);
- $binder->bindKeyValue("name", "hello");
- self::assertSame("Original", $document->querySelector("p")->textContent);
- self::assertSame("hello", $document->querySelector("span")->textContent);
- }
-
- #[DataProvider("invalidExpressions")]
- public function testInvalidFiltersExposeTheNameAndExpression(string $expression, string $exceptionClass, bool $registered):void {
- $document = new HTMLDocument('Original
');
- $binder = $this->createBinder($document);
- if($registered) {
- $binder->registerBindFilter(new class extends BindFilter {});
- }
- try {
- $binder->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 testFilteredListsUseTheSharedProviderForRows():void {
- $document = new HTMLDocument('');
- $binder = $this->createBinder($document);
- $binder->registerBindFilter(new class extends BindFilter {
- public function filterReverse(array $value):array {
- return array_reverse($value);
- }
- public function filterUpper(string $value):string {
- return strtoupper($value);
- }
- });
- $binder->bindKeyValue("items", [["name" => "one"], ["name" => "two"]]);
- self::assertSame("TWO", $document->querySelectorAll("li")[0]->textContent);
- self::assertSame("ONE", $document->querySelectorAll("li")[1]->textContent);
- }
-
- public function testFilteringDoesNotStringifyTheInputObject():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('
');
- $binder = $this->createBinder($document);
- $binder->registerBindFilter(new class extends BindFilter {
- public function filterLabel(object $value):string {
- return $value->label;
- }
- });
- $binder->bindData((object)["value" => $value]);
- self::assertSame("raw", $document->querySelector("p")->textContent);
- }
-
- public function testOrdinaryObjectValuesAreConvertedOnlyOnce():void {
- $value = new class implements \Stringable {
- public int $calls = 0;
- public function __toString():string {
- $this->calls++;
- return "hello";
- }
- };
- $document = new HTMLDocument('
{{value}} ');
- $binder = $this->createBinder($document);
- $binder->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 testListCallbacksKeepTheirOrdinaryObjectValues():void {
- $document = new HTMLDocument('');
- $binder = $this->createBinder($document);
- $binder->registerBindFilter(new class extends BindFilter {
- public function filterType(mixed $value):string {
- return get_debug_type($value);
- }
- });
- $binder->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 testUnregisteredDocumentDoesNotInheritAnotherProvider():void {
- $firstDocument = new HTMLDocument('
');
- $first = $this->createBinder($firstDocument);
- $first->registerBindFilter(new class extends BindFilter {
- public function filterUpper(string $value):string {
- return strtoupper($value);
- }
- });
- $first->bindKeyValue("name", "hello");
- self::assertSame("HELLO", $firstDocument->querySelector("p")->textContent);
- $second = $this->createBinder(new HTMLDocument('
'));
- $this->expectException(BindFilterNotRegisteredException::class);
- $second->bindKeyValue("name", "hello");
- }
-
- public function testFilterFailuresRetainTheOriginalException():void {
- $document = new HTMLDocument('Original
');
- $binder = $this->createBinder($document);
- $failure = new RuntimeException("Filter failed");
- $binder->registerBindFilter(new class($failure) extends BindFilter {
- public function __construct(private RuntimeException $failure) {}
- public function filterBroken(mixed $value):mixed {
- throw $this->failure;
- }
- });
- try {
- $binder->bindKeyValue("name", "hello");
- self::fail("Expected the original exception");
- }
- catch(RuntimeException $exception) {
- self::assertSame($failure, $exception);
- self::assertSame("Original", $document->querySelector("p")->textContent);
- }
- }
-
- private array $dependencies;
-
- private function createBinder(HTMLDocument $document, ?ElementBinder $elementBinder = null):DocumentBinder {
- $elementBinder ??= new ElementBinder();
- $attributes = new HTMLAttributeBinder();
- $collection = new HTMLAttributeCollection();
- $placeholders = new PlaceholderBinder();
- $table = new TableBinder();
- $list = new ListBinder();
- $templates = new ListElementCollection($document);
- $cache = new BindableCache();
- $attributes->setDependencies($list, $table);
- $elementBinder->setDependencies($attributes, $collection, $placeholders);
- $table->setDependencies($list, $templates, $elementBinder, $attributes, $collection, $placeholders);
- $list->setDependencies($elementBinder, $templates, $cache, $table);
- $binder = new DocumentBinder($document);
- $this->dependencies = [$elementBinder, $placeholders, $table, $list, $templates, $cache];
- $binder->setDependencies(...$this->dependencies);
- return $binder;
- }
-}
diff --git a/test/phpunit/BindFilterTest.php b/test/phpunit/BindFilterTest.php
index 897ad50..f515eb3 100644
--- a/test/phpunit/BindFilterTest.php
+++ b/test/phpunit/BindFilterTest.php
@@ -8,22 +8,22 @@
use stdClass;
class BindFilterTest extends TestCase {
- public function testDependenciesAreOptionalAndMatchInterfaces():void {
- $filter = new class extends BindFilter {};
- self::assertNull($filter->getDependency(Countable::class));
+ public function testGetDependency_optionalAndMatchesInterfaces():void {
+ $sut = new class extends BindFilter {};
+ self::assertNull($sut->getDependency(Countable::class));
$first = new ArrayObject([1]);
- $filter->setDependency($first);
- self::assertSame($first, $filter->getDependency(Countable::class));
- self::assertSame($first, $filter->getDependency(ArrayObject::class));
- self::assertNull($filter->getDependency(stdClass::class));
+ $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]);
- $filter->setDependency($second);
- self::assertSame($second, $filter->getDependency(Countable::class));
+ $sut->setDependency($second);
+ self::assertSame($second, $sut->getDependency(Countable::class));
}
- public function testOnlyPublicInstanceFilterMethodsAreExposed():void {
- $filter = new class extends BindFilter {
+ public function testGetFilter_exposesPublicInstanceMethods():void {
+ $sut = new class extends BindFilter {
public function filterUpper(string $value):string {
return strtoupper($value);
}
@@ -37,9 +37,9 @@ public function helper(string $value):string {
return $value;
}
};
- self::assertSame("HELLO", $filter->getFilter("upper")("hello"));
+ self::assertSame("HELLO", $sut->getFilter("upper")("hello"));
foreach(["hidden", "static", "helper", "setDependency", "getDependency", "missing"] as $name) {
- self::assertNull($filter->getFilter($name));
+ self::assertNull($sut->getFilter($name));
}
}
}
diff --git a/test/phpunit/BindableCacheTest.php b/test/phpunit/BindableCacheTest.php
index 95c5bee..a13a4e0 100644
--- a/test/phpunit/BindableCacheTest.php
+++ b/test/phpunit/BindableCacheTest.php
@@ -266,12 +266,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..2c33920 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,363 @@ 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 filterNumericOutput(float $value):string {
+ return number_format($value, 2);
+ }
+ public function filterCurrency(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 filterNumber(int $value):string {
+ return number_format($value, 2);
+ }
+ public function filterCurrency(string $value):string {
+ return "£" . $value;
+ }
+ });
+ $application = new class extends BindFilter {
+ public function filterCurrency(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 filterLabel(string $value):string {
+ return $this->prefix . $value;
+ }
+ };
+ $sut->registerBindFilter($first);
+ $sut->registerBindFilter(new class extends BindFilter {
+ public function filterLabel(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 filterDate(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 filterDate(DateTimeInterface $value):string {
+ return $value->format("Y-m-d");
+ }
+ public function filterType(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 filterFallback(mixed $value):string {
+ return $value ?? "Default";
+ }
+ public function filterIgnore(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 filterPositive(int $value):bool {
+ return $value > 0;
+ }
+ public function filterLower(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 filterPositive(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 filterLabel(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 filterUpper(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 filterReverse(array $value):array {
+ return array_reverse($value);
+ }
+ public function filterUpper(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 filterLabel(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('');
+ $sut = $this->createFilterBinder($document);
+ $sut->registerBindFilter(new class extends BindFilter {
+ public function filterType(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 filterUpper(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 filterBroken(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);
+ }
+ }
+
+ 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();
From f3ce686c0f2abaf8d7828f758ea30eac74cabc95 Mon Sep 17 00:00:00 2001
From: Greg Bowler
Date: Sat, 7 Nov 2026 15:23:21 +0000
Subject: [PATCH 5/7] test: cover real filter usage and conversion
compatibility
---
test/phpunit/BindableCacheTest.php | 35 ++++++++++++
test/phpunit/DocumentBinderTest.php | 87 +++++++++++++++++++++++++++++
2 files changed, 122 insertions(+)
diff --git a/test/phpunit/BindableCacheTest.php b/test/phpunit/BindableCacheTest.php
index a13a4e0..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]
diff --git a/test/phpunit/DocumentBinderTest.php b/test/phpunit/DocumentBinderTest.php
index 2c33920..ac2403f 100644
--- a/test/phpunit/DocumentBinderTest.php
+++ b/test/phpunit/DocumentBinderTest.php
@@ -2607,6 +2607,93 @@ public function filterBroken(mixed $value):mixed {
}
}
+ #[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 filterUpper(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 filterUpper(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('Customer '
+ . 'Total '
+ . ' '
+ . '
');
+ $sut = $this->createFilterBinder($document);
+ $sut->registerBindFilter(new class extends BindFilter {
+ public function filterUpper(string $value):string {
+ return strtoupper($value);
+ }
+ public function filterDecimal(float $value):string {
+ return number_format($value, 2);
+ }
+ });
+ $applicationFilters = new class extends BindFilter {
+ public function filterCurrency(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));
From 878cdcc1b63d4a1ee36a54f58c655bf279307b03 Mon Sep 17 00:00:00 2001
From: Greg Bowler
Date: Sat, 7 Nov 2026 15:23:21 +0000
Subject: [PATCH 6/7] fix: reuse the final table template cell when binding
rows
---
src/TableBinder.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
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];
}
From 630a4f65fa144dcd2c393891e6244263654f3d01 Mon Sep 17 00:00:00 2001
From: Greg Bowler
Date: Sat, 7 Nov 2026 15:25:41 +0000
Subject: [PATCH 7/7] Use filter method names directly in binding expressions
---
src/BindFilter.php | 5 ++-
src/BindFilterNotFoundException.php | 3 +-
test/phpunit/BindFilterTest.php | 9 ++---
test/phpunit/DocumentBinderTest.php | 56 ++++++++++++++---------------
4 files changed, 36 insertions(+), 37 deletions(-)
diff --git a/src/BindFilter.php b/src/BindFilter.php
index d6f21be..31dbd16 100644
--- a/src/BindFilter.php
+++ b/src/BindFilter.php
@@ -29,12 +29,11 @@ public function getDependency(string $class):?object {
}
public function getFilter(string $name):?Closure {
- $methodName = "filter" . ucfirst($name);
- if(!method_exists($this, $methodName)) {
+ if(method_exists(self::class, $name) || !method_exists($this, $name)) {
return null;
}
- $method = new ReflectionMethod($this, $methodName);
+ $method = new ReflectionMethod($this, $name);
if(!$method->isPublic() || $method->isStatic()) {
return null;
}
diff --git a/src/BindFilterNotFoundException.php b/src/BindFilterNotFoundException.php
index 6779782..f04e000 100644
--- a/src/BindFilterNotFoundException.php
+++ b/src/BindFilterNotFoundException.php
@@ -3,10 +3,9 @@
class BindFilterNotFoundException extends BindFilterException {
public function __construct(string $filterName, string $expression) {
- $methodName = "filter" . ucfirst($filterName);
parent::__construct($filterName, $expression,
"Bind filter \"$filterName\" could not be found for expression \"$expression\". "
- . "Define a public instance method named $methodName on a registered BindFilter class.",
+ . "Define a public instance method named $filterName on a registered BindFilter class.",
);
}
}
diff --git a/test/phpunit/BindFilterTest.php b/test/phpunit/BindFilterTest.php
index f515eb3..17b52e7 100644
--- a/test/phpunit/BindFilterTest.php
+++ b/test/phpunit/BindFilterTest.php
@@ -24,13 +24,13 @@ public function testGetDependency_optionalAndMatchesInterfaces():void {
public function testGetFilter_exposesPublicInstanceMethods():void {
$sut = new class extends BindFilter {
- public function filterUpper(string $value):string {
+ public function upper(string $value):string {
return strtoupper($value);
}
- protected function filterHidden(string $value):string {
+ protected function hidden(string $value):string {
return $value;
}
- public static function filterStatic(string $value):string {
+ public static function static(string $value):string {
return $value;
}
public function helper(string $value):string {
@@ -38,7 +38,8 @@ public function helper(string $value):string {
}
};
self::assertSame("HELLO", $sut->getFilter("upper")("hello"));
- foreach(["hidden", "static", "helper", "setDependency", "getDependency", "missing"] as $name) {
+ 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/DocumentBinderTest.php b/test/phpunit/DocumentBinderTest.php
index ac2403f..d9619bc 100644
--- a/test/phpunit/DocumentBinderTest.php
+++ b/test/phpunit/DocumentBinderTest.php
@@ -2261,10 +2261,10 @@ public function testBindKeyValue_chainsFiltersWithoutChangingOtherBindings():voi
. '
');
$sut = $this->createFilterBinder($document);
$sut->registerBindFilter(new class extends BindFilter {
- public function filterNumericOutput(float $value):string {
+ public function numericOutput(float $value):string {
return number_format($value, 2);
}
- public function filterCurrency(string $value):string {
+ public function currency(string $value):string {
return "£" . $value;
}
});
@@ -2280,15 +2280,15 @@ public function testRegisterBindFilter_laterOverridesAndEarlierFallbacks():void
. ' ');
$sut = $this->createFilterBinder($document);
$sut->registerBindFilter(new class extends BindFilter {
- public function filterNumber(int $value):string {
+ public function number(int $value):string {
return number_format($value, 2);
}
- public function filterCurrency(string $value):string {
+ public function currency(string $value):string {
return "£" . $value;
}
});
$application = new class extends BindFilter {
- public function filterCurrency(string $value):string {
+ public function currency(string $value):string {
return ($this->getDependency(stdClass::class)?->symbol ?? "€") . $value;
}
};
@@ -2305,13 +2305,13 @@ public function testRegisterBindFilter_replacesSameClassAndUpdatesPrecedence():v
$sut = $this->createFilterBinder($document);
$first = new class extends BindFilter {
public string $prefix = "first ";
- public function filterLabel(string $value):string {
+ public function label(string $value):string {
return $this->prefix . $value;
}
};
$sut->registerBindFilter($first);
$sut->registerBindFilter(new class extends BindFilter {
- public function filterLabel(string $value):string {
+ public function label(string $value):string {
return "second " . $value;
}
});
@@ -2328,7 +2328,7 @@ public function testBindKeyValue_filtersRawObjectsBeforeConversion():void {
$document = new HTMLDocument('
');
$sut = $this->createFilterBinder($document);
$sut->registerBindFilter(new class extends BindFilter {
- public function filterDate(DateTimeInterface $value):string {
+ public function date(DateTimeInterface $value):string {
return $value->format("Y-m-d");
}
});
@@ -2351,10 +2351,10 @@ public function getAmount():int {
. ' ');
$sut = $this->createFilterBinder($document);
$sut->registerBindFilter(new class extends BindFilter {
- public function filterDate(DateTimeInterface $value):string {
+ public function date(DateTimeInterface $value):string {
return $value->format("Y-m-d");
}
- public function filterType(mixed $value):string {
+ public function type(mixed $value):string {
return get_debug_type($value);
}
});
@@ -2371,10 +2371,10 @@ public function testBindKeyValue_filtersNullAndSkipsNullResults():void {
. 'Original
');
$sut = $this->createFilterBinder($document);
$sut->registerBindFilter(new class extends BindFilter {
- public function filterFallback(mixed $value):string {
+ public function fallback(mixed $value):string {
return $value ?? "Default";
}
- public function filterIgnore(mixed $value):mixed {
+ public function ignore(mixed $value):mixed {
return null;
}
});
@@ -2391,10 +2391,10 @@ public function testBindKeyValue_filtersWithModifiersAndRebinding():void {
. ' ');
$sut = $this->createFilterBinder($document);
$sut->registerBindFilter(new class extends BindFilter {
- public function filterPositive(int $value):bool {
+ public function positive(int $value):bool {
return $value > 0;
}
- public function filterLower(string $value):string {
+ public function lower(string $value):string {
return strtolower($value);
}
});
@@ -2416,7 +2416,7 @@ public function testBindKeyValue_keepsRemainingFilterExpressions():void {
$document = new HTMLDocument('
');
$sut = $this->createFilterBinder($document);
$sut->registerBindFilter(new class extends BindFilter {
- public function filterPositive(int $value):bool {
+ public function positive(int $value):bool {
return $value > 0;
}
});
@@ -2438,7 +2438,7 @@ public function testRegisterBindFilter_sharesProviderWithComponentsAndLists():vo
$component->setComponentBinderDependencies($document->querySelector("section"));
$filter = new class extends BindFilter {
public int $calls = 0;
- public function filterLabel(string $value):string {
+ public function label(string $value):string {
$this->calls++;
return ($this->getDependency(stdClass::class)?->prefix ?? "") . $value;
}
@@ -2459,7 +2459,7 @@ public function testBindValue_filtersAnonymousBindings():void {
$document = new HTMLDocument('
{{}} ');
$sut = $this->createFilterBinder($document);
$sut->registerBindFilter(new class extends BindFilter {
- public function filterUpper(string $value):string {
+ public function upper(string $value):string {
return strtoupper($value);
}
});
@@ -2511,10 +2511,10 @@ public function testBindKeyValue_filtersListsAndTheirRows():void {
. ' ');
$sut = $this->createFilterBinder($document);
$sut->registerBindFilter(new class extends BindFilter {
- public function filterReverse(array $value):array {
+ public function reverse(array $value):array {
return array_reverse($value);
}
- public function filterUpper(string $value):string {
+ public function upper(string $value):string {
return strtoupper($value);
}
});
@@ -2533,7 +2533,7 @@ public function __toString():string {
$document = new HTMLDocument('
');
$sut = $this->createFilterBinder($document);
$sut->registerBindFilter(new class extends BindFilter {
- public function filterLabel(object $value):string {
+ public function label(object $value):string {
return $value->label;
}
});
@@ -2563,7 +2563,7 @@ public function testBindListCallback_keepsOrdinaryValues():void {
. '{{amount}} ');
$sut = $this->createFilterBinder($document);
$sut->registerBindFilter(new class extends BindFilter {
- public function filterType(mixed $value):string {
+ public function type(mixed $value):string {
return get_debug_type($value);
}
});
@@ -2578,7 +2578,7 @@ public function testRegisterBindFilter_doesNotAffectIndependentDocuments():void
$firstDocument = new HTMLDocument('
');
$otherBinder = $this->createFilterBinder($firstDocument);
$otherBinder->registerBindFilter(new class extends BindFilter {
- public function filterUpper(string $value):string {
+ public function upper(string $value):string {
return strtoupper($value);
}
});
@@ -2593,7 +2593,7 @@ public function testBindKeyValue_retainsOriginalFilterExceptions():void {
$failure = new RuntimeException("Filter failed");
$sut->registerBindFilter(new class($failure) extends BindFilter {
public function __construct(private RuntimeException $failure) {}
- public function filterBroken(mixed $value):mixed {
+ public function broken(mixed $value):mixed {
throw $this->failure;
}
});
@@ -2614,7 +2614,7 @@ public function testBindData_filtersWithinOptionalElements(?bool $visible, ?stri
. '');
$sut = $this->createFilterBinder($document);
$sut->registerBindFilter(new class extends BindFilter {
- public function filterUpper(string $value):string {
+ public function upper(string $value):string {
return strtoupper($value);
}
});
@@ -2642,7 +2642,7 @@ public function testBindListCallback_filtersTheReturnedScalarValue():void {
$document = new HTMLDocument('');
$sut = $this->createFilterBinder($document);
$sut->registerBindFilter(new class extends BindFilter {
- public function filterUpper(string $value):string {
+ public function upper(string $value):string {
return strtoupper($value);
}
});
@@ -2667,15 +2667,15 @@ public function testBindTable_chainsFiltersFromSharedProvidersInRowTemplates():v
. '');
$sut = $this->createFilterBinder($document);
$sut->registerBindFilter(new class extends BindFilter {
- public function filterUpper(string $value):string {
+ public function upper(string $value):string {
return strtoupper($value);
}
- public function filterDecimal(float $value):string {
+ public function decimal(float $value):string {
return number_format($value, 2);
}
});
$applicationFilters = new class extends BindFilter {
- public function filterCurrency(string $value):string {
+ public function currency(string $value):string {
return $this->getDependency(stdClass::class)->symbol . $value;
}
};