Skip to content

Commit

Permalink
Add ClassHydrator::hydrateObject() method
Browse files Browse the repository at this point in the history
  • Loading branch information
kocsismate committed Dec 24, 2017
1 parent b229c9d commit 2cead1a
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 1 deletion.
13 changes: 13 additions & 0 deletions src/JsonApi/Hydrator/ClassHydrator.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,19 @@ public function hydrate(Document $document)
return $this->hydratePrimaryResources($document);
}

public function hydrateObject(Document $document): stdClass
{
if ($document->isSingleResourceDocument() === false) {
return new stdClass();
}

if ($document->hasAnyPrimaryResources() === false) {
return new stdClass();
}

return $this->hydratePrimaryResource($document);
}

public function hydrateCollection(Document $document): iterable
{
if ($document->hasAnyPrimaryResources() === false) {
Expand Down
76 changes: 75 additions & 1 deletion tests/JsonApi/Hydrator/ClassHydratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
namespace WoohooLabs\Yang\Tests\JsonApi\Hydrator;

use PHPUnit\Framework\TestCase;
use stdClass;
use WoohooLabs\Yang\JsonApi\Hydrator\ClassHydrator;
use WoohooLabs\Yang\JsonApi\Schema\Document;

Expand Down Expand Up @@ -366,7 +367,80 @@ public function hydrateObjectWithRecursiveRelationships()
/**
* @test
*/
public function hydrateEmptyCollection()
public function hydrateObjectWhenCollectionEmpty()
{
$document = [
"data" => [],
];

$document = Document::createFromArray($document);
$hydrator = new ClassHydrator();
$object = $hydrator->hydrateObject($document);

$this->assertEquals(new stdClass(), $object);
}

/**
* @test
*/
public function hydrateObjectWhenCollection()
{
$document = [
"data" => [
[
"type" => "a",
"id" => "1",
],
],
];

$document = Document::createFromArray($document);
$hydrator = new ClassHydrator();
$object = $hydrator->hydrateObject($document);

$this->assertEquals(new stdClass(), $object);
}

/**
* @test
*/
public function hydrateObjectWhenSingleResourceEmpty()
{
$document = [
"data" => null,
];

$document = Document::createFromArray($document);
$hydrator = new ClassHydrator();
$object = $hydrator->hydrateObject($document);

$this->assertEquals(new stdClass(), $object);
}

/**
* @test
*/
public function hydrateObjectWhenSingleResource()
{
$document = [
"data" => [
"type" => "a",
"id" => "1",
],
];

$document = Document::createFromArray($document);
$hydrator = new ClassHydrator();
$object = $hydrator->hydrateObject($document);

$this->assertEquals("a", $object->type);
$this->assertEquals("1", $object->id);
}

/**
* @test
*/
public function hydrateCollectionWhenEmpty()
{
$document = [
"data" => [],
Expand Down

0 comments on commit 2cead1a

Please sign in to comment.