From 2c6b0738fc1d979f27f1bb50f87b51bdd314fe29 Mon Sep 17 00:00:00 2001 From: Marius Date: Tue, 3 Dec 2024 10:41:02 +0200 Subject: [PATCH] introduce forceReplace and forceOffsetUnset macros to Request --- .../Controllers/ResourceControllerTrait.php | 4 +- src/Providers/CrudProvider.php | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/src/Http/Controllers/ResourceControllerTrait.php b/src/Http/Controllers/ResourceControllerTrait.php index 7a70473..e83bf27 100644 --- a/src/Http/Controllers/ResourceControllerTrait.php +++ b/src/Http/Controllers/ResourceControllerTrait.php @@ -149,7 +149,7 @@ public function update(string $identifier, Request $request): JsonResponse $this->resourceService->getIgnoreExternalUpdateFor() ))); /** $request can contain also files so, overwrite this function to handle them */ - $request->replace($model->getDirty()); + $request->forceReplace($model->getDirty()); return GeneralHelper::app(JsonResponse::class, [ 'data' => $this->resourceService->update($identifier, $this->validateUpdateRequest($request)) @@ -161,7 +161,7 @@ public function update(string $identifier, Request $request): JsonResponse throw $e; } - $request->replace($all); + $request->forceReplace($all); return $this->create($request); } diff --git a/src/Providers/CrudProvider.php b/src/Providers/CrudProvider.php index 8cae9e8..5a5addd 100644 --- a/src/Providers/CrudProvider.php +++ b/src/Providers/CrudProvider.php @@ -4,6 +4,7 @@ use Illuminate\Database\Eloquent\Builder as EloquentBuilder; use Illuminate\Database\Eloquent\Model; +use Illuminate\Http\Request; use Illuminate\Support\ServiceProvider; class CrudProvider extends ServiceProvider @@ -37,5 +38,41 @@ function (...$arguments): Model { return $model::query()->useWritePdo()->where($model->getPrimaryKeyFilter())->firstOrFail(); } ); + + Request::macro('forceOffsetUnset', function (string $offset): Request { + /** @var Request $this */ + + if ($this->json()->has($offset) > 0) { + $this->json()->remove($offset); + } + + if ($this->query->has($offset)) { + $this->query->remove($offset); + } + + if ($this->request->has($offset)) { + $this->request->remove($offset); + } + + return $this; + }); + + Request::macro('forceReplace', function (array $data): Request { + /** @var Request $this */ + + if ($this->json()->count() > 0) { + $this->json()->replace($data); + } + + if ($this->query->count() > 0) { + $this->query->replace($data); + } + + if ($this->request->count() > 0) { + $this->request->replace($data); + } + + return $this; + }); } }