Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/Listener/JsonApiListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -470,7 +470,7 @@ protected function _fieldSetsParameter($fieldSets, Subject $subject, $options):
{
// could be null for e.g. using integration tests
if ($fieldSets === null) {
return;
return;
}

// format $fieldSets to array acceptable by listener config()
Expand Down Expand Up @@ -875,6 +875,12 @@ protected function _getSingleEntity(Subject $subject): ?EntityInterface
}

if (!empty($subject->entities) && $subject->entities instanceof ResultSet) {
if ($subject->entities->first() === null) {
$repository = $subject->query->getRepository();
$entity = $repository->getEntityClass();
return new $entity();
}

return $subject->entities->first();
}

Expand Down
51 changes: 51 additions & 0 deletions tests/TestCase/Listener/JsonApiListenerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -855,6 +855,57 @@ public function testGetSingleEntity()
$result = $this->callProtectedMethod('_getSingleEntity', [$subject], $listener);
$this->assertSame($subject->entity, $result);
}

public function testGetSingleEntityForEmptyResultSet()
{
$controller = $this
->getMockBuilder(Controller::class)
->onlyMethods([])
->enableOriginalConstructor()
->getMock();

$listener = $this
->getMockBuilder(JsonApiListener::class)
->disableOriginalConstructor()
->addMethods(['_event'])
->onlyMethods(['_controller'])
->getMock();

$listener
->method('_controller')
->willReturn($controller);

$entity = new Entity();

$subject = $this
->getMockBuilder(Subject::class)
->getMock();

$subject->entities = $this
->getMockBuilder(ResultSet::class)
->disableOriginalConstructor()
->onlyMethods(['first'])
->getMock();

$subject->entities
->method('first')
->willReturn(null);

$query = $this
->getMockBuilder(Query::class)
->disableOriginalConstructor()
->getMock();

$subject->query = $query;
$subject->query
->method('getRepository')
->willReturn(TableRegistry::get('Countries'));

$this->setReflectionClassInstance($listener);
$result = $this->callProtectedMethod('_getSingleEntity', [$subject], $listener);

$this->assertInstanceOf('Cake\ORM\Entity', $result);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use Entity::class instead of a class name string.

}

/**
* Make sure associations not present in the find result are stripped
Expand Down