From d6ed4ec0e16319ca81b59dcc7789fd3410d0199e Mon Sep 17 00:00:00 2001 From: Eduard Lupacescu Date: Wed, 20 May 2020 00:29:45 +0300 Subject: [PATCH 1/2] Attach related repositories --- routes/api.php | 21 +++--- .../RepositoryAttachController.php | 65 ++++++++++++++++++ .../Requests/InteractWithRepositories.php | 62 ++++++++++++++++- src/Http/Requests/RepositoryAttachRequest.php | 8 +++ src/Http/Requests/RestifyRequest.php | 1 + src/Repositories/Repository.php | 13 ++++ .../RepositoryFilterControllerTest.php | 2 - .../RepositoryPivotControllerTest.php | 66 +++++++++++++++++++ tests/Factories/CompanyFactory.php | 21 ++++++ tests/Fixtures/Company/Company.php | 23 +++++++ tests/Fixtures/Company/CompanyRepository.php | 10 +++ tests/Fixtures/User/User.php | 8 +++ tests/IntegrationTest.php | 2 + ...2_22_000005_create_Company_user__table.php | 33 ++++++++++ ...19_12_22_000005_create_companies_table.php | 32 +++++++++ 15 files changed, 354 insertions(+), 13 deletions(-) create mode 100644 src/Http/Controllers/RepositoryAttachController.php create mode 100644 src/Http/Requests/RepositoryAttachRequest.php create mode 100644 tests/Controllers/RepositoryPivotControllerTest.php create mode 100644 tests/Factories/CompanyFactory.php create mode 100644 tests/Fixtures/Company/Company.php create mode 100644 tests/Fixtures/Company/CompanyRepository.php create mode 100644 tests/Migrations/2019_12_22_000005_create_Company_user__table.php create mode 100644 tests/Migrations/2019_12_22_000005_create_companies_table.php diff --git a/routes/api.php b/routes/api.php index dec06ba36..ca1fc4eb6 100644 --- a/routes/api.php +++ b/routes/api.php @@ -4,21 +4,26 @@ use Binaryk\LaravelRestify\Http\Controllers\RepositoryDestroyController; use Binaryk\LaravelRestify\Http\Controllers\RepositoryFilterController; use Binaryk\LaravelRestify\Http\Controllers\RepositoryIndexController; +use Binaryk\LaravelRestify\Http\Controllers\RepositoryAttachController; use Binaryk\LaravelRestify\Http\Controllers\RepositoryShowController; use Binaryk\LaravelRestify\Http\Controllers\RepositoryStoreController; use Binaryk\LaravelRestify\Http\Controllers\RepositoryUpdateController; use Illuminate\Support\Facades\Route; // Global Search... -Route::get('/search', '\\'.GlobalSearchController::class); +Route::get('/search', '\\' . GlobalSearchController::class); // Filters -Route::get('/{repository}/filters', '\\'.RepositoryFilterController::class); +Route::get('/{repository}/filters', '\\' . RepositoryFilterController::class); // API CRUD -Route::get('/{repository}', '\\'.RepositoryIndexController::class); -Route::post('/{repository}', '\\'.RepositoryStoreController::class); -Route::get('/{repository}/{repositoryId}', '\\'.RepositoryShowController::class); -Route::patch('/{repository}/{repositoryId}', '\\'.RepositoryUpdateController::class); -Route::put('/{repository}/{repositoryId}', '\\'.RepositoryUpdateController::class); -Route::delete('/{repository}/{repositoryId}', '\\'.RepositoryDestroyController::class); +Route::get('/{repository}', '\\' . RepositoryIndexController::class); +Route::post('/{repository}', '\\' . RepositoryStoreController::class); +Route::get('/{repository}/{repositoryId}', '\\' . RepositoryShowController::class); +Route::patch('/{repository}/{repositoryId}', '\\' . RepositoryUpdateController::class); +Route::put('/{repository}/{repositoryId}', '\\' . RepositoryUpdateController::class); +Route::delete('/{repository}/{repositoryId}', '\\' . RepositoryDestroyController::class); + + +// Attach related repository id +Route::post('/{repository}/{repositoryId}/attach/{relatedRepository}', '\\' . RepositoryAttachController::class); diff --git a/src/Http/Controllers/RepositoryAttachController.php b/src/Http/Controllers/RepositoryAttachController.php new file mode 100644 index 000000000..a017d42ad --- /dev/null +++ b/src/Http/Controllers/RepositoryAttachController.php @@ -0,0 +1,65 @@ +findModelOrFail(); + $repository = $request->repository()->allowToUpdate($request); + + return $repository->attach( + $request, $request->repositoryId, + collect(Arr::wrap($request->input($request->relatedRepository))) + ->map(fn($relatedRepositoryId) => $this->initializePivot( + $request, $model->{$request->viaRelationship ?? $request->relatedRepository}(), $relatedRepositoryId + )) + ); + } + + /** + * Initialize a fresh pivot model for the relationship. + * + * @param RestifyRequest $request + * @param $relationship + * @return mixed + * @throws \Binaryk\LaravelRestify\Exceptions\Eloquent\EntityNotFoundException + * @throws \Binaryk\LaravelRestify\Exceptions\UnauthorizedException + */ + protected function initializePivot(RestifyRequest $request, $relationship, $relatedKey) + { + $parentKey = $request->repositoryId; + + $parentKeyName = $relationship->getParentKeyName(); + $relatedKeyName = $relationship->getRelatedKeyName(); + + if ($parentKeyName !== $request->model()->getKeyName()) { + $parentKey = $request->findModelOrFail()->{$parentKeyName}; + } + + if ($relatedKeyName !== ($request->newRelatedRepository()::newModel())->getKeyName()) { + $relatedKey = $request->findRelatedModelOrFail()->{$relatedKeyName}; + } + + ($pivot = $relationship->newPivot())->forceFill([ + $relationship->getForeignPivotKeyName() => $parentKey, + $relationship->getRelatedPivotKeyName() => $relatedKey, + ]); + + if ($relationship->withTimestamps) { + $pivot->forceFill([ + $relationship->createdAt() => new DateTime, + $relationship->updatedAt() => new DateTime, + ]); + } + + return $pivot; + } + +} diff --git a/src/Http/Requests/InteractWithRepositories.php b/src/Http/Requests/InteractWithRepositories.php index 991f2cee9..cf7009273 100644 --- a/src/Http/Requests/InteractWithRepositories.php +++ b/src/Http/Requests/InteractWithRepositories.php @@ -44,7 +44,7 @@ public function repository($key = null): ?Repository ]), 404); } - if (! $repository::authorizedToUseRepository($this)) { + if (!$repository::authorizedToUseRepository($this)) { throw new UnauthorizedException(__('Unauthorized to view repository :name. See "allowRestify" policy.', [ 'name' => $repository, ]), 403); @@ -114,7 +114,7 @@ public function newRepositoryWith($model, $uriKey = null) */ public function newQueryWithoutScopes($uriKey = null) { - if (! $this->isViaRepository()) { + if (!$this->isViaRepository()) { return $this->model($uriKey)->newQueryWithoutScopes(); } @@ -152,15 +152,71 @@ public function findModelQuery($repositoryId = null, $uriKey = null) ); } + public function findModelOrFail($id = null) + { + if ($id) { + return $this->findModelQuery($id)->firstOrFail(); + } + + return once(function () { + return $this->findModelQuery()->firstOrFail(); + }); + } + + public function findRelatedModelOrFail() + { + return once(function () { + return $this->findRelatedQuery()->firstOrFail(); + }); + } + + + public function findRelatedQuery($relatedRepository = null, $relatedRepositoryId = null) + { + return $this->repository($relatedRepository ?? request('relatedRepository'))::newModel() + ->newQueryWithoutScopes() + ->whereKey($relatedRepositoryId ?? request('relatedRepositoryId')); + } + + + protected function findPivot(RestifyRequest $request, $model) + { + $pivot = $model->{$request->relatedRepository}()->getPivotAccessor(); + + return $model->{$request->viaRelationship}() + ->withoutGlobalScopes() + ->lockForUpdate() + ->findOrFail($request->relatedRepositoryId)->{$pivot}; + } + public function viaParentModel() { $parent = $this->repository($this->viaRepository); - return once(fn () => $parent::newModel()->newQueryWithoutScopes()->whereKey($this->viaRepositoryId)->firstOrFail()); + return once(fn() => $parent::newModel()->newQueryWithoutScopes()->whereKey($this->viaRepositoryId)->firstOrFail()); } public function viaQuery() { return $this->viaParentModel()->{$this->viaRelationship}(); } + + /** + * Get a new instance of the "related" resource being requested. + * + * @return Repository + */ + public function newRelatedRepository() + { + $resource = $this->relatedRepository(); + + return new $resource($resource::newModel()); + } + + public function relatedRepository() + { + return Restify::repositoryForKey($this->relatedRepository); + } + + } diff --git a/src/Http/Requests/RepositoryAttachRequest.php b/src/Http/Requests/RepositoryAttachRequest.php new file mode 100644 index 000000000..1586752ae --- /dev/null +++ b/src/Http/Requests/RepositoryAttachRequest.php @@ -0,0 +1,8 @@ +success(); } + public function attach(RestifyRequest $request, $repositoryId, Collection $pivots) + { + DB::transaction(function () use ($request, $pivots) { + return $pivots->map(fn($pivot) => $pivot->forceFill($request->except($request->relatedRepository))) + ->map(fn($pivot) => $pivot->save()); + }); + + return $this->response() + ->data($pivots) + ->created(); + } + public function destroy(RestifyRequest $request, $repositoryId) { $status = DB::transaction(function () { diff --git a/tests/Controllers/RepositoryFilterControllerTest.php b/tests/Controllers/RepositoryFilterControllerTest.php index f5c535799..b4a24c6d7 100644 --- a/tests/Controllers/RepositoryFilterControllerTest.php +++ b/tests/Controllers/RepositoryFilterControllerTest.php @@ -16,7 +16,6 @@ public function test_can_get_available_filters() $response = $this ->withoutExceptionHandling() ->getJson('restify-api/posts/filters') - ->dump() ->assertStatus(200); $this->assertCount(3, $response->json('data')); @@ -39,7 +38,6 @@ public function test_the_boolean_filter_is_applied() $response = $this ->withoutExceptionHandling() ->getJson('restify-api/posts?filters='.$filters) - ->dump() ->assertStatus(200); $this->assertCount(1, $response->json('data')); diff --git a/tests/Controllers/RepositoryPivotControllerTest.php b/tests/Controllers/RepositoryPivotControllerTest.php new file mode 100644 index 000000000..b6262b5ea --- /dev/null +++ b/tests/Controllers/RepositoryPivotControllerTest.php @@ -0,0 +1,66 @@ +mockUsers(2)->first(); + $company = factory(Company::class)->create(); + + $response = $this->postJson('restify-api/companies/' . $company->id . '/attach/users', [ + 'users' => $user->id, + 'is_admin' => true, + ]) + ->assertStatus(201); + + $response->assertJsonFragment([ + 'company_id' => '1', + 'user_id' => $user->id, + 'is_admin' => true, + ]); + } + + public function test_attach_multiple_users_to_a_company() + { + $user = $this->mockUsers(2)->first(); + $company = factory(Company::class)->create(); + $usersFromCompany = $this->getJson('/restify-api/users?viaRepository=companies&viaRepositoryId=1&viaRelationship=users'); + $this->assertCount(0, $usersFromCompany->json('data')); + + $response = $this->postJson('restify-api/companies/' . $company->id . '/attach/users', [ + 'users' => [1, 2], + 'is_admin' => true, + ]) + ->assertStatus(201); + + $response->assertJsonFragment([ + 'company_id' => '1', + 'user_id' => $user->id, + 'is_admin' => true, + ]); + + $usersFromCompany = $this->getJson('/restify-api/users?viaRepository=companies&viaRepositoryId=1&viaRelationship=users'); + $this->assertCount(2, $usersFromCompany->json('data')); + } + + public function test_after_attach_a_user_to_company_number_of_users_increased() + { + $user = $this->mockUsers()->first(); + $company = factory(Company::class)->create(); + + $usersFromCompany = $this->getJson('/restify-api/users?viaRepository=companies&viaRepositoryId=1&viaRelationship=users'); + $this->assertCount(0, $usersFromCompany->json('data')); + + $this->postJson('restify-api/companies/' . $company->id . '/attach/users', [ + 'users' => $user->id, + ]); + + $usersFromCompany = $this->getJson('/restify-api/users?viaRepository=companies&viaRepositoryId=1&viaRelationship=users'); + $this->assertCount(1, $usersFromCompany->json('data')); + } +} diff --git a/tests/Factories/CompanyFactory.php b/tests/Factories/CompanyFactory.php new file mode 100644 index 000000000..e0e43d8f3 --- /dev/null +++ b/tests/Factories/CompanyFactory.php @@ -0,0 +1,21 @@ +define(Company::class, function (Faker $faker) { + return [ + 'name' => $faker->name, + ]; +}); diff --git a/tests/Fixtures/Company/Company.php b/tests/Fixtures/Company/Company.php new file mode 100644 index 000000000..6caf50442 --- /dev/null +++ b/tests/Fixtures/Company/Company.php @@ -0,0 +1,23 @@ +belongsToMany(User::class, 'company_user', 'company_id', 'user_id') + ->withPivot([ + 'is_admin' + ]) + ->withTimestamps(); + } +} diff --git a/tests/Fixtures/Company/CompanyRepository.php b/tests/Fixtures/Company/CompanyRepository.php new file mode 100644 index 000000000..f6b59e693 --- /dev/null +++ b/tests/Fixtures/Company/CompanyRepository.php @@ -0,0 +1,10 @@ +hasMany(Post::class); } + public function companies() + { + return $this->belongsToMany(Company::class, 'company_user', 'user_id', 'company_id')->withPivot([ + 'is_admin' + ])->withTimestamps(); + } + /** * Set default test values. */ diff --git a/tests/IntegrationTest.php b/tests/IntegrationTest.php index c61a275a9..6c083d20e 100644 --- a/tests/IntegrationTest.php +++ b/tests/IntegrationTest.php @@ -5,6 +5,7 @@ use Binaryk\LaravelRestify\Exceptions\RestifyHandler; use Binaryk\LaravelRestify\LaravelRestifyServiceProvider; use Binaryk\LaravelRestify\Restify; +use Binaryk\LaravelRestify\Tests\Fixtures\Company\CompanyRepository; use Binaryk\LaravelRestify\Tests\Fixtures\Post\Post; use Binaryk\LaravelRestify\Tests\Fixtures\Post\PostAuthorizeRepository; use Binaryk\LaravelRestify\Tests\Fixtures\Post\PostMergeableRepository; @@ -178,6 +179,7 @@ public function loadRepositories() Restify::repositories([ UserRepository::class, PostRepository::class, + CompanyRepository::class, PostMergeableRepository::class, PostAuthorizeRepository::class, PostWithUnauthorizedFieldsRepository::class, diff --git a/tests/Migrations/2019_12_22_000005_create_Company_user__table.php b/tests/Migrations/2019_12_22_000005_create_Company_user__table.php new file mode 100644 index 000000000..84575f583 --- /dev/null +++ b/tests/Migrations/2019_12_22_000005_create_Company_user__table.php @@ -0,0 +1,33 @@ +foreignId('company_id')->constrained('companies'); + $table->foreignId('user_id')->constrained('users'); + $table->boolean('is_admin')->default(false); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('company_user'); + } +} diff --git a/tests/Migrations/2019_12_22_000005_create_companies_table.php b/tests/Migrations/2019_12_22_000005_create_companies_table.php new file mode 100644 index 000000000..7c2c2886b --- /dev/null +++ b/tests/Migrations/2019_12_22_000005_create_companies_table.php @@ -0,0 +1,32 @@ +id(); + $table->string('name'); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('companies'); + } +} From ffadb5fc00ba650ead942f57f6e2c8ddef591b8f Mon Sep 17 00:00:00 2001 From: Lupacescu Eduard Date: Wed, 20 May 2020 00:30:08 +0300 Subject: [PATCH 2/2] Apply fixes from StyleCI (#181) --- routes/api.php | 21 +++++++++---------- .../RepositoryAttachController.php | 3 +-- .../Requests/InteractWithRepositories.php | 10 +++------ src/Http/Requests/RepositoryAttachRequest.php | 1 - src/Repositories/Repository.php | 5 ++--- .../RepositoryPivotControllerTest.php | 6 +++--- tests/Fixtures/Company/Company.php | 2 +- tests/Fixtures/User/User.php | 2 +- 8 files changed, 21 insertions(+), 29 deletions(-) diff --git a/routes/api.php b/routes/api.php index ca1fc4eb6..fa01dfe90 100644 --- a/routes/api.php +++ b/routes/api.php @@ -1,29 +1,28 @@ attach( $request, $request->repositoryId, collect(Arr::wrap($request->input($request->relatedRepository))) - ->map(fn($relatedRepositoryId) => $this->initializePivot( + ->map(fn ($relatedRepositoryId) => $this->initializePivot( $request, $model->{$request->viaRelationship ?? $request->relatedRepository}(), $relatedRepositoryId )) ); @@ -61,5 +61,4 @@ protected function initializePivot(RestifyRequest $request, $relationship, $rela return $pivot; } - } diff --git a/src/Http/Requests/InteractWithRepositories.php b/src/Http/Requests/InteractWithRepositories.php index cf7009273..7d2030908 100644 --- a/src/Http/Requests/InteractWithRepositories.php +++ b/src/Http/Requests/InteractWithRepositories.php @@ -44,7 +44,7 @@ public function repository($key = null): ?Repository ]), 404); } - if (!$repository::authorizedToUseRepository($this)) { + if (! $repository::authorizedToUseRepository($this)) { throw new UnauthorizedException(__('Unauthorized to view repository :name. See "allowRestify" policy.', [ 'name' => $repository, ]), 403); @@ -114,7 +114,7 @@ public function newRepositoryWith($model, $uriKey = null) */ public function newQueryWithoutScopes($uriKey = null) { - if (!$this->isViaRepository()) { + if (! $this->isViaRepository()) { return $this->model($uriKey)->newQueryWithoutScopes(); } @@ -170,7 +170,6 @@ public function findRelatedModelOrFail() }); } - public function findRelatedQuery($relatedRepository = null, $relatedRepositoryId = null) { return $this->repository($relatedRepository ?? request('relatedRepository'))::newModel() @@ -178,7 +177,6 @@ public function findRelatedQuery($relatedRepository = null, $relatedRepositoryId ->whereKey($relatedRepositoryId ?? request('relatedRepositoryId')); } - protected function findPivot(RestifyRequest $request, $model) { $pivot = $model->{$request->relatedRepository}()->getPivotAccessor(); @@ -193,7 +191,7 @@ public function viaParentModel() { $parent = $this->repository($this->viaRepository); - return once(fn() => $parent::newModel()->newQueryWithoutScopes()->whereKey($this->viaRepositoryId)->firstOrFail()); + return once(fn () => $parent::newModel()->newQueryWithoutScopes()->whereKey($this->viaRepositoryId)->firstOrFail()); } public function viaQuery() @@ -217,6 +215,4 @@ public function relatedRepository() { return Restify::repositoryForKey($this->relatedRepository); } - - } diff --git a/src/Http/Requests/RepositoryAttachRequest.php b/src/Http/Requests/RepositoryAttachRequest.php index 1586752ae..972af0822 100644 --- a/src/Http/Requests/RepositoryAttachRequest.php +++ b/src/Http/Requests/RepositoryAttachRequest.php @@ -4,5 +4,4 @@ class RepositoryAttachRequest extends RestifyRequest { - } diff --git a/src/Repositories/Repository.php b/src/Repositories/Repository.php index 097726cb3..da83f4911 100644 --- a/src/Repositories/Repository.php +++ b/src/Repositories/Repository.php @@ -8,7 +8,6 @@ use Binaryk\LaravelRestify\Fields\Field; use Binaryk\LaravelRestify\Fields\FieldCollection; use Binaryk\LaravelRestify\Filter; -use Binaryk\LaravelRestify\Http\Requests\RepositoryAttachRequest; use Binaryk\LaravelRestify\Http\Requests\RestifyRequest; use Binaryk\LaravelRestify\Restify; use Binaryk\LaravelRestify\Services\Search\RepositorySearchService; @@ -578,8 +577,8 @@ public function update(RestifyRequest $request, $repositoryId) public function attach(RestifyRequest $request, $repositoryId, Collection $pivots) { DB::transaction(function () use ($request, $pivots) { - return $pivots->map(fn($pivot) => $pivot->forceFill($request->except($request->relatedRepository))) - ->map(fn($pivot) => $pivot->save()); + return $pivots->map(fn ($pivot) => $pivot->forceFill($request->except($request->relatedRepository))) + ->map(fn ($pivot) => $pivot->save()); }); return $this->response() diff --git a/tests/Controllers/RepositoryPivotControllerTest.php b/tests/Controllers/RepositoryPivotControllerTest.php index b6262b5ea..997065ad0 100644 --- a/tests/Controllers/RepositoryPivotControllerTest.php +++ b/tests/Controllers/RepositoryPivotControllerTest.php @@ -12,7 +12,7 @@ public function test_attach_a_user_to_a_company() $user = $this->mockUsers(2)->first(); $company = factory(Company::class)->create(); - $response = $this->postJson('restify-api/companies/' . $company->id . '/attach/users', [ + $response = $this->postJson('restify-api/companies/'.$company->id.'/attach/users', [ 'users' => $user->id, 'is_admin' => true, ]) @@ -32,7 +32,7 @@ public function test_attach_multiple_users_to_a_company() $usersFromCompany = $this->getJson('/restify-api/users?viaRepository=companies&viaRepositoryId=1&viaRelationship=users'); $this->assertCount(0, $usersFromCompany->json('data')); - $response = $this->postJson('restify-api/companies/' . $company->id . '/attach/users', [ + $response = $this->postJson('restify-api/companies/'.$company->id.'/attach/users', [ 'users' => [1, 2], 'is_admin' => true, ]) @@ -56,7 +56,7 @@ public function test_after_attach_a_user_to_company_number_of_users_increased() $usersFromCompany = $this->getJson('/restify-api/users?viaRepository=companies&viaRepositoryId=1&viaRelationship=users'); $this->assertCount(0, $usersFromCompany->json('data')); - $this->postJson('restify-api/companies/' . $company->id . '/attach/users', [ + $this->postJson('restify-api/companies/'.$company->id.'/attach/users', [ 'users' => $user->id, ]); diff --git a/tests/Fixtures/Company/Company.php b/tests/Fixtures/Company/Company.php index 6caf50442..d1ed1dc86 100644 --- a/tests/Fixtures/Company/Company.php +++ b/tests/Fixtures/Company/Company.php @@ -16,7 +16,7 @@ public function users() { return $this->belongsToMany(User::class, 'company_user', 'company_id', 'user_id') ->withPivot([ - 'is_admin' + 'is_admin', ]) ->withTimestamps(); } diff --git a/tests/Fixtures/User/User.php b/tests/Fixtures/User/User.php index 39fea7f61..7cab46a0e 100644 --- a/tests/Fixtures/User/User.php +++ b/tests/Fixtures/User/User.php @@ -85,7 +85,7 @@ public function posts() public function companies() { return $this->belongsToMany(Company::class, 'company_user', 'user_id', 'company_id')->withPivot([ - 'is_admin' + 'is_admin', ])->withTimestamps(); }