Skip to content

Commit

Permalink
Fixes #2. Add php magic __get function
Browse files Browse the repository at this point in the history
  • Loading branch information
yadakhov committed Jun 13, 2015
1 parent 1298e73 commit 928da74
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/Json.php
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,24 @@ public function __toString()
}
}

/**
* PHP get magic function.
*
* @param $name
* @return mixed
* @throws Exception
*/
public function __get($name)
{
if ($this->bodyType === 'array' && Arr::has($this->body, $name)) {
return Arr::get($this->body, $name);
} elseif ($this->bodyType === 'stdClass' && isset($this->body->{$name})) {
return $this->body->{$name};
}

throw new \Exception(sprintf('Non-existent property %s.', $name));
}

/**
* Returns data which can be serialized by json_encode().
*
Expand Down
16 changes: 16 additions & 0 deletions tests/JsonTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,20 @@ public function testToArrayPrimitiveJson()
$this->assertEquals(null, $json->toArray());
}

public function testCreateFactoryMethod()
{
$json = Json::create();

$this->assertTrue($json instanceof Json);
}

public function testMagicGetter()
{
// pass by json
$json = new Json('{"key":"value"}');
$this->assertEquals('value', $json->key);

$json = new Json(['name' => 'Yada Khov']);
$this->assertEquals('Yada Khov', $json->name);
}
}

0 comments on commit 928da74

Please sign in to comment.