Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added the NestedRelation #290

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
37 changes: 37 additions & 0 deletions lib/Mapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
namespace Spot;

use Doctrine\DBAL\Types\Type;
use Spot\Relation\RelationAbstract;

/**
* Base DataMapper
Expand Down Expand Up @@ -218,6 +219,19 @@ public function belongsTo(EntityInterface $entity, $foreignEntity, $localKey)
return new Relation\BelongsTo($this, $foreignEntity, $foreignKey, $localKey, $entity->$localKey);
}

/**
* Relation: NestedRelation
*
* @param RelationAbstract $relationObject ,
* @param RelationAbstract $parentRelationObject
*
* @return Relation\NestedRelation|bool
*/
public function nestedRelation(RelationAbstract $relationObject, RelationAbstract $parentRelationObject)
{
return new Relation\NestedRelation($relationObject, $parentRelationObject);
}

/**
* Prepare entity and load necessary objects on it
* @param EntityInterface $entity
Expand Down Expand Up @@ -445,6 +459,8 @@ protected function with($collection, $entityName, $with = [])
return $collection;
}

$relationObjects = [];

foreach ($with as $relationName) {
// We only need a single entity from the collection, because we're
// going to modify the query to pass in an array of all the
Expand All @@ -458,6 +474,25 @@ protected function with($collection, $entityName, $with = [])

$relationObject = $singleEntity->relation($relationName);

// Handle nested relations
if ($relationObject === false) {
$relationNames = explode('.', $relationName);
if (count($relationNames) > 1) {
$finalRelationName = array_pop($relationNames);
$parentRelationName = implode('.', $relationNames);
if (!isset($relationObjects[$parentRelationName])) {
throw new \InvalidArgumentException("Nested relation exception: parent relation is not loaded:'" . $parentRelationName . "'");
}
$parentRelation = $relationObjects[$parentRelationName];
$parentRelationEntity = $parentRelation->entityName();
if( !isset($parentRelationEntity::relations($this, (new $parentRelationEntity))[$finalRelationName])) {
throw new \InvalidArgumentException("Nested relation exception: target relation '" . $finalRelationName . "' doesn't exist in Entity '" . $parentRelationEntity . "'");
}
$targetRelation = $parentRelationEntity::relations($this, (new $parentRelationEntity))[$finalRelationName];
$relationObject = $this->nestedRelation($targetRelation, $parentRelation);
}
}

// Ensure we have a valid relation name
if ($relationObject === false) {
throw new Exception("Invalid relation name eager-loaded in 'with' clause: No relation on $entityName with name '$relationName'");
Expand All @@ -478,6 +513,8 @@ protected function with($collection, $entityName, $with = [])

// Eager-load relation results back to collection
$collection = $relationObject->eagerLoadOnCollection($relationName, $collection);

$relationObjects[$relationName] = $relationObject;
}

$eventEmitter->emit('afterWith', [$this, $collection, $with]);
Expand Down
12 changes: 12 additions & 0 deletions lib/MapperInterface.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<?php
namespace Spot;

use Spot\Relation\RelationAbstract;

/**
* Base DataMapper Interface
*
Expand Down Expand Up @@ -92,6 +94,16 @@ public function hasOne(EntityInterface $entity, $foreignEntity, $foreignKey);
*/
public function belongsTo(EntityInterface $entity, $foreignEntity, $localKey);

/**
* Relation: NestedRelation
*
* Loading multilevel relations
*
* @param RelationAbstract $relationObject ,
* @param RelationAbstract $parentRelationObject
*/
public function nestedRelation(RelationAbstract $relationObject, RelationAbstract $parentRelationObject);

/**
* Prepare entity and load necessary objects on it
*/
Expand Down
186 changes: 186 additions & 0 deletions lib/Relation/NestedRelation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
<?php
namespace Spot\Relation;

use Spot\EntityInterface;
use Spot\Entity\Collection;

/**
* NestedRelation
*
* Used for eager-loading multilevel relations
*
* @package Spot
*/
class NestedRelation extends RelationAbstract
alexberezinsky marked this conversation as resolved.
Show resolved Hide resolved
{
/**
* @var RelationAbstract
*/
protected $relationObject;

/**
* @var RelationAbstract
*/
protected $parentRelationObject;

/**
* @var string
*/
protected $parentRelationName;

/**
* @var string
*/
protected $relationName;

/**
* @var string
*/
protected $entityName;

/*
* @var Collection
*/
protected $relationCollection;

/**
* @var array
*/
protected $relationCollectionReversedIdentities = [];

/**
* NestedRelation constructor
*
* @param RelationAbstract $relationObject
* @param RelationAbstract $parentRelationObject
*/
public function __construct (
RelationAbstract $relationObject,
RelationAbstract $parentRelationObject
)
{
$this->relationObject = $relationObject;
$this->parentRelationObject = $parentRelationObject;
$this->entityName = $relationObject->entityName();
}

/**
* Set identity values from given collection
*
* @param \Spot\Entity\Collection
*/
public function identityValuesFromCollection(Collection $collection)
{
throw new \BadMethodCallException("This method is not implemented in NestedRelation class");
}

/**
* Build query object
*
*/
protected function buildQuery()
{
throw new \BadMethodCallException("This method is not implemented in NestedRelation class");
}

/**
* Map relation results to original collection of entities
*
* @param string Relation name
* @param \Spot\Entity\Collection Collection of original entities to map results of query back to
*
* @return \Spot\Entity\Collection
*
* @throws \Exception
*/
public function eagerLoadOnCollection($relationName, Collection $collection)
{
$relationNames = explode('.', $relationName);
alexberezinsky marked this conversation as resolved.
Show resolved Hide resolved
$this->relationName = array_pop($relationNames);
$this->parentRelationName = array_pop($relationNames);

$this->createRelationCollection($collection);

$filledRelationCollection = $this->relationObject->eagerLoadOnCollection($this->relationName, $this->relationCollection);

if (!empty($this->relationCollectionReversedIdentities)) {
$result = [];
foreach ($filledRelationCollection as $ent) {
if (isset($this->relationCollectionReversedIdentities[$ent->primaryKey()])) {
$result[$this->relationCollectionReversedIdentities[$ent->primaryKey()]][] = $ent;
}
}
$filledRelationCollection = $result;
}

return $this->addFilledCollection($collection, $filledRelationCollection);
}

/**
* @param $collection
* @param $filledRelationCollection
*
* @return mixed
*/
public function addFilledCollection($collection, $filledRelationCollection)
{
$parentCollection = $collection;
if ($this->parentRelationObject instanceof NestedRelation) {
$parentCollection = $this->parentRelationObject->relationCollection;
}

foreach($parentCollection as $entity) {
if (isset($filledRelationCollection[$entity->primaryKey()])) {
$entity->relation($this->parentRelationName, $filledRelationCollection[$entity->primaryKey()]);
}
}

if ($this->parentRelationObject instanceof NestedRelation) {
return $this->parentRelationObject->addFilledCollection($collection, $parentCollection);
}

return $parentCollection;
}

/**
* @param Collection $collection
*/
public function createRelationCollection(Collection $collection)
{
if ($this->parentRelationObject instanceof NestedRelation) {
$collection = $this->parentRelationObject->relationCollection;
}
$relationCollection = [];
$resultsIdentities = [];
foreach($collection as $entity) {
$relatedEntity = $entity->relation($this->parentRelationName);
if ($relatedEntity instanceof Collection) {
foreach ($relatedEntity as $childEntity) {
$relationCollection[] = $childEntity;
$resultsIdentities[] = $childEntity->primaryKey();
$this->relationCollectionReversedIdentities[$childEntity->primaryKey()] = $entity->primaryKey();
}
} else {
$relationCollection[$entity->primaryKey()] = $relatedEntity;
$resultsIdentities[] = $relatedEntity->primaryKey();
}
}
$this->relationCollection = new Collection($relationCollection, $resultsIdentities);
$this->relationObject->identityValuesFromCollection($this->relationCollection);
}


/**
* Save related entities
*
* @param EntityInterface $entity Entity to save relation from
* @param string $relationName Name of the relation to save
* @param array $options Options to pass to the mappers
*
* @throws \Exception
*/
public function save(EntityInterface $entity, $relationName, $options = [])
{
throw new \BadMethodCallException("This method is not implemented in NestedRelation class");
}
}
2 changes: 1 addition & 1 deletion tests/CRUD.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/
class CRUD extends \PHPUnit_Framework_TestCase
{
private static $entities = ['PolymorphicComment', 'PostTag', 'Post\Comment', 'Post', 'Tag', 'Author', 'Setting', 'Event\Search', 'Event'];
private static $entities = ['PolymorphicComment', 'PostTag', 'Post\UserComment', 'Post\Comment', 'Post', 'Tag', 'Author', 'Setting', 'Event\Search', 'Event'];

public static function setupBeforeClass()
{
Expand Down
2 changes: 2 additions & 0 deletions tests/Entity/Post.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Spot\MapperInterface;
use Spot\EventEmitter;
use Spot\Query;
use SpotTest\Entity\Post\UserComment;

/**
* Post
Expand Down Expand Up @@ -38,6 +39,7 @@ public static function relations(MapperInterface $mapper, EntityInterface $entit
'tags' => $mapper->hasManyThrough($entity, 'SpotTest\Entity\Tag', 'SpotTest\Entity\PostTag', 'tag_id', 'post_id'),
'comments' => $mapper->hasMany($entity, 'SpotTest\Entity\Post\Comment', 'post_id')->order(['date_created' => 'ASC']),
'polymorphic_comments' => $mapper->hasMany($entity, 'SpotTest\Entity\PolymorphicComment', 'item_id')->where(['item_type' => 'post']),
'user_comments' => $mapper->hasMany($entity, 'SpotTest\Entity\Post\UserComment', 'post_id'),
'author' => $mapper->belongsTo($entity, 'SpotTest\Entity\Author', 'author_id')
];
}
Expand Down
37 changes: 37 additions & 0 deletions tests/Entity/Post/UserComment.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php
namespace SpotTest\Entity\Post;

use DateTime;
use Spot\Entity;
use Spot\EntityInterface;
use Spot\MapperInterface;
use Spot\Query;

/**
* Post Comment
*
* @package Spot
*/
class UserComment extends Entity
{
protected static $table = 'test_post_user_comments';

public static function fields()
{
return [
'id' => ['type' => 'integer', 'primary' => true, 'autoincrement' => true],
'post_id' => ['type' => 'integer', 'index' => true, 'required' => true],
'user_id' => ['type' => 'integer', 'index' => true, 'required' => true],
'body' => ['type' => 'text', 'required' => true],
'date_created' => ['type' => 'datetime']
];
}

public static function relations(MapperInterface $mapper, EntityInterface $entity)
{
return [
'post' => $mapper->belongsTo($entity, 'SpotTest\Entity\Post', 'post_id'),
'user' => $mapper->belongsTo($entity, 'SpotTest\Entity\User', 'user_id')
];
}
}
27 changes: 27 additions & 0 deletions tests/Entity/User.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php
namespace SpotTest\Entity;

/**
* Author
*
* @package Spot
*/
class User extends \Spot\Entity
{
protected static $table = 'test_users';

public static function fields()
{
return [
'id' => ['type' => 'integer', 'primary' => true, 'autoincrement' => true],
'email' => ['type' => 'string', 'required' => true, 'unique' => true,
'validation' => [
'email',
'length' => [4, 255]
]
], // Unique
'password' => ['type' => 'text', 'required' => true],
'date_created' => ['type' => 'datetime', 'value' => new \DateTime()]
];
}
}
Loading