Skip to content

Commit

Permalink
Implement and test bound attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
g105b committed Dec 27, 2017
1 parent 3ebabac commit 94fe998
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/Bindable.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php
namespace Gt\DomTemplate;

use Gt\Dom\Attr;
use Gt\Dom\Element as BaseElement;

trait Bindable {
Expand Down Expand Up @@ -51,7 +52,7 @@ protected function setData(BaseElement $element, iterable $data):void {
continue;
}

$key = $attr->value;
$key = $this->getKeyFromAttribute($element, $attr);
$dataValue = $data[$key];

switch($matches[1]) {
Expand All @@ -65,4 +66,15 @@ protected function setData(BaseElement $element, iterable $data):void {
}
}
}

protected function getKeyFromAttribute(BaseElement $element, Attr $attr):string {
$key = $attr->value;

if($key[0] === "@") {
$key = substr($key, 1);
return $element->getAttribute($key);
}

return $key;
}
}
15 changes: 15 additions & 0 deletions test/unit/BindableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,19 @@ public function testBindExistingElements() {
self::assertEquals($name,$spanChildren[0]->innerText);
self::assertEquals($age,$spanChildren[1]->innerText);
}

public function testBindAttributeLookup() {
$document = new HTMLDocument(Helper::HTML_NO_TEMPLATES_BIND_ATTR);
$name = "Julia Dixon";
$age = 26;
$document->bind([
"name" => $name,
"age" => $age,
]);

$boundDataTestElement = $document->querySelector(".bound-data-test");
$spanChildren = $boundDataTestElement->querySelectorAll("span");
self::assertEquals($name,$spanChildren[0]->innerText);
self::assertEquals($age,$spanChildren[1]->innerText);
}
}
21 changes: 21 additions & 0 deletions test/unit/Helper/Helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,27 @@ class Helper {
</main>
HTML;

const HTML_NO_TEMPLATES_BIND_ATTR = <<<HTML
<!doctype html>
<meta charset="utf-8" />
<title>This document has no templates but does have bound attributes</title>
<main>
<section>
<h1>Hello, World!</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. A aliquam animi
deleniti distinctio dolore doloremque, eius et facilis iure maiores nihil
nisi, nostrum optio perferendis perspiciatis, rerum vitae voluptates.
</p>
<p class="bound-data-test">
My name is <span id="name" name="person_id" data-bind:text="@id">Example</span>
and I am <span name="age" data-bind:text="@name">0</span> years old.
</p>
</section>
</main>
HTML;


const HTML_TEMPLATES = <<<HTML
<!doctype html>
<meta charset="utf-8" />
Expand Down

0 comments on commit 94fe998

Please sign in to comment.