Skip to content

Commit

Permalink
ENH Rendering scalars in ArrayList in templates
Browse files Browse the repository at this point in the history
  • Loading branch information
emteknetnz committed May 14, 2024
1 parent 0c8fcfb commit c93d391
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/View/SSViewer_Scope.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@
use ArrayIterator;
use Countable;
use Iterator;
use SilverStripe\ORM\FieldType\DBBoolean;
use SilverStripe\ORM\FieldType\DBText;
use SilverStripe\ORM\FieldType\DBFloat;
use SilverStripe\ORM\FieldType\DBInt;
use SilverStripe\ORM\FieldType\DBField;

/**
* This tracks the current scope for an SSViewer instance. It has three goals:
Expand Down Expand Up @@ -339,6 +344,9 @@ public function next()
public function __call($name, $arguments)
{
$on = $this->itemIterator ? $this->itemIterator->current() : $this->item;
if (is_scalar($on) || is_null($on)) {
$on = $this->convertPrimitiveToDBField($on);
}
$retval = $on ? $on->$name(...$arguments) : null;

$this->resetLocalScope();
Expand Down Expand Up @@ -368,4 +376,15 @@ protected function getUpIndex()
{
return $this->upIndex;
}

private function convertPrimitiveToDBField(bool|string|float|int|null $value): DBField
{
return match (gettype($value)) {
'boolean' => DBBoolean::create()->setValue($value),
'string' => DBText::create()->setValue($value),
'double' => DBFloat::create()->setValue($value),
'integer' => DBInt::create()->setValue($value),
'NULL' => DBText::create()->setValue('NULL')
};
}
}
11 changes: 11 additions & 0 deletions tests/php/View/SSViewerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2218,4 +2218,15 @@ public function testFromStringCaching()
$this->assertTrue(file_exists($cacheFile ?? ''), 'Cache file wasn\'t created when it was meant to');
unlink($cacheFile ?? '');
}

public function testPrimitivesConvertedToDBFields()
{
$data = new ArrayData([
'Foo' => new ArrayList(['hello', true, 456, 7.89, null])
]);
$this->assertEqualIgnoringWhitespace(
'hello 1 456 7.89 NULL',
$this->render('<% loop $Foo %>$Me<% end_loop %>', $data)
);
}
}

0 comments on commit c93d391

Please sign in to comment.