From 0266a89ae31410ff1cf5c4d261a8fe165b5eaa91 Mon Sep 17 00:00:00 2001 From: tracer Date: Fri, 28 Oct 2022 17:01:29 +0200 Subject: [PATCH] added error handling to ajax calls --- src/Controller/AddressBookController.php | 54 ++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 4 deletions(-) diff --git a/src/Controller/AddressBookController.php b/src/Controller/AddressBookController.php index a88ed69..9d3a920 100644 --- a/src/Controller/AddressBookController.php +++ b/src/Controller/AddressBookController.php @@ -11,6 +11,7 @@ namespace App\Controller; use App\Entity\User; use App\Entity\AddressBookEntry; +use App\Enums\StatusCode; use App\Enums\UserAuth; use App\Service\Router; use App\Service\Template; @@ -71,16 +72,61 @@ class AddressBookController { $_POST = json_decode(json: file_get_contents(filename: "php://input"), associative: true); - $address = new AddressBookEntry(owner: $_POST['owner'], first: $_POST['first'], last: $_POST['last'], street: $_POST['street'], zip: $_POST['zip'], city: $_POST['city'], phone: $_POST['phone'], id: $_POST['id']); - $this->addressRepository->update(address: $address); + if (empty($_POST)) { + $this->template->renderJson(results: [ + 'status' => 400, + 'message' => 'BAD REQUEST' + ]); + } + + if ($address = new AddressBookEntry(owner: $_POST['owner'], first: $_POST['first'], last: $_POST['last'], street: $_POST['street'], zip: $_POST['zip'], city: $_POST['city'], phone: $_POST['phone'], id: $_POST['id'])) { + if ($this->addressRepository->update(address: $address)) { + $status = 200; + $message = 'OK'; + } else { + $status = 400; + $message = 'BAD_REQUEST'; + } + } else { + $status = 400; + $message = "BAD REQUEST"; + } + + $this->template->renderJson(results: [ + 'status' => $status, + 'message' => $message + ]); } public function deleteAddress(): void { - echo "in del"; $_POST = json_decode(json: file_get_contents(filename: "php://input"), associative: true); + + if (empty($_POST)) { + $this->template->renderJson(results: [ + 'status' => 400, + 'message' => 'BAD REQUEST' + ]); + } + if ($address = $this->addressRepository->findByID(id: $_POST['id'])) { - $this->addressRepository->delete(addressBookEntry: $address); + if ($this->addressRepository->delete(addressBookEntry: $address)) { + $this->template->renderJson(results: [ + 'status' => 200, + 'message' => 'OK' + ]); + } else { + $this->template->renderJson(results: [ + 'status' => 400, + 'message' => 'BAD REQUEST' + ]); + + } + } else { + $this->template->renderJson(results: [ + 'status' => 400, + 'message' => 'BAD REQUEST' + ]); } }