Skip to content

Commit

Permalink
Merge branch 'release/v0.2.5' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
betterthanclay committed Jan 25, 2023
2 parents 060a2af + 008f73e commit a99babb
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 0 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
## v0.2.5 (2023-01-25)
* Added normalize() method to Elements

## v0.2.4 (2023-01-04)
* Improved :attr binding support

Expand Down
5 changes: 5 additions & 0 deletions src/Element.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ interface Element extends
*/
public function setBody(mixed $body): static;

/**
* @return $this
*/
public function normalize(): static;

public function render(bool $pretty = false): ?Buffer;
public function renderContent(bool $pretty = false): ?Buffer;
}
22 changes: 22 additions & 0 deletions src/ElementTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,28 @@ public function __construct(
$this->merge($content);
}


/**
* Normalize body content to individual items
*
* @return $this
*/
public function normalize(): static
{
$items = [];

foreach ($this->items as $item) {
foreach ($this->normalizeChild($item, true) as $child) {
$items[] = $child;
}
}

$this->items = $items;
return $this;
}



/**
* Render to more readable string (for dump)
*/
Expand Down
45 changes: 45 additions & 0 deletions src/Markup/ChildRendererTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
namespace DecodeLabs\Elementary\Markup;

use DecodeLabs\Coercion;
use DecodeLabs\Elementary\Buffer;
use DecodeLabs\Elementary\Element;
use DecodeLabs\Elementary\Markup;

Expand Down Expand Up @@ -68,6 +69,50 @@ protected function renderChild(
return (string)$output;
}

/**
* Normalize child elements
*
* @return Generator<mixed>
*/
protected function normalizeChild(
mixed $value,
bool $pretty = false
): Generator {
if (
is_callable($value) &&
is_object($value)
) {
yield from $this->normalizeChild($value($this), $pretty);
return;
}

if ($value instanceof Proxy) {
$value = $value->toMarkup();
}

if (
is_iterable($value) &&
!$value instanceof Markup
) {
foreach ($value as $part) {
yield $this->newBuffer($this->renderChild($part, $pretty));
}

if (
$value instanceof Generator &&
null !== ($part = $value->getReturn())
) {
yield $this->newBuffer($this->renderChild($part, $pretty));
}

return;
}

yield $value;
}

abstract protected function newBuffer(?string $value): Buffer;

/**
* Escape HTML
*/
Expand Down

0 comments on commit a99babb

Please sign in to comment.