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

Allow using callbacks with load relations extender #3116

Merged
merged 8 commits into from
Nov 1, 2021
Merged
Show file tree
Hide file tree
Changes from 3 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
30 changes: 25 additions & 5 deletions src/Api/Controller/AbstractSerializeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -165,15 +165,20 @@ protected function getRelationsToLoad(): array

/**
* Eager loads the required relationships.
*
* @param Collection $models
* @param array $relations
* @return void
*/
protected function loadRelations(Collection $models, array $relations): void
protected function loadRelations(Collection $models, array $relations, ServerRequestInterface $request = null): void
{
$addedRelations = $this->getRelationsToLoad();

// Filter out callables
$callables = [];
foreach ($addedRelations as $name => $relation) {
if (is_callable($relation)) {
$addedRelations[$name] = $name;
$callables[$name] = $relation;
}
}

if (! empty($addedRelations)) {
usort($addedRelations, function ($a, $b) {
return substr_count($a, '.') - substr_count($b, '.');
Expand All @@ -194,6 +199,21 @@ protected function loadRelations(Collection $models, array $relations): void

if (! empty($relations)) {
$relations = array_unique($relations);
}

foreach ($relations as $k => $relation) {
if (isset($callables[$relation])) {
$load = $callables[$relation];

$relations[$relation] = function ($query) use ($load, $request) {
$load($query, $request);
};

unset($relations[$k]);
}
}

if (! empty($relations)) {
$models->loadMissing($relations);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Api/Controller/ListDiscussionsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ protected function data(ServerRequestInterface $request, Document $document)

$results = $results->getResults();

$this->loadRelations($results, $include);
$this->loadRelations($results, $include, $request);

if ($relations = array_intersect($include, ['firstPost', 'lastPost', 'mostRelevantPost'])) {
foreach ($results as $discussion) {
Expand Down
2 changes: 1 addition & 1 deletion src/Api/Controller/ListGroupsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ protected function data(ServerRequestInterface $request, Document $document)

$results = Group::whereVisibleTo($actor)->get();

$this->loadRelations($results, []);
$this->loadRelations($results, [], $request);

return $results;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Api/Controller/ListNotificationsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ protected function data(ServerRequestInterface $request, Document $document)

$notifications = $this->notifications->findByUser($actor, $limit + 1, $offset);

$this->loadRelations($notifications, array_diff($include, ['subject.discussion']));
$this->loadRelations($notifications, array_diff($include, ['subject.discussion']), $request);

$notifications = $notifications->all();

Expand Down
2 changes: 1 addition & 1 deletion src/Api/Controller/ListPostsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ protected function data(ServerRequestInterface $request, Document $document)

$results = $results->getResults();

$this->loadRelations($results, $include);
$this->loadRelations($results, $include, $request);

return $results;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Api/Controller/ListUsersController.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ protected function data(ServerRequestInterface $request, Document $document)

$results = $results->getResults();

$this->loadRelations($results, $include);
$this->loadRelations($results, $include, $request);

return $results;
}
Expand Down
4 changes: 3 additions & 1 deletion src/Extend/ApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
use Flarum\Extension\Extension;
use Flarum\Foundation\ContainerUtil;
use Illuminate\Contracts\Container\Container;
use Illuminate\Database\Query\Builder;
use Psr\Http\Message\ServerRequestInterface;

class ApiController implements ExtenderInterface
{
Expand Down Expand Up @@ -298,7 +300,7 @@ public function setSort(array $sort, $callback = null): self
* To force load the relationship, both levels have to be specified,
* example: ['relation', 'relation.subRelation'].
*
* @param string|string[] $relations
* @param string|string[]|array<string, callable(Builder, ServerRequestInterface|null): void> $relations
* @return self
*/
public function load($relations): self
Expand Down
121 changes: 121 additions & 0 deletions tests/integration/extenders/ApiControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -803,6 +803,127 @@ public function custom_second_level_relation_is_not_loaded_when_first_level_is_n

$this->assertTrue($users->pluck('firstLevelRelation')->filter->relationLoaded('secondLevelRelation')->isEmpty());
}

/**
* @test
*/
public function custom_callable_first_level_relation_is_loaded_if_added()
{
$users = null;

$this->extend(
(new Extend\Model(User::class))
->hasOne('firstLevelRelation', Post::class, 'user_id'),
(new Extend\ApiController(ListUsersController::class))
->load(['firstLevelRelation' => function ($query, $request) {}])
->prepareDataForSerialization(function ($controller, $data) use (&$users) {
$users = $data;

return [];
})
);

$this->send(
$this->request('GET', '/api/users', [
'authenticatedAs' => 1,
])
);

$this->assertFalse($users->filter->relationLoaded('firstLevelRelation')->isEmpty());
}

/**
* @test
*/
public function custom_callable_second_level_relation_is_loaded_if_added()
{
$users = null;

$this->extend(
(new Extend\Model(User::class))
->hasOne('firstLevelRelation', Post::class, 'user_id'),
(new Extend\Model(Post::class))
->belongsTo('secondLevelRelation', Discussion::class),
(new Extend\ApiController(ListUsersController::class))
->load(['firstLevelRelation', 'firstLevelRelation.secondLevelRelation' => function ($query, $request) {}])
->prepareDataForSerialization(function ($controller, $data) use (&$users) {
$users = $data;

return [];
})
);

$this->send(
$this->request('GET', '/api/users', [
'authenticatedAs' => 1,
])
);

$this->assertFalse($users->pluck('firstLevelRelation')->filter->relationLoaded('secondLevelRelation')->isEmpty());
}

/**
* @test
*/
public function custom_callable_second_level_relation_is_not_loaded_when_first_level_is_not()
{
$users = null;

$this->extend(
(new Extend\Model(User::class))
->hasOne('firstLevelRelation', Post::class, 'user_id'),
(new Extend\Model(Post::class))
->belongsTo('secondLevelRelation', Discussion::class),
(new Extend\ApiController(ListUsersController::class))
->load(['firstLevelRelation.secondLevelRelation' => function ($query, $request) {}])
->prepareDataForSerialization(function ($controller, $data) use (&$users) {
$users = $data;

return [];
})
);

$this->send(
$this->request('GET', '/api/users', [
'authenticatedAs' => 1,
])
);

$this->assertTrue($users->pluck('firstLevelRelation')->filter->relationLoaded('secondLevelRelation')->isEmpty());
}

/**
* @test
*/
public function custom_callable_second_level_relation_is_loaded_when_first_level_is()
{
$users = null;

$this->extend(
(new Extend\Model(User::class))
->hasOne('firstLevelRelation', Post::class, 'user_id'),
(new Extend\Model(Post::class))
->belongsTo('secondLevelRelation', Discussion::class),
(new Extend\ApiController(ListUsersController::class))
->load([
'firstLevelRelation' => function ($query, $request) {},
'firstLevelRelation.secondLevelRelation' => function ($query, $request) {}
])
->prepareDataForSerialization(function ($controller, $data) use (&$users) {
$users = $data;

return [];
})
);

$this->send(
$this->request('GET', '/api/users', [
'authenticatedAs' => 1,
])
);

$this->assertTrue($users->pluck('firstLevelRelation')->filter->relationLoaded('secondLevelRelation')->isNotEmpty());
}
}

class CustomDiscussionSerializer extends DiscussionSerializer
Expand Down