Skip to content

Commit

Permalink
Allow id to be set/get using magic methods
Browse files Browse the repository at this point in the history
This allows you to set/get the id just like any other attribute. This is useful for example if you want to pluck all ids of a collection of items.
  • Loading branch information
JaZo committed Jul 1, 2019
1 parent 3622c5d commit 62d7932
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/Item.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
use Swis\JsonApi\Client\Traits\HasMeta;
use Swis\JsonApi\Client\Traits\HasType;

/**
* @property string|null id
*/
class Item extends Model implements ItemInterface
{
use HasLinks;
Expand Down Expand Up @@ -219,6 +222,20 @@ public function canBeIncluded(): bool
return true;
}

/**
* @param string $key
*
* @return mixed
*/
public function __get($key)
{
if ($key === 'id') {
return $this->getId();
}

return parent::__get($key);
}

/**
* @param string $key
*
Expand All @@ -243,6 +260,21 @@ public function hasAttribute($key): bool
return array_key_exists($key, $this->attributes);
}

/**
* @param string $key
* @param mixed $value
*/
public function __set($key, $value)
{
if ($key === 'id') {
$this->setId($value);

return;
}

parent::__set($key, $value);
}

/**
* Get the relationship data.
*
Expand Down Expand Up @@ -277,6 +309,10 @@ public function getRelationValue($key)
*/
public function __isset($key)
{
if ($key === 'id') {
return $this->hasId();
}

return parent::__isset($key) || $this->hasRelationship($key) || $this->hasRelationship(snake_case($key));
}

Expand Down
34 changes: 34 additions & 0 deletions tests/ItemTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,40 @@ public function it_returns_id_when_id_isset()
$this->assertEquals(1234, $item->getId());
}

/**
* @test
*/
public function it_can_set_the_id_using_the_magic_method()
{
$item = new Item();

$item->id = 1234;
$this->assertEquals(1234, $item->getId());
}

/**
* @test
*/
public function it_can_get_the_id_using_the_magic_method()
{
$item = new Item();
$item->setId(1234);

$this->assertEquals(1234, $item->id);
}

/**
* @test
*/
public function it_can_check_if_the_id_is_set_using_the_magic_method()
{
$item = new Item();

$this->assertFalse(isset($item->id));
$item->setId(1234);
$this->assertTrue(isset($item->id));
}

/**
* @test
*/
Expand Down

0 comments on commit 62d7932

Please sign in to comment.