Skip to content

Commit f844cd9

Browse files
authored
Merge pull request #135 from funkjedi/array-first-last-dot-notation
Add support for array first/last dot notation
2 parents dba1a1f + 9534e90 commit f844cd9

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/Liquid/Context.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,16 @@ private function variable($key)
330330
}
331331

332332
if (is_array($object)) {
333+
// if the last part of the context variable is .first we return the first array element
334+
if ($nextPartName == 'first' && count($parts) == 0 && !array_key_exists('first', $object)) {
335+
return StandardFilters::first($object);
336+
}
337+
338+
// if the last part of the context variable is .last we return the last array element
339+
if ($nextPartName == 'last' && count($parts) == 0 && !array_key_exists('last', $object)) {
340+
return StandardFilters::last($object);
341+
}
342+
333343
// if the last part of the context variable is .size we just return the count
334344
if ($nextPartName == 'size' && count($parts) == 0 && !array_key_exists('size', $object)) {
335345
return count($object);

tests/Liquid/ContextTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,30 @@ public function testOverrideSize()
319319
$this->assertEquals(5000, $this->context->get('hash.size'));
320320
}
321321

322+
public function testArrayFirst()
323+
{
324+
$this->context->set('array', array(11, 'jack', 43, 74, 5, 'tom'));
325+
$this->assertEquals(11, $this->context->get('array.first'));
326+
}
327+
328+
public function testOverrideFirst()
329+
{
330+
$this->context->set('array', array(11, 'jack', 43, 'first' => 74, 5, 'tom'));
331+
$this->assertEquals(74, $this->context->get('array.first'));
332+
}
333+
334+
public function testArrayLast()
335+
{
336+
$this->context->set('array', array(11, 'jack', 43, 74, 5, 'tom'));
337+
$this->assertEquals('tom', $this->context->get('array.last'));
338+
}
339+
340+
public function testOverrideLast()
341+
{
342+
$this->context->set('array', array(11, 'jack', 43, 'last' => 74, 5, 'tom'));
343+
$this->assertEquals(74, $this->context->get('array.last'));
344+
}
345+
322346
public function testDeepValueNotObject()
323347
{
324348
$this->context->set('example', array('foo' => new ToLiquidNotObject()));

0 commit comments

Comments
 (0)