Skip to content

Commit

Permalink
Generate attribute accessors
Browse files Browse the repository at this point in the history
  • Loading branch information
caendesilva committed Jul 10, 2024
1 parent 8080709 commit 8b6d678
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -127,4 +127,51 @@ public function getExtraAttributes(): array
{
return $this->attributes;
}

/**
* Set an extra attribute for the navigation item.
*
* @param string $key
* @param scalar $value
* @return $this
*/
public function setAttribute(string $key, $value): self
{
$this->attributes[$key] = $value;
return $this;
}

/**
* Set multiple extra attributes for the navigation item.
*
* @param array<string, scalar> $attributes
* @return $this
*/
public function setAttributes(array $attributes): self
{
$this->attributes = array_merge($this->attributes, $attributes);
return $this;
}

/**
* Get an extra attribute of the navigation item.
*
* @param string $key
* @param scalar|null $default
* @return scalar|null
*/
public function getAttribute(string $key, $default = null)
{
return $this->attributes[$key] ?? $default;
}

/**
* Get all extra attributes of the navigation item.
*
* @return array<string, scalar>
*/
public function getAttributes(): array
{
return $this->attributes;
}
}
29 changes: 29 additions & 0 deletions packages/framework/tests/Unit/NavigationItemTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -337,4 +337,33 @@ public function testCreateWithAttributes()
$item = NavigationItem::create('foo', 'Test', 500, ['class' => 'active']);
$this->assertSame(['class' => 'active'], $item->getExtraAttributes());
}

public function testSetAttribute()
{
$item = new NavigationItem('foo', 'Test');
$item->setAttribute('class', 'active');
$this->assertSame('active', $item->getAttribute('class'));
}

public function testSetAttributes()
{
$item = new NavigationItem('foo', 'Test');
$item->setAttributes(['class' => 'active', 'id' => 'nav-item']);
$this->assertSame(['class' => 'active', 'id' => 'nav-item'], $item->getAttributes());
}

public function testGetAttribute()
{
$item = new NavigationItem('foo', 'Test', 500, ['class' => 'active']);
$this->assertSame('active', $item->getAttribute('class'));
$this->assertNull($item->getAttribute('id'));
$this->assertSame('default', $item->getAttribute('id', 'default'));
}

public function testGetAttributes()
{
$attributes = ['class' => 'active', 'id' => 'nav-item'];
$item = new NavigationItem('foo', 'Test', 500, $attributes);
$this->assertSame($attributes, $item->getAttributes());
}
}

0 comments on commit 8b6d678

Please sign in to comment.