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
7 changes: 2 additions & 5 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,9 @@ jobs:
strategy:
fail-fast: false
matrix:
php: [8.1, 8.2, 8.3]
laravel: [10.*, 11.*]
php: [8.2, 8.3, 8.4]
laravel: [10.*, 11.*, 12.*]
dependency-version: [prefer-lowest, prefer-stable]
exclude:
- php: 8.1
laravel: 11.*

name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }}

Expand Down
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@ composer.phar
composer.lock
vendor
.php_cs.cache
.phpunit.result.cache
.phpunit.result.cache
.phpunit.cache
.claude
16 changes: 8 additions & 8 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@
}
},
"require": {
"php": "^8.1",
"illuminate/container": "^10.0|^11.0",
"illuminate/database": "^10.0|^11.0",
"illuminate/support": "^10.0|^11.0",
"spatie/laravel-query-builder": "^5.0"
"php": "^8.2|^8.3|^8.4",
"illuminate/container": "^10.0|^11.0|^12.0",
"illuminate/database": "^10.0|^11.0|^12.0",
"illuminate/support": "^10.0|^11.0|^12.0",
"spatie/laravel-query-builder": "^6.0"
},
"require-dev": {
"phpunit/phpunit": "^9.0",
"laravel/laravel": "^10.0|^11.0",
"phpunit/phpunit": "^10.0|^11.0",
"laravel/laravel": "^10.0|^11.0|^12.0",
"mockery/mockery": "^1.5",
"makeabledk/laravel-factory-enhanced": "^5.0",
"makeabledk/laravel-factory-enhanced": "^6.0",
"fakerphp/faker": "^1.18"
},
"autoload-dev": {
Expand Down
36 changes: 13 additions & 23 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -1,25 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
verbose="true"
>
<testsuites>
<testsuite name="Package Test Suite">
<directory suffix="Test.php">./tests/</directory>
</testsuite>
</testsuites>
<php>
<ini name="display_errors" value="1" />
<server name="APP_ENV" value="testing" />
<server name="APP_DEBUG" value="true" />
<server name="DB_CONNECTION" value="sqlite" />
<server name="DB_DATABASE" value=":memory:" />
</php>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" backupGlobals="false" bootstrap="vendor/autoload.php" colors="true" processIsolation="false" stopOnFailure="false" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.5/phpunit.xsd" cacheDirectory=".phpunit.cache" backupStaticProperties="false">
<testsuites>
<testsuite name="Package Test Suite">
<directory suffix="Test.php">./tests/</directory>
</testsuite>
</testsuites>
<php>
<ini name="display_errors" value="1"/>
<server name="APP_ENV" value="testing"/>
<server name="APP_DEBUG" value="true"/>
<server name="DB_CONNECTION" value="sqlite"/>
<server name="DB_DATABASE" value=":memory:"/>
</php>
</phpunit>
7 changes: 6 additions & 1 deletion src/Endpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Makeable\ApiEndpoints\Concerns\NormalizesRelationNames;
use Spatie\QueryBuilder\AllowedInclude;

class Endpoint
{
Expand Down Expand Up @@ -203,7 +205,7 @@ public function getQuery()
* @param Request|null $request
* @return \Makeable\ApiEndpoints\QueryBuilder
*/
public function toQueryBuilder(Request $request = null)
public function toQueryBuilder(?Request $request = null)
{
$builder = call_user_func([static::$queryBuilderClass, 'for'], $this->model, $request);

Expand Down Expand Up @@ -342,6 +344,9 @@ protected function buildNamespacedConstraintArrays($relations)
};
}

// NOTE: In order to support AllowedInclude::relationship() we'd need to do
// additional normalization here since it returns a Collection of AllowedInclude.

// Furthermore we'll allow for multiple constraints on the same relation.
// Later on we'll apply all of the constraints into the same query.
return [$relation => Arr::wrap($constraint)];
Expand Down
45 changes: 26 additions & 19 deletions src/QueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@
use Closure;
use Illuminate\Contracts\Pagination\CursorPaginator;
use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Makeable\ApiEndpoints\Concerns\AddsAppendsToQuery;
use Makeable\ApiEndpoints\Concerns\NormalizesRelationNames;
use Spatie\QueryBuilder\AllowedInclude;
use Spatie\QueryBuilder\QueryBuilder as SpatieBuilder;

class QueryBuilder extends SpatieBuilder
Expand All @@ -21,6 +24,15 @@ class QueryBuilder extends SpatieBuilder
allowedAppends as originalAllowedAppends;
}

public function __construct(
protected Relation|EloquentBuilder $subject,
?Request $request = null
) {
$this->request = $request
? QueryBuilderRequest::fromRequest($request)
: app(QueryBuilderRequest::class);
}

/**
* @var array
*/
Expand All @@ -47,27 +59,14 @@ public function __call($name, $arguments)
return $result;
}

/**
* @param Request|null $request
* @return QueryBuilder
*/
protected function initializeRequest(?Request $request = null): static
{
$this->request = $request
? QueryBuilderRequest::fromRequest($request)
: app(QueryBuilderRequest::class);

return $this;
}

/**
* @param $appends
* @return QueryBuilder
*/
public function allowedAppends($appends): static
{
collect($appends)
->mapWithKeys(Closure::fromCallable([$this, 'normalizeRelationQueries']))
->flatMap(fn ($constraints, $relation) => $this->normalizeRelationQueries($constraints, $relation))
->tap(function (Collection $appends) {
$this->originalAllowedAppends($appends->keys()->all());
})
Expand All @@ -94,7 +93,7 @@ public function allowedAppends($appends): static
* @param Collection|null $appends
* @return mixed
*/
protected function addAppendsToResults(Collection $results, Collection $appends = null)
protected function addAppendsToResults(Collection $results, ?Collection $appends = null)
{
$appends = collect($appends ?: $this->request->appends());

Expand Down Expand Up @@ -129,7 +128,7 @@ protected function addAppendsToResults(Collection $results, Collection $appends
public function allowedIncludes($includes): static
{
collect($includes)
->mapWithKeys(Closure::fromCallable([$this, 'normalizeRelationQueries']))
->flatMap(fn ($constraints, $relation) => $this->normalizeRelationQueries($constraints, $relation))
->mapWithKeys(fn ($constraints, $relation) => [$this->normalizeRelationName($relation) => $constraints])
->tap(function (Collection $includes) {
$this->queueConstraints($includes);
Expand Down Expand Up @@ -244,12 +243,20 @@ protected function mergeConstraints(...$constraints): Closure
* @param $relation
* @return array
*/
protected function normalizeRelationQueries($constraints, $relation): array
protected function normalizeRelationQueries($constraints, $relation): Collection
{
if (is_numeric($relation)) {
// Currently not working as intended
// // Support AllowedInclude::relationship() which returns a Collection of AllowedInclude
// if (is_numeric($relation) && is_array($constraints) && count($constraints) === 1 && $constraints[0] instanceof Collection) {
// return $constraints[0]->mapWithKeys(function (AllowedInclude $include) {
// return [$include->getName() => [fn ($query) => $include->include($query)]];
// });
// }

if (is_numeric($relation) && is_string($constraints)) {
[$constraints, $relation] = [[], $constraints];
}

return [$relation => $constraints];
return collect([$relation => $constraints]);
}
}
41 changes: 27 additions & 14 deletions tests/Feature/EndpointHttpTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ class EndpointHttpTest extends TestCase
{
use RefreshDatabase;

/** @test */
public function it_can_load_model_with_nested_endpoint_relations()
public function test_it_can_load_model_with_nested_endpoint_relations()
{
$user = factory(User::class)
->with(1, 'servers.databases')
Expand All @@ -30,8 +29,7 @@ public function it_can_load_model_with_nested_endpoint_relations()
]]);
}

/** @test **/
public function any_allowed_relation_is_also_countable()
public function test_any_allowed_relation_is_also_countable()
{
$user = factory(User::class)->with(2, 'servers')->create();

Expand All @@ -45,8 +43,7 @@ public function any_allowed_relation_is_also_countable()
]]);
}

/** @test **/
public function it_appends_attributes()
public function test_it_appends_attributes()
{
$server = factory(Server::class)->create();

Expand All @@ -60,8 +57,7 @@ public function it_appends_attributes()
]]);
}

/** @test **/
public function it_accepts_custom_queries_for_appends()
public function test_it_accepts_custom_queries_for_appends()
{
$user = factory(User::class)->with(1, 'servers')->create();

Expand All @@ -77,8 +73,7 @@ public function it_accepts_custom_queries_for_appends()
]]);
}

/** @test */
public function filters_may_be_applied()
public function test_filters_may_be_applied()
{
$notFavorite = factory(Server::class)->create(['is_favorite' => false]);
$favorite = factory(Server::class)->create(['is_favorite' => true]);
Expand All @@ -93,8 +88,7 @@ public function filters_may_be_applied()
]]);
}

/** @test **/
public function it_normalizes_snake_case_to_camel_case()
public function test_it_normalizes_snake_case_to_camel_case()
{
factory(Team::class)
->with(1, 'users')
Expand All @@ -111,8 +105,7 @@ public function it_normalizes_snake_case_to_camel_case()
->assertJsonCount(1, '0.users.0.favorite_servers.0.databases');
}

/** @test **/
public function it_supports_circular_includes()
public function test_it_supports_circular_includes()
{
$server = factory(Server::class)
->with(1, 'databases')
Expand All @@ -132,4 +125,24 @@ public function it_supports_circular_includes()
]],
]]);
}

// Currently not working as intended
// public function test_it_supports_allowed_includes_syntax()
// {
// $server = factory(Server::class)
// ->with(1, 'users.teams')
// ->create();
//
// $this
// ->withoutExceptionHandling()
// ->getJson('/servers?include=users.teams,users.teams_count')
// ->assertSuccessful()
// ->assertJson([[
// 'id' => $server->id,
// 'users' => [[
// 'teams' => [
// ],
// ]],
// ]]);
// }
}
Loading