Skip to content
This repository was archived by the owner on Oct 24, 2023. It is now read-only.

Commit 5d6ef10

Browse files
author
Jens Schulze
committed
feat(Attribute): enhance getting attribute by name from attributes collection
1 parent e77fc3f commit 5d6ef10

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/Core/Model/Common/AttributeCollection.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,23 @@ public function __get($attributeName)
4444
return null;
4545
}
4646

47+
public function __call($name, $arguments)
48+
{
49+
if (strpos($name, 'get') === 0) {
50+
$name = lcfirst(substr($name, 3));
51+
}
52+
return $this->getByName($name);
53+
}
54+
55+
56+
public function offsetGet($offset)
57+
{
58+
if (is_string($offset)) {
59+
return $this->getByName($offset);
60+
}
61+
return $this->getAt($offset);
62+
}
63+
4764
/**
4865
* @param $attributeName
4966
* @return Attribute|null

tests/unit/Model/Common/AttributeCollectionTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,29 @@ public function testAttributeAs()
7272
$this->assertInstanceOf(Enum::class, $attributes->getByName('collection-enum-set')->getValueAsEnumSet()->getAt(0));
7373
}
7474

75+
public function testAttributeByNameArrayAccess()
76+
{
77+
$collection = AttributeCollection::of();
78+
$collection->add(Attribute::fromArray(['name' => 'test', 'value' => 'Test']));
79+
80+
$this->assertSame('Test', $collection['test']->getValue());
81+
}
82+
83+
public function testAttributeByNameMagicCall()
84+
{
85+
$collection = AttributeCollection::of();
86+
$collection->add(Attribute::fromArray(['name' => 'test', 'value' => 'Test']));
87+
88+
$this->assertSame('Test', $collection->test()->getValue());
89+
$this->assertSame('Test', $collection->getTest()->getValue());
90+
}
91+
92+
public function testAttributeByPositionArrayAccess()
93+
{
94+
$collection = AttributeCollection::of();
95+
$collection->add(Attribute::fromArray(['name' => 'test', 'value' => 'Test']));
96+
$this->assertSame('Test', $collection[0]->getValue());
97+
}
7598

7699
public function testMagicGetNotSet()
77100
{

0 commit comments

Comments
 (0)