From 7695ec364ffea60bb6860a0257f1f4b4af9ceabe Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Thu, 1 Jul 2021 16:47:01 +0200 Subject: [PATCH 01/23] Created docker env --- .docker/docker-compose.yml | 39 +++++++++++++++++++++ .docker/dumps/orig_db.sql | 70 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 109 insertions(+) create mode 100755 .docker/docker-compose.yml create mode 100644 .docker/dumps/orig_db.sql diff --git a/.docker/docker-compose.yml b/.docker/docker-compose.yml new file mode 100755 index 0000000..5c76276 --- /dev/null +++ b/.docker/docker-compose.yml @@ -0,0 +1,39 @@ +version: '3.1' +services: + apache2: + container_name: apache2_php + image: webdevops/php-apache:ubuntu-18.04 + ports: + - 80:80 + - 443:443 + volumes: + - ../:/app/ + depends_on: + - mariadb + links: + - mariadb + restart: always + networks: + zssn_net: + ipv4_address: 12.7.0.4 + mariadb: + image: mariadb + restart: always + environment: + MYSQL_DATABASE: 'zssn' + MYSQL_ROOT_PASSWORD: 'root' + ports: + - '3307:3306' + expose: + - '3307' + volumes: + - ./db:/var/lib/mysql + networks: + zssn_net: + ipv4_address: 12.7.0.5 +networks: + zssn_net: + driver: bridge + ipam: + config: + - subnet: 12.7.0.0/16 \ No newline at end of file diff --git a/.docker/dumps/orig_db.sql b/.docker/dumps/orig_db.sql new file mode 100644 index 0000000..a8eb3a5 --- /dev/null +++ b/.docker/dumps/orig_db.sql @@ -0,0 +1,70 @@ +/* +SQLyog Ultimate v13.1.2 (64 bit) +MySQL - 10.5.9-MariaDB-1:10.5.9+maria~focal : Database - zssn +********************************************************************* +*/ + +/*!40101 SET NAMES utf8 */; + +/*!40101 SET SQL_MODE=''*/; + +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/`zssn` /*!40100 DEFAULT CHARACTER SET utf8mb4 */; + +USE `zssn`; + +/*Table structure for table `inventory` */ + +DROP TABLE IF EXISTS `inventory`; + +CREATE TABLE `inventory` ( + `id_survivor` int(11) NOT NULL AUTO_INCREMENT, + `item` text DEFAULT NULL, + `qty` int(11) DEFAULT NULL, + PRIMARY KEY (`id_survivor`), + CONSTRAINT `id_survivor` FOREIGN KEY (`id_survivor`) REFERENCES `survivors` (`id_survivor`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +/*Data for the table `inventory` */ + +/*Table structure for table `survivors` */ + +DROP TABLE IF EXISTS `survivors`; + +CREATE TABLE `survivors` ( + `id_survivor` int(11) NOT NULL AUTO_INCREMENT, + `name` text DEFAULT NULL, + `age` int(11) DEFAULT NULL, + `gender` text DEFAULT NULL, + `location` text DEFAULT NULL, + `infected` smallint(6) DEFAULT NULL, + `reported` smallint(6) DEFAULT NULL, + PRIMARY KEY (`id_survivor`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +/*Data for the table `survivors` */ + +/*Table structure for table `trade_points` */ + +DROP TABLE IF EXISTS `trade_points`; + +CREATE TABLE `trade_points` ( + `item` text DEFAULT NULL, + `points` int(11) DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +/*Data for the table `trade_points` */ + +insert into `trade_points`(`item`,`points`) values +('Water',4), +('Food',3), +('Medication',2), +('Ammunition',1); + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; From dbdd0e7b13aa51d0d027546a5d5616875ad5d6c9 Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Thu, 1 Jul 2021 16:47:09 +0200 Subject: [PATCH 02/23] add .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c148e02 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/.docker/db \ No newline at end of file From ac4f947ba3b37824a56465ce51d4d7a44730c0a7 Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Wed, 7 Jul 2021 15:11:05 +0200 Subject: [PATCH 03/23] Created docker env --- .env.docker | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .env.docker diff --git a/.env.docker b/.env.docker new file mode 100644 index 0000000..def4cf4 --- /dev/null +++ b/.env.docker @@ -0,0 +1,5 @@ +DB_HOST=mariadb +DB_PORT=3306 +DB_DATABASE=zssn +DB_USERNAME=root +DB_PASSWORD=root \ No newline at end of file From d4ed7b768b6a758c8c32e312df39fc131bb1657d Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Wed, 7 Jul 2021 15:11:58 +0200 Subject: [PATCH 04/23] Added api.php and created index.php --- api.php | 3 +++ index.php | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 api.php create mode 100644 index.php diff --git a/api.php b/api.php new file mode 100644 index 0000000..1023d03 --- /dev/null +++ b/api.php @@ -0,0 +1,3 @@ + $value) { + putenv($key . '=' . $value); +} + +$db = new DatabaseConnector; +$dbConnection = $db->getConnection(); + +$requestMethod = $_SERVER["REQUEST_METHOD"]; +$apiController = new ApiController($requestMethod, $uri); From 6ef521703808d1e0b6e071cc40250bce768632ad Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Wed, 7 Jul 2021 15:13:29 +0200 Subject: [PATCH 05/23] Created entities connection to DB --- src/DatabaseManager/DatabaseConnector.php | 32 +++++ src/DatabaseManager/InventoryConnection.php | 110 ++++++++++++++++ src/DatabaseManager/SurvivorConnection.php | 118 ++++++++++++++++++ src/DatabaseManager/TradePointsConnection.php | 58 +++++++++ 4 files changed, 318 insertions(+) create mode 100644 src/DatabaseManager/DatabaseConnector.php create mode 100644 src/DatabaseManager/InventoryConnection.php create mode 100644 src/DatabaseManager/SurvivorConnection.php create mode 100644 src/DatabaseManager/TradePointsConnection.php diff --git a/src/DatabaseManager/DatabaseConnector.php b/src/DatabaseManager/DatabaseConnector.php new file mode 100644 index 0000000..29649de --- /dev/null +++ b/src/DatabaseManager/DatabaseConnector.php @@ -0,0 +1,32 @@ +dbConnection = new \PDO( + "mysql:host=$host;port=$port;charset=utf8mb4;dbname=$db", + $user, + $pass + ); + } catch (\PDOException $e) { + exit($e->getMessage()); + } + } + + public function getConnection() + { + return $this->dbConnection; + } +} diff --git a/src/DatabaseManager/InventoryConnection.php b/src/DatabaseManager/InventoryConnection.php new file mode 100644 index 0000000..22c6915 --- /dev/null +++ b/src/DatabaseManager/InventoryConnection.php @@ -0,0 +1,110 @@ +db = $db; + } + + public function selectAll() + { + $stmt = " + SELECT + item, qty + FROM + $this->tbName + "; + + try { + $stmt = $this->db->prepare($stmt); + $stmt->execute(); + + return $stmt->fetchAll(\PDO::FETCH_ASSOC); + } catch (\PDOException $e) { + exit($e->getMessage()); + } + } + + public function selectBySurvivorId(array $input) + { + $stmt = " + SELECT + item, qty + FROM + $this->tbName + WHERE id_survivor = :id_survivor; + "; + try { + $stmt = $this->db->prepare($stmt); + + $stmt->execute( + [ + 'id_survivor' => $input['id_survivor'], + 'item' => $input['item'], + 'qty' => $input['qty'], + ] + ); + + return $stmt->fetchAll(\PDO::FETCH_ASSOC); + } catch (\PDOException $e) { + exit($e->getMessage()); + } + } + + public function insert(array $input) + { + $stmt = " + INSERT INTO $this->tbName (id_survivor, item, qty) + VALUES (:id_survivor, :item, :qty); + "; + try { + $stmt = $this->db->prepare($stmt); + $stmt->execute( + [ + 'id_survivor' => $input['id_survivor'], + 'item' => $input['item'], + 'qty' => $input['qty'], + ] + ); + + var_dump($stmt); + + } catch (\PDOException $e) { + exit($e->getMessage()); + } + } + + public function update($id_survivor, array $input) + { + $stmt = " + UPDATE $this->tbName + SET + id_survivor = :id_survivor + item = :item + qty = :qty + WHERE + id_survivor = :id_survivor; + "; + try { + $stmt = $this->db->prepare($stmt); + $stmt->execute( + [ + 'id_survivor' => $input['id_survivor'], + 'item' => $input['item'], + 'qty' => $input['qty'], + ] + ); + + return $stmt->rowCount(); + } catch (\PDOException $e) { + exit($e->getMessage()); + } + } + +} diff --git a/src/DatabaseManager/SurvivorConnection.php b/src/DatabaseManager/SurvivorConnection.php new file mode 100644 index 0000000..a45bced --- /dev/null +++ b/src/DatabaseManager/SurvivorConnection.php @@ -0,0 +1,118 @@ +db = $db; + } + + public function selectAll() + { + $stmt = " + SELECT + name, age, gender, location, infected, reported + FROM + $this->tbName + "; + + try { + $stmt = $this->db->prepare($stmt); + $stmt->execute(); + + return $stmt->fetchAll(\PDO::FETCH_ASSOC); + } catch (\PDOException $e) { + exit($e->getMessage()); + } + } + + public function selectByName($name) + { + $stmt = " + SELECT + id_survivor, name, age, gender, location, infected, reported + FROM + $this->tbName + WHERE + name = :name; + "; + + try { + $stmt = $this->db->prepare($stmt); + + $stmt->execute( + [ + 'name' => $name + ] + ); + return $stmt->fetchAll(\PDO::FETCH_ASSOC); + } catch (\PDOException $e) { + exit($e->getMessage()); + } + } + + public function insert(array $input) + { + $stmt = " + INSERT INTO $this->tbName (name, age, gender, location, infected, reported) + VALUES (:name, :age, :gender, :location, :infected, :reported); + "; + try { + $stmt = $this->db->prepare($stmt); + $stmt->execute( + [ + 'name' => $input['name'], + 'age' => $input['age'], + 'gender' => $input['gender'], + 'location' => $input['location'], + 'infected' => $input['infected'], + 'reported' => $input['reported'], + ] + ); + + return $stmt->rowCount(); + + } catch (\PDOException $e) { + exit($e->getMessage()); + } + } + + public function update($name, array $input) + { + $stmt = " + UPDATE $this->tbName + SET + name = :name + age = :age + gender = :gender + location = :location + infected = :infected + reported = :reported + WHERE + name = :name; + "; + try { + $stmt = $this->db->prepare($stmt); + $stmt->execute( + [ + 'name' => $input['name'], + 'age' => $input['age'], + 'gender' => $input['gender'], + 'location' => $input['location'], + 'infected' => $input['infected'], + 'reported' => $input['reported'], + ] + ); + + return $stmt->rowCount(); + } catch (\PDOException $e) { + exit($e->getMessage()); + } + } + +} diff --git a/src/DatabaseManager/TradePointsConnection.php b/src/DatabaseManager/TradePointsConnection.php new file mode 100644 index 0000000..7717504 --- /dev/null +++ b/src/DatabaseManager/TradePointsConnection.php @@ -0,0 +1,58 @@ +db = $db; + } + + public function selectAll() + { + $stmt = " + SELECT + item, points + FROM + $this->tbName + "; + + try { + $stmt = $this->db->prepare($stmt); + $stmt->execute(); + + return $stmt->fetchAll(\PDO::FETCH_ASSOC); + } catch (\PDOException $e) { + exit($e->getMessage()); + } + } + + public function selectByItem($item) + { + $stmt = " + SELECT + item, points + FROM + $this->tbName + WHERE + item = :item; + "; + + try { + $stmt = $this->db->prepare($stmt); + $stmt->execute( + [ + 'item' => $item + ] + ); + + return $stmt->fetchAll(\PDO::FETCH_ASSOC); + } catch (\PDOException $e) { + exit($e->getMessage()); + } + } +} From 4c93dc7d72ce8bcb767bb1e53f7a090aff9c952c Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Wed, 7 Jul 2021 15:14:01 +0200 Subject: [PATCH 06/23] Creating Entities helper interface --- src/EntityDbHelper/DbHelper.php | 20 +++++++ .../DbHelper/InventoryHelper.php | 58 +++++++++++++++++++ .../DbHelper/SurvivorHelper.php | 55 ++++++++++++++++++ 3 files changed, 133 insertions(+) create mode 100644 src/EntityDbHelper/DbHelper.php create mode 100644 src/EntityDbHelper/DbHelper/InventoryHelper.php create mode 100644 src/EntityDbHelper/DbHelper/SurvivorHelper.php diff --git a/src/EntityDbHelper/DbHelper.php b/src/EntityDbHelper/DbHelper.php new file mode 100644 index 0000000..4b4112e --- /dev/null +++ b/src/EntityDbHelper/DbHelper.php @@ -0,0 +1,20 @@ +db = $dbClass->getConnection(); + } +} \ No newline at end of file diff --git a/src/EntityDbHelper/DbHelper/InventoryHelper.php b/src/EntityDbHelper/DbHelper/InventoryHelper.php new file mode 100644 index 0000000..c41bcd2 --- /dev/null +++ b/src/EntityDbHelper/DbHelper/InventoryHelper.php @@ -0,0 +1,58 @@ +inventoryConnection = new InventoryConnection($this->db); + } + + /** + * @return mixed + */ + public function getAllInventories() + { + return $this->inventoryConnection->selectAll(); + } + + /** + * @param $survivorId + * @return mixed + */ + public function getInventoryBySurvivorId($inventory) + { + return $this->inventoryConnection->selectBySurvivorId($inventory)[0]; + } + + /** + * @param $inventory + * @return mixed + */ + public function addNewInventory($inventory) + { + + $existInventory = $this->getInventoryBySurvivorId($inventory); + if($existInventory){ + header('HTTP/1.1 400 BAD REQUEST'); + echo "Inventory already exists, pick another survivor name"; + exit(); + } + + foreach ($inventory as $item){ + $this->inventoryConnection->insert($item); + } + } + +} + diff --git a/src/EntityDbHelper/DbHelper/SurvivorHelper.php b/src/EntityDbHelper/DbHelper/SurvivorHelper.php new file mode 100644 index 0000000..059cc86 --- /dev/null +++ b/src/EntityDbHelper/DbHelper/SurvivorHelper.php @@ -0,0 +1,55 @@ +survivorConnection = new SurvivorConnection($this->db); + } + + /** + * @return mixed + */ + public function getAllSurvivors() + { + return $this->survivorConnection->selectAll(); + } + + /** + * @param $name + * @return mixed + */ + public function getSurvivorByName($name) + { + return $this->survivorConnection->selectByName($name)[0]; + } + + /** + * @param $survivor + * @return mixed + */ + public function addNewSurvivor($survivor) + { + + $existSurvivor = $this->getSurvivorByName($survivor['name']); + if($existSurvivor){ + header('HTTP/1.1 400 BAD REQUEST'); + echo "Survivor already exists, pick another name"; + exit(); + } + return $this->survivorConnection->insert($survivor); + } + +} + From c9388bcbf7a8a644bf300e16be7bedb722a73504 Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Wed, 7 Jul 2021 15:14:27 +0200 Subject: [PATCH 07/23] Creating Api Controller --- src/ApiController/ApiController.php | 203 ++++++++++++++++++++++++++++ 1 file changed, 203 insertions(+) create mode 100644 src/ApiController/ApiController.php diff --git a/src/ApiController/ApiController.php b/src/ApiController/ApiController.php new file mode 100644 index 0000000..ede313e --- /dev/null +++ b/src/ApiController/ApiController.php @@ -0,0 +1,203 @@ +requestMethod = $requestMethod; + $this->uriPath = $uriPath; + $this->processRequest(); + } + + public function processRequest() + { + switch ($this->requestMethod) { + case 'GET': + $this->_getActionCall(); + break; + case 'POST': + $this->_addSurvivor(); + break; + default: + break; + } + } + + private function _getActionCall() + { + if (!$this->uriPath[2]) { + $this->runBadRequest(); + } + + $this->_setParamsDataFromUriQuery(); + $result = []; + switch ($this->uriPath[2]) { + case 'getInfectedPercentage': + $result = $this->_getInfectedPercentage(); + break; + case 'getNonInfectedPercentage': + $result = $this->_getNonInfectedPercentage(); + break; + case 'getAverageAllResources': + $this->_getAverageAllResources(); + break; + case 'getLostPoints': + $this->_getLostPoints(); + break; + default: + $this->runBadRequest(); + break; + } + + header($result['status_code_header']); + + echo $result['body']; + } + + private function _getInfectedPercentage() + { + $infected = 0; + $survivorsQty = 0; + $this->survivor = new SurvivorHelper(); + $survivors = $this->survivor->getAllSurvivors(); + + foreach ($survivors as $survivor) { + $survivorsQty++; + foreach ($survivor as $key => $value) { + if ($key !== 'infected') { + continue; + } + + if ($value == 0) { + continue; + } + + $infected++; + } + } + $percentage = intval($this->getPercentage($infected, $survivorsQty)); + + $message = "Infected Percentage = " . $percentage . "%"; + + $response['status_code_header'] = self::STATUS_OK; + $response['infected'] = $infected; + $response['survivorsQty'] = $survivorsQty; + $response['percentage'] = $percentage; + + $response['body'] = json_encode($message); + + return $response; + } + + private function _getNonInfectedPercentage() + { + $infectedResponse = $this->_getInfectedPercentage(); + $percentage = $infectedResponse['percentage']; + $nonInfectedPercentage = intval(100 - $percentage); + $message = "Non Infected Percentage = " . $nonInfectedPercentage . "%"; + $response['status_code_header'] = self::STATUS_OK; + $response['nonInfectedPercentage'] = $nonInfectedPercentage; + + $response['body'] = json_encode($message); + + return $response; + } + + private function _getAverageAllResources() + { + } + + private function _getLostPoints() + { + } + + private function _addSurvivor() + { + $survivorData = $this->_getSurvivorDataFromPost(); + $this->survivor = new SurvivorHelper(); + $this->survivor->addNewSurvivor($survivorData); + + $this->inventory = new InventoryHelper(); + $survivorId = $this->survivor->getSurvivorByName($survivorData['name'])['id_survivor']; + $inventoryData = $this->_getInventoryDataFromPost($survivorId); + + $this->inventory->addNewInventory($inventoryData); + } + + private function _getSurvivorDataFromPost() + { + $survivorData = []; + if (!$_POST['name']) { + $this->runBadRequest(); + } + $survivorData['name'] = $_POST['name']; + $survivorData['age'] = $_POST['age']; + $survivorData['gender'] = $_POST['gender']; + $survivorData['location'] = $_POST['location']; + $survivorData['infected'] = 0; + $survivorData['reported'] = 0; + + return $survivorData; + } + + private function _getInventoryDataFromPost($survivorId) + { + $inventoryData = []; + array_push($inventoryData, + ['id_survivor' => $survivorId, 'item' => 'water', 'qty' => $_POST['water']], + ['id_survivor' => $survivorId, 'item' => 'food', 'qty' => $_POST['food']], + ['id_survivor' => $survivorId, 'item' => 'medication', 'qty' => $_POST['medication']], + ['id_survivor' => $survivorId, 'item' => 'ammunition', 'qty' => $_POST['ammunition']] + ); + + return $inventoryData; + } + + private function _setParamsDataFromUriQuery() + { + $this->uriQuery = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY); + if (!$this->uriQuery) { + $this->uriParams = null; + + return; + } + $params = []; + parse_str($this->uriQuery, $params); + + $this->uriParams = $params; + } + + /** + * @param $a + * @param $b + * @return float|int + * + * $a : $b = result : 100 + */ + public function getPercentage($a, $b) + { + return ($a / $b) * 100; + } + + public function runBadRequest() + { + header(self::STATUS_ERROR); + echo "Bad Request"; + exit(); + } + +} \ No newline at end of file From ebb07baa88d38573aae9e0df9400d586fcdb8ade Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Wed, 7 Jul 2021 15:14:42 +0200 Subject: [PATCH 08/23] Added composer autoload --- composer.json | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 composer.json diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..fff29b3 --- /dev/null +++ b/composer.json @@ -0,0 +1,7 @@ +{ + "autoload": { + "psr-4": { + "Src\\": "src/" + } + } +} \ No newline at end of file From b53f227f35b20b5bb52497f2a0b820521660c6e0 Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Thu, 8 Jul 2021 10:42:04 +0200 Subject: [PATCH 09/23] Fix SurvivorHelper and Add TradePointsHelper --- .../DbHelper/SurvivorHelper.php | 12 ++++++-- .../DbHelper/TradePointsHelper.php | 28 +++++++++++++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) create mode 100644 src/EntityDbHelper/DbHelper/TradePointsHelper.php diff --git a/src/EntityDbHelper/DbHelper/SurvivorHelper.php b/src/EntityDbHelper/DbHelper/SurvivorHelper.php index 059cc86..a8effa6 100644 --- a/src/EntityDbHelper/DbHelper/SurvivorHelper.php +++ b/src/EntityDbHelper/DbHelper/SurvivorHelper.php @@ -1,4 +1,5 @@ getSurvivorByName($survivor['name']); - if($existSurvivor){ + if ($existSurvivor) { header('HTTP/1.1 400 BAD REQUEST'); echo "Survivor already exists, pick another name"; exit(); } - return $this->survivorConnection->insert($survivor); + + $this->survivorConnection->insert($survivor); + } + + public function updateSurvivor($survivor) + { + $this->survivorConnection->update($survivor); } } diff --git a/src/EntityDbHelper/DbHelper/TradePointsHelper.php b/src/EntityDbHelper/DbHelper/TradePointsHelper.php new file mode 100644 index 0000000..81b4c1c --- /dev/null +++ b/src/EntityDbHelper/DbHelper/TradePointsHelper.php @@ -0,0 +1,28 @@ +tradePointsConnection = new TradePointsConnection($this->db); + } + + /** + * @return mixed + */ + public function getAllTradePoints() + { + return $this->tradePointsConnection->selectAll(); + } +} \ No newline at end of file From abfbc6706e8f81fff972b6bceefec0bd6da1bce5 Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Thu, 8 Jul 2021 10:42:32 +0200 Subject: [PATCH 10/23] Fix Survivor and Inventory Connection --- src/DatabaseManager/InventoryConnection.php | 2 -- src/DatabaseManager/SurvivorConnection.php | 13 ++++++------- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/src/DatabaseManager/InventoryConnection.php b/src/DatabaseManager/InventoryConnection.php index 22c6915..13e06dc 100644 --- a/src/DatabaseManager/InventoryConnection.php +++ b/src/DatabaseManager/InventoryConnection.php @@ -73,8 +73,6 @@ public function insert(array $input) ] ); - var_dump($stmt); - } catch (\PDOException $e) { exit($e->getMessage()); } diff --git a/src/DatabaseManager/SurvivorConnection.php b/src/DatabaseManager/SurvivorConnection.php index a45bced..206b409 100644 --- a/src/DatabaseManager/SurvivorConnection.php +++ b/src/DatabaseManager/SurvivorConnection.php @@ -82,16 +82,16 @@ public function insert(array $input) } } - public function update($name, array $input) + public function update(array $input) { $stmt = " UPDATE $this->tbName SET - name = :name - age = :age - gender = :gender - location = :location - infected = :infected + name = :name, + age = :age, + gender = :gender, + location = :location, + infected = :infected, reported = :reported WHERE name = :name; @@ -109,7 +109,6 @@ public function update($name, array $input) ] ); - return $stmt->rowCount(); } catch (\PDOException $e) { exit($e->getMessage()); } From ce36df517ffcda7ad30b0f0451a34a9b0d52a7a6 Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Thu, 8 Jul 2021 10:43:36 +0200 Subject: [PATCH 11/23] Added action calls: _getInfectedPercentage _getNonInfectedPercentage _addSurvivor _updateSurvivor --- src/ApiController/ApiController.php | 120 +++++++++++++++++++++++++--- 1 file changed, 107 insertions(+), 13 deletions(-) diff --git a/src/ApiController/ApiController.php b/src/ApiController/ApiController.php index ede313e..c7f9384 100644 --- a/src/ApiController/ApiController.php +++ b/src/ApiController/ApiController.php @@ -4,6 +4,8 @@ use Src\EntityDbHelper\DbHelper\SurvivorHelper; use Src\EntityDbHelper\DbHelper\InventoryHelper; +use Src\EntityDbHelper\DbHelper\TradePointsHelper; + class ApiController { @@ -11,6 +13,7 @@ class ApiController const STATUS_ERROR = 'HTTP/1.1 400 BAD REQUEST'; private $survivor; private $inventory; + private $tradePoints; private $requestMethod; private $uriPath; private $uriQuery; @@ -25,19 +28,27 @@ public function __construct($requestMethod, $uriPath) public function processRequest() { + $response = []; switch ($this->requestMethod) { case 'GET': - $this->_getActionCall(); + $response = $this->getActionCall(); break; case 'POST': - $this->_addSurvivor(); + $response = $this->_addSurvivor(); + break; + case 'PUT': + $response = $this->getUpdateCall(); break; default: + $this->runBadRequest(); break; } + + header($response['status_code_header']); + echo $response['body']; } - private function _getActionCall() + public function getActionCall() { if (!$this->uriPath[2]) { $this->runBadRequest(); @@ -63,9 +74,31 @@ private function _getActionCall() break; } - header($result['status_code_header']); + return $result; + } + + public function getUpdateCall() + { + if (!$this->uriPath[2]) { + $this->runBadRequest(); + } + $result = []; + switch ($this->uriPath[2]) { + case 'updateLocation': + $result = $this->_updateSurvivor('location'); + breaK; + case 'reportInfected': + $result = $this->_updateSurvivor('reported'); + breaK; + case 'tradeItems': + $result = $this->_tradeItems(); + breaK; + default: + $this->runBadRequest(); + break; + } - echo $result['body']; + return $result; } private function _getInfectedPercentage() @@ -125,8 +158,26 @@ private function _getLostPoints() { } + private function _setParamsDataFromUriQuery() + { + $this->uriQuery = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY); + if (!$this->uriQuery) { + $this->uriParams = null; + + return; + } + $params = []; + parse_str($this->uriQuery, $params); + + $this->uriParams = $params; + } + private function _addSurvivor() { + if ($this->uriPath[2] !== 'addSurvivor') { + $this->runBadRequest(); + } + $survivorData = $this->_getSurvivorDataFromPost(); $this->survivor = new SurvivorHelper(); $this->survivor->addNewSurvivor($survivorData); @@ -136,6 +187,12 @@ private function _addSurvivor() $inventoryData = $this->_getInventoryDataFromPost($survivorId); $this->inventory->addNewInventory($inventoryData); + + $message = 'Survivor Created!'; + $response['status_code_header'] = self::STATUS_OK; + $response['body'] = json_encode($message); + + return $response; } private function _getSurvivorDataFromPost() @@ -167,18 +224,55 @@ private function _getInventoryDataFromPost($survivorId) return $inventoryData; } - private function _setParamsDataFromUriQuery() + private function _updateSurvivor($type) { - $this->uriQuery = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY); - if (!$this->uriQuery) { - $this->uriParams = null; + $vars = json_decode(file_get_contents("php://input"), true); + if (!$vars['name']) { + $this->runBadRequest(); + } + $isLocationType = $type == 'location'; + if ($isLocationType && !$vars['location']) { + $this->runBadRequest(); + } - return; + $this->survivor = new SurvivorHelper(); + $survivorData = $this->survivor->getSurvivorByName($vars['name']); + $survivorData[$type] = $isLocationType ? $vars['location'] : $survivorData[$type] + 1; + + $this->survivor->updateSurvivor($survivorData); + + $message = 'Survivor: ' . $survivorData['name'] . ' Updated! '; + + if (!$isLocationType && $survivorData[$type] >= 3) { + $survivorData['infected'] = 1; + $message .= $survivorData['name'] . ' is now infected!!'; } - $params = []; - parse_str($this->uriQuery, $params); - $this->uriParams = $params; + $response['status_code_header'] = self::STATUS_OK; + $response['body'] = json_encode($message); + + return $response; + } + + private function _tradeItems() + { + $vars = json_decode(file_get_contents("php://input"), true); + + if(!$vars['buyer'] || !$vars['seller']){ + $this->runBadRequest(); + } + + $tradePoints = []; + $this->tradePoints = new TradePointsHelper(); + $tradePoints = $this->tradePoints->getAllTradePoints(); + + var_dump($tradePoints); + + $message = 'Trade Done'; + $response['status_code_header'] = self::STATUS_OK; + $response['body'] = json_encode($message); + + return $response; } /** From 7c57bac6b175ebabb79765398a53cb122f84cd5f Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Thu, 8 Jul 2021 11:44:01 +0200 Subject: [PATCH 12/23] Added getItemPoints method --- .../DbHelper/TradePointsHelper.php | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/EntityDbHelper/DbHelper/TradePointsHelper.php b/src/EntityDbHelper/DbHelper/TradePointsHelper.php index 81b4c1c..66c3088 100644 --- a/src/EntityDbHelper/DbHelper/TradePointsHelper.php +++ b/src/EntityDbHelper/DbHelper/TradePointsHelper.php @@ -1,10 +1,10 @@ tradePointsConnection->selectAll(); } + + public function getItemPoints($pointsTable) + { + $itemPoints = []; + foreach ($pointsTable as $value) { + $item = ''; + foreach ($value as $key => $val){ + if($key == 'item'){ + $item = $val ; + } + if($key == 'points'){ + $itemPoints[$item] = $val; + } + } + } + return $itemPoints; + } } \ No newline at end of file From c85e1adf468d41b5ab2a3e9d517be2a549ff6624 Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Thu, 8 Jul 2021 13:03:06 +0200 Subject: [PATCH 13/23] Added Api Helper class --- src/ApiHelper/ApiHelper.php | 211 ++++++++++++++++++++++++++++++++++++ 1 file changed, 211 insertions(+) create mode 100644 src/ApiHelper/ApiHelper.php diff --git a/src/ApiHelper/ApiHelper.php b/src/ApiHelper/ApiHelper.php new file mode 100644 index 0000000..d649691 --- /dev/null +++ b/src/ApiHelper/ApiHelper.php @@ -0,0 +1,211 @@ +runBadRequest(); + } + $survivorData['name'] = $_POST['name']; + $survivorData['age'] = $_POST['age']; + $survivorData['gender'] = $_POST['gender']; + $survivorData['location'] = $_POST['location']; + $survivorData['infected'] = 0; + $survivorData['reported'] = 0; + + return $survivorData; + } + + /** + * @param $survivorId + * @return array + */ + public function setInventoryDataFromPost($survivorId) + { + $inventoryData = []; + array_push($inventoryData, + ['id_survivor' => $survivorId, 'item' => 'water', 'qty' => $_POST['water']], + ['id_survivor' => $survivorId, 'item' => 'food', 'qty' => $_POST['food']], + ['id_survivor' => $survivorId, 'item' => 'medication', 'qty' => $_POST['medication']], + ['id_survivor' => $survivorId, 'item' => 'ammunition', 'qty' => $_POST['ammunition']] + ); + + return $inventoryData; + } + + /** + * @param $tradeBuyer + * @param $tradeSeller + * @return bool + */ + public function tradeCanBeDone($tradeBuyer, $tradeSeller) + { + $survivorBuyerId = $this->getSurvivorIdByName($tradeBuyer['name']); + $inventoryBuyer = $this->getInventoryBySurvivorId($survivorBuyerId); + $itemsQtyBuyer = $this->getInventoryItemsQty($inventoryBuyer); + + $survivorSellerId = $this->getSurvivorIdByName($tradeSeller['name']); + $inventorySeller = $this->getInventoryBySurvivorId($survivorSellerId); + $itemsQtySeller = $this->getInventoryItemsQty($inventorySeller); + + $tablePoints = $this->getAllTradePoints(); + $itemPoints = $this->getItemPoints($tablePoints); + + $buyerPoints = $this->calculateTradePoints($tradeBuyer, $itemPoints, $itemsQtyBuyer); + $sellerPoints = $this->calculateTradePoints($tradeSeller, $itemPoints, $itemsQtySeller); + + return $buyerPoints == $sellerPoints; + } + + /** + * @param $name + * @return mixed + */ + public function getSurvivorIdByName($name) + { + if (!$this->survivor) { + $this->survivor = new SurvivorHelper(); + } + + return $this->survivor->getSurvivorByName($name)['id_survivor']; + } + + /** + * @param $survivorId + * @return mixed + */ + public function getInventoryBySurvivorId($survivorId) + { + if (!$this->inventory) { + $this->inventory = new InventoryHelper(); + } + + return $this->inventory->getInventoryBySurvivorId($survivorId); + } + + /** + * @param $inventory + * @return array + */ + public function getInventoryItemsQty($inventory) + { + if (!$this->inventory) { + $this->inventory = new InventoryHelper(); + } + + return $this->inventory->getInventoryItemsQty($inventory); + } + + /** + * @return mixed + */ + public function getAllTradePoints() + { + if (!$this->inventory) { + $this->tradePoints = new TradePointsHelper(); + } + + return $this->tradePoints->getAllTradePoints(); + } + + /** + * @param $tablePoints + * @return array + */ + public function getItemPoints($tablePoints) + { + if (!$this->inventory) { + $this->tradePoints = new TradePointsHelper(); + } + + return $this->tradePoints->getItemPoints($tablePoints); + } + + /** + * @param $trader + * @param $itemPoints + * @param $traderInventory + * @return bool|float|int + */ + public function calculateTradePoints($trader, $itemPoints, $traderInventory) + { + $result = 0; + + foreach ($itemPoints as $item => $point) { + foreach ($trader as $key => $value) { + if ($item !== $key) { + continue; + } + if (!$this->checkIfTraderHasItems($traderInventory, $key, $value)) { + return false; + } + $result = ($value * $point) + $result; + } + } + + return $result; + } + + /** + * @param $traderInventory + * @param $traderItem + * @param $itemQty + * @return bool + */ + public function checkIfTraderHasItems($traderInventory, $traderItem, $itemQty) + { + $result = true; + foreach ($traderInventory as $item => $qty) { + if ($item == $traderItem) { + if ($itemQty < $qty) { + return false; + } + } + } + + return $result; + } + + /** + * @param $a + * @param $b + * @return float|int + * + * $a : $b = result : 100 + */ + public function getPercentage( + $a, + $b + ) { + return ($a / $b) * 100; + } + + /** + * Exception Trigger + */ + public function runBadRequest() + { + header(self::STATUS_ERROR); + echo "Bad Request"; + exit(); + } +} \ No newline at end of file From a2869034eb1200095188913761d96e162b4238b5 Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Thu, 8 Jul 2021 13:19:43 +0200 Subject: [PATCH 14/23] Code style: Adapted ApiController to ApiHelper --- src/ApiController/ApiController.php | 124 ++++++++-------------------- src/ApiHelper/ApiHelper.php | 75 +++++++++++------ 2 files changed, 86 insertions(+), 113 deletions(-) diff --git a/src/ApiController/ApiController.php b/src/ApiController/ApiController.php index c7f9384..2c5a1ba 100644 --- a/src/ApiController/ApiController.php +++ b/src/ApiController/ApiController.php @@ -2,18 +2,12 @@ namespace Src\ApiController; -use Src\EntityDbHelper\DbHelper\SurvivorHelper; -use Src\EntityDbHelper\DbHelper\InventoryHelper; -use Src\EntityDbHelper\DbHelper\TradePointsHelper; - +use Src\ApiHelper\ApiHelper; class ApiController { - const STATUS_OK = 'HTTP/1.1 200 OK'; - const STATUS_ERROR = 'HTTP/1.1 400 BAD REQUEST'; - private $survivor; - private $inventory; - private $tradePoints; + + private $helper; private $requestMethod; private $uriPath; private $uriQuery; @@ -24,6 +18,7 @@ public function __construct($requestMethod, $uriPath) $this->requestMethod = $requestMethod; $this->uriPath = $uriPath; $this->processRequest(); + $this->helper = new ApiHelper(); } public function processRequest() @@ -40,7 +35,7 @@ public function processRequest() $response = $this->getUpdateCall(); break; default: - $this->runBadRequest(); + $this->helper->runBadRequest(); break; } @@ -51,7 +46,7 @@ public function processRequest() public function getActionCall() { if (!$this->uriPath[2]) { - $this->runBadRequest(); + $this->helper->runBadRequest(); } $this->_setParamsDataFromUriQuery(); @@ -70,7 +65,7 @@ public function getActionCall() $this->_getLostPoints(); break; default: - $this->runBadRequest(); + $this->helper->runBadRequest(); break; } @@ -80,7 +75,7 @@ public function getActionCall() public function getUpdateCall() { if (!$this->uriPath[2]) { - $this->runBadRequest(); + $this->helper->runBadRequest(); } $result = []; switch ($this->uriPath[2]) { @@ -94,7 +89,7 @@ public function getUpdateCall() $result = $this->_tradeItems(); breaK; default: - $this->runBadRequest(); + $this->helper->runBadRequest(); break; } @@ -105,8 +100,7 @@ private function _getInfectedPercentage() { $infected = 0; $survivorsQty = 0; - $this->survivor = new SurvivorHelper(); - $survivors = $this->survivor->getAllSurvivors(); + $survivors = $this->helper->getAllSurvivors(); foreach ($survivors as $survivor) { $survivorsQty++; @@ -122,11 +116,11 @@ private function _getInfectedPercentage() $infected++; } } - $percentage = intval($this->getPercentage($infected, $survivorsQty)); + $percentage = intval($this->helper->getPercentage($infected, $survivorsQty)); $message = "Infected Percentage = " . $percentage . "%"; - $response['status_code_header'] = self::STATUS_OK; + $response['status_code_header'] = $this->helper::STATUS_OK; $response['infected'] = $infected; $response['survivorsQty'] = $survivorsQty; $response['percentage'] = $percentage; @@ -142,7 +136,7 @@ private function _getNonInfectedPercentage() $percentage = $infectedResponse['percentage']; $nonInfectedPercentage = intval(100 - $percentage); $message = "Non Infected Percentage = " . $nonInfectedPercentage . "%"; - $response['status_code_header'] = self::STATUS_OK; + $response['status_code_header'] = $this->helper::STATUS_OK; $response['nonInfectedPercentage'] = $nonInfectedPercentage; $response['body'] = json_encode($message); @@ -175,71 +169,39 @@ private function _setParamsDataFromUriQuery() private function _addSurvivor() { if ($this->uriPath[2] !== 'addSurvivor') { - $this->runBadRequest(); + $this->helper->runBadRequest(); } - $survivorData = $this->_getSurvivorDataFromPost(); - $this->survivor = new SurvivorHelper(); - $this->survivor->addNewSurvivor($survivorData); + $survivorData = $this->helper->getSurvivorDataFromPost(); + $this->helper->addNewSurvivor($survivorData); - $this->inventory = new InventoryHelper(); - $survivorId = $this->survivor->getSurvivorByName($survivorData['name'])['id_survivor']; - $inventoryData = $this->_getInventoryDataFromPost($survivorId); + $survivorId = $this->helper->getSurvivorIdByName($survivorData['name']); + $inventoryData = $this->helper->setInventoryDataFromPost($survivorId); - $this->inventory->addNewInventory($inventoryData); + $this->helper->addNewInventory($inventoryData); $message = 'Survivor Created!'; - $response['status_code_header'] = self::STATUS_OK; + $response['status_code_header'] = $this->helper::STATUS_OK; $response['body'] = json_encode($message); return $response; } - private function _getSurvivorDataFromPost() - { - $survivorData = []; - if (!$_POST['name']) { - $this->runBadRequest(); - } - $survivorData['name'] = $_POST['name']; - $survivorData['age'] = $_POST['age']; - $survivorData['gender'] = $_POST['gender']; - $survivorData['location'] = $_POST['location']; - $survivorData['infected'] = 0; - $survivorData['reported'] = 0; - - return $survivorData; - } - - private function _getInventoryDataFromPost($survivorId) - { - $inventoryData = []; - array_push($inventoryData, - ['id_survivor' => $survivorId, 'item' => 'water', 'qty' => $_POST['water']], - ['id_survivor' => $survivorId, 'item' => 'food', 'qty' => $_POST['food']], - ['id_survivor' => $survivorId, 'item' => 'medication', 'qty' => $_POST['medication']], - ['id_survivor' => $survivorId, 'item' => 'ammunition', 'qty' => $_POST['ammunition']] - ); - - return $inventoryData; - } - private function _updateSurvivor($type) { $vars = json_decode(file_get_contents("php://input"), true); if (!$vars['name']) { - $this->runBadRequest(); + $this->helper->runBadRequest(); } $isLocationType = $type == 'location'; if ($isLocationType && !$vars['location']) { - $this->runBadRequest(); + $this->helper->runBadRequest(); } - $this->survivor = new SurvivorHelper(); - $survivorData = $this->survivor->getSurvivorByName($vars['name']); + $survivorData = $this->helper->getSurvivorByName($vars['name']); $survivorData[$type] = $isLocationType ? $vars['location'] : $survivorData[$type] + 1; - $this->survivor->updateSurvivor($survivorData); + $this->helper->updateSurvivor($survivorData); $message = 'Survivor: ' . $survivorData['name'] . ' Updated! '; @@ -248,7 +210,7 @@ private function _updateSurvivor($type) $message .= $survivorData['name'] . ' is now infected!!'; } - $response['status_code_header'] = self::STATUS_OK; + $response['status_code_header'] = $this->helper::STATUS_OK; $response['body'] = json_encode($message); return $response; @@ -258,40 +220,22 @@ private function _tradeItems() { $vars = json_decode(file_get_contents("php://input"), true); - if(!$vars['buyer'] || !$vars['seller']){ - $this->runBadRequest(); + if (!$vars['buyer'] || !$vars['seller'] || !$vars['buyer']['name'] || !$vars['seller']['name']) { + $this->helper->runBadRequest(); } - $tradePoints = []; - $this->tradePoints = new TradePointsHelper(); - $tradePoints = $this->tradePoints->getAllTradePoints(); + $isTradeOk = $this->helper->tradeCanBeDone($vars['buyer'], $vars['seller']); - var_dump($tradePoints); + if ($isTradeOk) { + $buyerId = $this->helper->getSurvivorIdByName($vars['buyer']['name']); + } + + $message = $isTradeOk ? 'Trade Done' : 'Trade cannot be done'; - $message = 'Trade Done'; - $response['status_code_header'] = self::STATUS_OK; + $response['status_code_header'] = $this->helper::STATUS_OK; $response['body'] = json_encode($message); return $response; } - /** - * @param $a - * @param $b - * @return float|int - * - * $a : $b = result : 100 - */ - public function getPercentage($a, $b) - { - return ($a / $b) * 100; - } - - public function runBadRequest() - { - header(self::STATUS_ERROR); - echo "Bad Request"; - exit(); - } - } \ No newline at end of file diff --git a/src/ApiHelper/ApiHelper.php b/src/ApiHelper/ApiHelper.php index d649691..a1332d8 100644 --- a/src/ApiHelper/ApiHelper.php +++ b/src/ApiHelper/ApiHelper.php @@ -12,9 +12,16 @@ class ApiHelper const STATUS_OK = 'HTTP/1.1 200 OK'; const STATUS_ERROR = 'HTTP/1.1 400 BAD REQUEST'; - private $survivor; - private $inventory; - private $tradePoints; + public $survivor; + public $inventory; + public $tradePoints; + + public function __construct() + { + $this->survivor = new SurvivorHelper(); + $this->inventory = new InventoryHelper(); + $this->tradePoints = new TradePointsHelper(); + } /** * @return array @@ -76,17 +83,46 @@ public function tradeCanBeDone($tradeBuyer, $tradeSeller) return $buyerPoints == $sellerPoints; } + /** + * @return mixed + */ + public function getAllSurvivors() + { + return $this->survivor->getAllSurvivors(); + } + + /** + * @param $name + * @return mixed + */ + public function getSurvivorByName($name) + { + return $this->survivor->getSurvivorByName($name); + } + /** * @param $name * @return mixed */ public function getSurvivorIdByName($name) { - if (!$this->survivor) { - $this->survivor = new SurvivorHelper(); - } + return $this->getSurvivorByName($name)['id_survivor']; + } - return $this->survivor->getSurvivorByName($name)['id_survivor']; + /** + * @param $survivor + */ + public function addNewSurvivor($survivor) + { + $this->survivor->addNewSurvivor($survivor); + } + + /** + * @param $survivorData + */ + public function updateSurvivor($survivorData) + { + $this->survivor->updateSurvivor($survivorData); } /** @@ -95,10 +131,6 @@ public function getSurvivorIdByName($name) */ public function getInventoryBySurvivorId($survivorId) { - if (!$this->inventory) { - $this->inventory = new InventoryHelper(); - } - return $this->inventory->getInventoryBySurvivorId($survivorId); } @@ -108,22 +140,23 @@ public function getInventoryBySurvivorId($survivorId) */ public function getInventoryItemsQty($inventory) { - if (!$this->inventory) { - $this->inventory = new InventoryHelper(); - } - return $this->inventory->getInventoryItemsQty($inventory); } + /** + * @param $inventory + * @return mixed + */ + public function addNewInventory($inventory) + { + return $this->inventory->addNewInventory($inventory); + } + /** * @return mixed */ public function getAllTradePoints() { - if (!$this->inventory) { - $this->tradePoints = new TradePointsHelper(); - } - return $this->tradePoints->getAllTradePoints(); } @@ -133,10 +166,6 @@ public function getAllTradePoints() */ public function getItemPoints($tablePoints) { - if (!$this->inventory) { - $this->tradePoints = new TradePointsHelper(); - } - return $this->tradePoints->getItemPoints($tablePoints); } From f6f0d5aeaf4877e219f928b4cd2f5e3db62dbf74 Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Thu, 8 Jul 2021 13:22:35 +0200 Subject: [PATCH 15/23] Add Update method on Inventory Helper --- .../DbHelper/InventoryHelper.php | 35 +++++++++++++++---- 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/src/EntityDbHelper/DbHelper/InventoryHelper.php b/src/EntityDbHelper/DbHelper/InventoryHelper.php index c41bcd2..68f059b 100644 --- a/src/EntityDbHelper/DbHelper/InventoryHelper.php +++ b/src/EntityDbHelper/DbHelper/InventoryHelper.php @@ -1,4 +1,5 @@ inventoryConnection->selectBySurvivorId($inventory)[0]; + return $this->inventoryConnection->selectBySurvivorId($survivorId); } /** @@ -41,18 +42,40 @@ public function getInventoryBySurvivorId($inventory) */ public function addNewInventory($inventory) { - - $existInventory = $this->getInventoryBySurvivorId($inventory); - if($existInventory){ + $existInventory = $this->getInventoryBySurvivorId($inventory['id_survivor']); + if ($existInventory) { header('HTTP/1.1 400 BAD REQUEST'); echo "Inventory already exists, pick another survivor name"; exit(); } - foreach ($inventory as $item){ + foreach ($inventory as $item) { $this->inventoryConnection->insert($item); } } + public function getInventoryItemsQty($inventory) + { + $itemQty = []; + foreach ($inventory as $value) { + $item = ''; + foreach ($value as $key => $val) { + if ($key == 'item') { + $item = $val; + } + if ($key == 'qty') { + $itemQty[$item] = $val; + } + } + } + + return $itemQty; + } + + public function updateInventory($inventory) + { + $this->inventoryConnection->update($inventory); + } + } From f26f603162e2bba4e15e3789ed8c18c5128fb893 Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Fri, 9 Jul 2021 11:50:53 +0200 Subject: [PATCH 16/23] Added guide 'how to run project' --- .docker/dumps/orig_db.sql | 70 --------------------------------------- HOW_TO_RUN_PROJECT.md | 20 +++++++++++ 2 files changed, 20 insertions(+), 70 deletions(-) delete mode 100644 .docker/dumps/orig_db.sql create mode 100644 HOW_TO_RUN_PROJECT.md diff --git a/.docker/dumps/orig_db.sql b/.docker/dumps/orig_db.sql deleted file mode 100644 index a8eb3a5..0000000 --- a/.docker/dumps/orig_db.sql +++ /dev/null @@ -1,70 +0,0 @@ -/* -SQLyog Ultimate v13.1.2 (64 bit) -MySQL - 10.5.9-MariaDB-1:10.5.9+maria~focal : Database - zssn -********************************************************************* -*/ - -/*!40101 SET NAMES utf8 */; - -/*!40101 SET SQL_MODE=''*/; - -/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; -/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; -/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -CREATE DATABASE /*!32312 IF NOT EXISTS*/`zssn` /*!40100 DEFAULT CHARACTER SET utf8mb4 */; - -USE `zssn`; - -/*Table structure for table `inventory` */ - -DROP TABLE IF EXISTS `inventory`; - -CREATE TABLE `inventory` ( - `id_survivor` int(11) NOT NULL AUTO_INCREMENT, - `item` text DEFAULT NULL, - `qty` int(11) DEFAULT NULL, - PRIMARY KEY (`id_survivor`), - CONSTRAINT `id_survivor` FOREIGN KEY (`id_survivor`) REFERENCES `survivors` (`id_survivor`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; - -/*Data for the table `inventory` */ - -/*Table structure for table `survivors` */ - -DROP TABLE IF EXISTS `survivors`; - -CREATE TABLE `survivors` ( - `id_survivor` int(11) NOT NULL AUTO_INCREMENT, - `name` text DEFAULT NULL, - `age` int(11) DEFAULT NULL, - `gender` text DEFAULT NULL, - `location` text DEFAULT NULL, - `infected` smallint(6) DEFAULT NULL, - `reported` smallint(6) DEFAULT NULL, - PRIMARY KEY (`id_survivor`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; - -/*Data for the table `survivors` */ - -/*Table structure for table `trade_points` */ - -DROP TABLE IF EXISTS `trade_points`; - -CREATE TABLE `trade_points` ( - `item` text DEFAULT NULL, - `points` int(11) DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; - -/*Data for the table `trade_points` */ - -insert into `trade_points`(`item`,`points`) values -('Water',4), -('Food',3), -('Medication',2), -('Ammunition',1); - -/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; -/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; -/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; -/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; diff --git a/HOW_TO_RUN_PROJECT.md b/HOW_TO_RUN_PROJECT.md new file mode 100644 index 0000000..52b4dc0 --- /dev/null +++ b/HOW_TO_RUN_PROJECT.md @@ -0,0 +1,20 @@ +## How to run project +1. From project root: `composer install` +2. `composer dump-autoload -o` +3. `cp .env.docker .env` +4. `cd .docker/` +5. `docker-compose up -d` +6. Connect to Mariadb Docker image: + `docker exec -it $(docker ps -qf expose=3306) bash` +7. Import db to mariadb: + `mysql -uroot -proot zssn < /usr/db.sql` +8. Once it's done, you can `exit` from machine +9. Import ./ZSSN.postman_collection.json file into your Postman app +10. If it's all done, you can try api calls from postman +11. You can connect to the database using this parameters: + * DB_HOST=127.0.0.1 + * DB_PORT=3307 + * DB_DATABASE=zssn + * DB_USERNAME=root + * DB_PASSWORD=root + \ No newline at end of file From 76dd680ef58579e61035959543e734a5eb9902be Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Fri, 9 Jul 2021 11:51:21 +0200 Subject: [PATCH 17/23] Added db dump --- .docker/dumps/db.sql | 101 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 .docker/dumps/db.sql diff --git a/.docker/dumps/db.sql b/.docker/dumps/db.sql new file mode 100644 index 0000000..e4265dd --- /dev/null +++ b/.docker/dumps/db.sql @@ -0,0 +1,101 @@ +/* +SQLyog Ultimate v13.1.2 (64 bit) +MySQL - 10.5.9-MariaDB-1:10.5.9+maria~focal : Database - zssn +********************************************************************* +*/ + +/*!40101 SET NAMES utf8 */; + +/*!40101 SET SQL_MODE=''*/; + +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/`zssn` /*!40100 DEFAULT CHARACTER SET utf8mb4 */; + +USE `zssn`; + +/*Table structure for table `inventory` */ + +DROP TABLE IF EXISTS `inventory`; + +CREATE TABLE `inventory` ( + `id_inventory` int(11) NOT NULL AUTO_INCREMENT, + `id_survivor` int(11) DEFAULT NULL, + `item` text DEFAULT NULL, + `qty` int(11) DEFAULT NULL, + PRIMARY KEY (`id_inventory`), + KEY `id_survivor` (`id_survivor`), + CONSTRAINT `inventory_ibfk_1` FOREIGN KEY (`id_survivor`) REFERENCES `survivors` (`id_survivor`) +) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=utf8mb4; + +/*Data for the table `inventory` */ + +insert into `inventory`(`id_inventory`,`id_survivor`,`item`,`qty`) values +(27,42,'water',6), +(28,42,'food',0), +(29,42,'medication',3), +(30,42,'ammunition',0), +(31,43,'water',2), +(32,43,'food',0), +(33,43,'medication',5), +(34,43,'ammunition',3), +(35,44,'water',0), +(36,44,'food',5), +(37,44,'medication',2), +(38,44,'ammunition',5), +(39,45,'water',8), +(40,45,'food',1), +(41,45,'medication',0), +(42,45,'ammunition',4), +(43,46,'water',1), +(44,46,'food',1), +(45,46,'medication',2), +(46,46,'ammunition',4); + +/*Table structure for table `survivors` */ + +DROP TABLE IF EXISTS `survivors`; + +CREATE TABLE `survivors` ( + `id_survivor` int(11) NOT NULL AUTO_INCREMENT, + `name` text DEFAULT NULL, + `age` int(11) DEFAULT NULL, + `gender` text DEFAULT NULL, + `location` text DEFAULT NULL, + `infected` smallint(6) DEFAULT NULL, + `reported` smallint(6) DEFAULT NULL, + PRIMARY KEY (`id_survivor`) +) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=utf8mb4; + +/*Data for the table `survivors` */ + +insert into `survivors`(`id_survivor`,`name`,`age`,`gender`,`location`,`infected`,`reported`) values +(42,'testerino',12,'male','+1234/+8901',0,0), +(43,'testerina',39,'female','-9298338/+1234900',0,0), +(44,'gigi',17,'female','+12345/-14',0,6), +(45,'gigi2',98,'male','+4321/+9382',0,2), +(46,'franco',24,'male','+0391/+933838',0,0); + +/*Table structure for table `trade_points` */ + +DROP TABLE IF EXISTS `trade_points`; + +CREATE TABLE `trade_points` ( + `item` text DEFAULT NULL, + `points` int(11) DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +/*Data for the table `trade_points` */ + +insert into `trade_points`(`item`,`points`) values +('water',4), +('food',3), +('medication',2), +('ammunition',1); + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; From b9f1c60de24acef630d655e2ad786b55c20882bf Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Fri, 9 Jul 2021 11:51:41 +0200 Subject: [PATCH 18/23] Updated .gitignore --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index c148e02..cbb9fa6 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -/.docker/db \ No newline at end of file +/.docker/db +/.env \ No newline at end of file From 4886af4800f427a070269c87c1635d586b3e10f4 Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Fri, 9 Jul 2021 11:53:01 +0200 Subject: [PATCH 19/23] Code Style: index.php --- index.php | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/index.php b/index.php index 7dc2cc7..0337702 100644 --- a/index.php +++ b/index.php @@ -2,20 +2,15 @@ require "vendor/autoload.php"; use Src\DatabaseManager\DatabaseConnector; -use Src\DatabaseManager\SurvivorConnection; -use Src\DatabaseManager\InventoryConnection; -use Src\DatabaseManager\TradePointsConnection; -use Src\EntityDbHelper\DbHelper\SurvivorHelper; use Src\ApiController\ApiController; - header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); header("Access-Control-Allow-Methods: OPTIONS,GET,POST,PUT,DELETE"); $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); -$uri = explode( '/', $uri ); +$uri = explode('/', $uri); if ($uri[1] !== 'api.php') { header("HTTP/1.1 404 Not Found"); @@ -30,5 +25,5 @@ $db = new DatabaseConnector; $dbConnection = $db->getConnection(); -$requestMethod = $_SERVER["REQUEST_METHOD"]; +$requestMethod = $_SERVER["REQUEST_METHOD"]; $apiController = new ApiController($requestMethod, $uri); From 964f6e6b7d0759a2a9a13d1b0c79c165bf2235ef Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Fri, 9 Jul 2021 11:53:14 +0200 Subject: [PATCH 20/23] Added postman collection for tests --- ZSSN.postman_collection.json | 210 +++++++++++++++++++++++++++++++++++ 1 file changed, 210 insertions(+) create mode 100644 ZSSN.postman_collection.json diff --git a/ZSSN.postman_collection.json b/ZSSN.postman_collection.json new file mode 100644 index 0000000..6298d6d --- /dev/null +++ b/ZSSN.postman_collection.json @@ -0,0 +1,210 @@ +{ + "info": { + "_postman_id": "b417f438-139c-4071-b6d3-d6c3faf8d2e0", + "name": "ZSSN", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "addSurvivor", + "request": { + "method": "POST", + "header": [ + { + "key": "name", + "value": "ciccio", + "type": "text" + } + ], + "body": { + "mode": "formdata", + "formdata": [ + { + "key": "name", + "value": "franco", + "type": "text" + }, + { + "key": "age", + "value": "24", + "type": "text" + }, + { + "key": "gender", + "value": "male", + "type": "text" + }, + { + "key": "location", + "value": "+0391/+933838", + "type": "text" + }, + { + "key": "water", + "value": "1", + "type": "text" + }, + { + "key": "food", + "value": "1", + "type": "text" + }, + { + "key": "medication", + "value": "2", + "type": "text" + }, + { + "key": "ammunition", + "value": "4", + "type": "text" + } + ] + }, + "url": { + "raw": "http://127.0.0.1/api.php/addSurvivor", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "path": [ + "api.php", + "addSurvivor" + ] + } + }, + "response": [] + }, + { + "name": "tradeItems", + "request": { + "method": "PUT", + "header": [ + { + "key": "name", + "value": "ciccio", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"buyer\": {\n \"name\": \"gigi\",\n \"water\": \"1\"\n }, \n \"seller\": {\n \"name\": \"testerino\",\n \"food\": \"1\",\n \"ammunition\": \"1\"\n }\n}" + }, + "url": { + "raw": "http://127.0.0.1/api.php/tradeItems", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "path": [ + "api.php", + "tradeItems" + ] + } + }, + "response": [] + }, + { + "name": "updateLocation", + "request": { + "method": "PUT", + "header": [], + "body": { + "mode": "raw", + "raw": "{\n \"name\":\"testerina\",\n \"location\":{\n \"longitude\":\"-093245\",\n \"latitude\":\"+101010\"\n }\n}" + }, + "url": { + "raw": "http://127.0.0.1/api.php/updateLocation", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "path": [ + "api.php", + "updateLocation" + ] + } + }, + "response": [] + }, + { + "name": "reportInfected", + "request": { + "method": "PUT", + "header": [], + "body": { + "mode": "raw", + "raw": "{\n \"name\":\"gigi2\"\n}" + }, + "url": { + "raw": "http://127.0.0.1/api.php/reportInfected", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "path": [ + "api.php", + "reportInfected" + ] + } + }, + "response": [] + }, + { + "name": "getInfectedPercentage", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "http://127.0.0.1/api.php/getInfectedPercentage", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "path": [ + "api.php", + "getInfectedPercentage" + ] + } + }, + "response": [] + }, + { + "name": "getNonInfectedPercentage", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "http://127.0.0.1/api.php/getNonInfectedPercentage", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "path": [ + "api.php", + "getNonInfectedPercentage" + ] + } + }, + "response": [] + } + ] +} \ No newline at end of file From 8baaf8b15afa1799400882d62e6ae15644e16985 Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Fri, 9 Jul 2021 11:54:12 +0200 Subject: [PATCH 21/23] Updated .docker for xdebug --- .docker/Dockerfile | 3 +++ .docker/docker-compose.yml | 10 +++++++--- 2 files changed, 10 insertions(+), 3 deletions(-) create mode 100644 .docker/Dockerfile diff --git a/.docker/Dockerfile b/.docker/Dockerfile new file mode 100644 index 0000000..31620ba --- /dev/null +++ b/.docker/Dockerfile @@ -0,0 +1,3 @@ +FROM webdevops/php-nginx:7.2 + +RUN pecl install xdebug-2.9.8 && docker-php-ext-enable xdebug \ No newline at end of file diff --git a/.docker/docker-compose.yml b/.docker/docker-compose.yml index 5c76276..b04b4cc 100755 --- a/.docker/docker-compose.yml +++ b/.docker/docker-compose.yml @@ -1,8 +1,8 @@ version: '3.1' services: apache2: - container_name: apache2_php - image: webdevops/php-apache:ubuntu-18.04 + container_name: docker_apache2_php + build: . ports: - 80:80 - 443:443 @@ -12,7 +12,10 @@ services: - mariadb links: - mariadb - restart: always + environment: + PHP_IDE_CONFIG: 'serverName=postman' + XDEBUG_CONFIG: 'remote_mode=req remote_enable=1 remote_connect_back=0 remote_autostart=1 remote_host=172.17.0.1 remote_port=9000 idekey=PHPSTORM' + restart: always networks: zssn_net: ipv4_address: 12.7.0.4 @@ -28,6 +31,7 @@ services: - '3307' volumes: - ./db:/var/lib/mysql + - ./dumps/db.sql:/usr/db.sql networks: zssn_net: ipv4_address: 12.7.0.5 From 27114bf3538c20d10e9108d738ea39252b5643fd Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Fri, 9 Jul 2021 11:55:58 +0200 Subject: [PATCH 22/23] Code Style && Added tradeItems action --- src/ApiController/ApiController.php | 75 ++++++---- src/ApiHelper/ApiHelper.php | 134 +++++++++++++----- src/DatabaseManager/InventoryConnection.php | 40 +++--- .../DbHelper/InventoryHelper.php | 6 +- .../DbHelper/SurvivorHelper.php | 1 - 5 files changed, 171 insertions(+), 85 deletions(-) diff --git a/src/ApiController/ApiController.php b/src/ApiController/ApiController.php index 2c5a1ba..72982fb 100644 --- a/src/ApiController/ApiController.php +++ b/src/ApiController/ApiController.php @@ -10,15 +10,13 @@ class ApiController private $helper; private $requestMethod; private $uriPath; - private $uriQuery; - private $uriParams; public function __construct($requestMethod, $uriPath) { $this->requestMethod = $requestMethod; $this->uriPath = $uriPath; - $this->processRequest(); $this->helper = new ApiHelper(); + $this->processRequest(); } public function processRequest() @@ -43,13 +41,15 @@ public function processRequest() echo $response['body']; } - public function getActionCall() + /** + * @return array + */ + public function getActionCall(): array { if (!$this->uriPath[2]) { $this->helper->runBadRequest(); } - $this->_setParamsDataFromUriQuery(); $result = []; switch ($this->uriPath[2]) { case 'getInfectedPercentage': @@ -72,7 +72,10 @@ public function getActionCall() return $result; } - public function getUpdateCall() + /** + * @return array + */ + public function getUpdateCall(): array { if (!$this->uriPath[2]) { $this->helper->runBadRequest(); @@ -96,7 +99,10 @@ public function getUpdateCall() return $result; } - private function _getInfectedPercentage() + /** + * @return array + */ + private function _getInfectedPercentage(): array { $infected = 0; $survivorsQty = 0; @@ -130,7 +136,10 @@ private function _getInfectedPercentage() return $response; } - private function _getNonInfectedPercentage() + /** + * @return array + */ + private function _getNonInfectedPercentage(): array { $infectedResponse = $this->_getInfectedPercentage(); $percentage = $infectedResponse['percentage']; @@ -144,29 +153,24 @@ private function _getNonInfectedPercentage() return $response; } + /** + * TODO + */ private function _getAverageAllResources() { } + /** + * TODO + */ private function _getLostPoints() { } - private function _setParamsDataFromUriQuery() - { - $this->uriQuery = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY); - if (!$this->uriQuery) { - $this->uriParams = null; - - return; - } - $params = []; - parse_str($this->uriQuery, $params); - - $this->uriParams = $params; - } - - private function _addSurvivor() + /** + * @return array + */ + private function _addSurvivor(): array { if ($this->uriPath[2] !== 'addSurvivor') { $this->helper->runBadRequest(); @@ -187,19 +191,32 @@ private function _addSurvivor() return $response; } - private function _updateSurvivor($type) + /** + * @param $type + * @return array + */ + private function _updateSurvivor($type): array { $vars = json_decode(file_get_contents("php://input"), true); + if (!$vars['name']) { $this->helper->runBadRequest(); } + $isLocationType = $type == 'location'; + if ($isLocationType && !$vars['location']) { $this->helper->runBadRequest(); } + if($isLocationType){ + $long = $vars['location']['longitude']; + $lat = $vars['location']['latitude']; + $location = sprintf('%s/%s', $long, $lat); + } + $survivorData = $this->helper->getSurvivorByName($vars['name']); - $survivorData[$type] = $isLocationType ? $vars['location'] : $survivorData[$type] + 1; + $survivorData[$type] = $isLocationType ? $location : $survivorData[$type] + 1; $this->helper->updateSurvivor($survivorData); @@ -207,6 +224,7 @@ private function _updateSurvivor($type) if (!$isLocationType && $survivorData[$type] >= 3) { $survivorData['infected'] = 1; + $this->helper->updateSurvivor($survivorData); $message .= $survivorData['name'] . ' is now infected!!'; } @@ -216,7 +234,10 @@ private function _updateSurvivor($type) return $response; } - private function _tradeItems() + /** + * @return array + */ + private function _tradeItems(): array { $vars = json_decode(file_get_contents("php://input"), true); @@ -227,7 +248,7 @@ private function _tradeItems() $isTradeOk = $this->helper->tradeCanBeDone($vars['buyer'], $vars['seller']); if ($isTradeOk) { - $buyerId = $this->helper->getSurvivorIdByName($vars['buyer']['name']); + $this->helper->updateInventoryTraders($vars['buyer'], $vars['seller']); } $message = $isTradeOk ? 'Trade Done' : 'Trade cannot be done'; diff --git a/src/ApiHelper/ApiHelper.php b/src/ApiHelper/ApiHelper.php index a1332d8..a04265b 100644 --- a/src/ApiHelper/ApiHelper.php +++ b/src/ApiHelper/ApiHelper.php @@ -26,7 +26,7 @@ public function __construct() /** * @return array */ - public function getSurvivorDataFromPost() + public function getSurvivorDataFromPost(): array { $survivorData = []; if (!$_POST['name']) { @@ -46,7 +46,7 @@ public function getSurvivorDataFromPost() * @param $survivorId * @return array */ - public function setInventoryDataFromPost($survivorId) + public function setInventoryDataFromPost($survivorId): array { $inventoryData = []; array_push($inventoryData, @@ -59,30 +59,6 @@ public function setInventoryDataFromPost($survivorId) return $inventoryData; } - /** - * @param $tradeBuyer - * @param $tradeSeller - * @return bool - */ - public function tradeCanBeDone($tradeBuyer, $tradeSeller) - { - $survivorBuyerId = $this->getSurvivorIdByName($tradeBuyer['name']); - $inventoryBuyer = $this->getInventoryBySurvivorId($survivorBuyerId); - $itemsQtyBuyer = $this->getInventoryItemsQty($inventoryBuyer); - - $survivorSellerId = $this->getSurvivorIdByName($tradeSeller['name']); - $inventorySeller = $this->getInventoryBySurvivorId($survivorSellerId); - $itemsQtySeller = $this->getInventoryItemsQty($inventorySeller); - - $tablePoints = $this->getAllTradePoints(); - $itemPoints = $this->getItemPoints($tablePoints); - - $buyerPoints = $this->calculateTradePoints($tradeBuyer, $itemPoints, $itemsQtyBuyer); - $sellerPoints = $this->calculateTradePoints($tradeSeller, $itemPoints, $itemsQtySeller); - - return $buyerPoints == $sellerPoints; - } - /** * @return mixed */ @@ -135,12 +111,14 @@ public function getInventoryBySurvivorId($survivorId) } /** - * @param $inventory + * @param $survivorId * @return array */ - public function getInventoryItemsQty($inventory) + public function getInventoryItemsQtyBySurvivorId($survivorId): array { - return $this->inventory->getInventoryItemsQty($inventory); + $survivorInventory = $this->getInventoryBySurvivorId($survivorId); + + return $this->inventory->getInventoryItemsQty($survivorInventory); } /** @@ -152,6 +130,11 @@ public function addNewInventory($inventory) return $this->inventory->addNewInventory($inventory); } + public function updateInventory($inventory) + { + $this->inventory->updateInventory($inventory); + } + /** * @return mixed */ @@ -164,11 +147,33 @@ public function getAllTradePoints() * @param $tablePoints * @return array */ - public function getItemPoints($tablePoints) + public function getItemPoints($tablePoints): array { return $this->tradePoints->getItemPoints($tablePoints); } + /** + * @param $tradeBuyer + * @param $tradeSeller + * @return bool + */ + public function tradeCanBeDone($tradeBuyer, $tradeSeller): bool + { + $survivorBuyerId = $this->getSurvivorIdByName($tradeBuyer['name']); + $itemsQtyBuyer = $this->getInventoryItemsQtyBySurvivorId($survivorBuyerId); + + $survivorSellerId = $this->getSurvivorIdByName($tradeSeller['name']); + $itemsQtySeller = $this->getInventoryItemsQtyBySurvivorId($survivorSellerId); + + $tablePoints = $this->getAllTradePoints(); + $itemPoints = $this->getItemPoints($tablePoints); + + $buyerPoints = $this->calculateTradePoints($tradeBuyer, $itemPoints, $itemsQtyBuyer); + $sellerPoints = $this->calculateTradePoints($tradeSeller, $itemPoints, $itemsQtySeller); + + return $buyerPoints == $sellerPoints; + } + /** * @param $trader * @param $itemPoints @@ -200,12 +205,12 @@ public function calculateTradePoints($trader, $itemPoints, $traderInventory) * @param $itemQty * @return bool */ - public function checkIfTraderHasItems($traderInventory, $traderItem, $itemQty) + public function checkIfTraderHasItems($traderInventory, $traderItem, $itemRequestedQty): bool { $result = true; foreach ($traderInventory as $item => $qty) { if ($item == $traderItem) { - if ($itemQty < $qty) { + if ($qty < $itemRequestedQty) { return false; } } @@ -214,6 +219,68 @@ public function checkIfTraderHasItems($traderInventory, $traderItem, $itemQty) return $result; } + /** + * @param $buyerTrade + * @param $sellerTrade + */ + public function updateInventoryTraders($buyerTrade, $sellerTrade) + { + $buyerId = $this->getSurvivorIdByName($buyerTrade['name']); + $buyerInventory = $this->getInventoryItemsQtyBySurvivorId($buyerId); + $sellerId = $this->getSurvivorIdByName($sellerTrade['name']); + $sellerInventory = $this->getInventoryItemsQtyBySurvivorId($sellerId); + $toSellerItems = $this->getToTraderItems($buyerInventory, $buyerTrade); + $toBuyerItems = $this->getToTraderItems($sellerInventory, $sellerTrade); + + $this->updateFinalTraderInventory($buyerInventory, $toBuyerItems, $buyerId); + $this->updateFinalTraderInventory($sellerInventory, $toSellerItems, $sellerId); + } + + /** + * @param $traderInventory + * @param $trade + * @return array + */ + public function getToTraderItems(&$traderInventory, $trade): array + { + $result = []; + + foreach ($traderInventory as $itemTrader => $qtyTrader) { + foreach ($trade as $itemTrade => $qtyTrade) { + if ($itemTrader != $itemTrade) { + continue; + } + $traderInventory[$itemTrader] = $traderInventory[$itemTrader] - $qtyTrade; + $result[$itemTrader] = $qtyTrade; + } + } + + return $result; + } + + /** + * @param $inventory + * @param $items + * @param $survivorId + */ + public function updateFinalTraderInventory($inventory, $items, $survivorId) + { + $temporaryInventory = ['id_survivor' => $survivorId]; + foreach ($inventory as $key => $value) { + if ($key == 'name') { + continue; + } + foreach ($items as $item => $qty) { + if ($key == $item) { + $value = $inventory[$key] + $qty; + } + } + $temporaryInventory['item'] = $key; + $temporaryInventory['qty'] = $value; + $this->updateInventory($temporaryInventory); + } + } + /** * @param $a * @param $b @@ -237,4 +304,5 @@ public function runBadRequest() echo "Bad Request"; exit(); } -} \ No newline at end of file +} + diff --git a/src/DatabaseManager/InventoryConnection.php b/src/DatabaseManager/InventoryConnection.php index 13e06dc..70050db 100644 --- a/src/DatabaseManager/InventoryConnection.php +++ b/src/DatabaseManager/InventoryConnection.php @@ -31,7 +31,11 @@ public function selectAll() } } - public function selectBySurvivorId(array $input) + /** + * @param $survivorId + * @return mixed + */ + public function selectBySurvivorId($survivorId) { $stmt = " SELECT @@ -42,14 +46,8 @@ public function selectBySurvivorId(array $input) "; try { $stmt = $this->db->prepare($stmt); - - $stmt->execute( - [ - 'id_survivor' => $input['id_survivor'], - 'item' => $input['item'], - 'qty' => $input['qty'], - ] - ); + $stmt->bindParam(':id_survivor', $survivorId, \PDO::PARAM_INT); + $stmt->execute(); return $stmt->fetchAll(\PDO::FETCH_ASSOC); } catch (\PDOException $e) { @@ -72,34 +70,30 @@ public function insert(array $input) 'qty' => $input['qty'], ] ); - } catch (\PDOException $e) { exit($e->getMessage()); } } - public function update($id_survivor, array $input) + public function update(array $input) { $stmt = " UPDATE $this->tbName SET - id_survivor = :id_survivor - item = :item + id_survivor = :id_survivor, + item = :item, qty = :qty WHERE - id_survivor = :id_survivor; + id_survivor = :id_survivor + AND + item = :item; "; try { $stmt = $this->db->prepare($stmt); - $stmt->execute( - [ - 'id_survivor' => $input['id_survivor'], - 'item' => $input['item'], - 'qty' => $input['qty'], - ] - ); - - return $stmt->rowCount(); + $stmt->bindParam(':id_survivor', $input['id_survivor'], \PDO::PARAM_INT); + $stmt->bindParam(':item', $input['item'], \PDO::PARAM_STR); + $stmt->bindParam(':qty', $input['qty'], \PDO::PARAM_INT); + $stmt->execute(); } catch (\PDOException $e) { exit($e->getMessage()); } diff --git a/src/EntityDbHelper/DbHelper/InventoryHelper.php b/src/EntityDbHelper/DbHelper/InventoryHelper.php index 68f059b..6989110 100644 --- a/src/EntityDbHelper/DbHelper/InventoryHelper.php +++ b/src/EntityDbHelper/DbHelper/InventoryHelper.php @@ -54,7 +54,11 @@ public function addNewInventory($inventory) } } - public function getInventoryItemsQty($inventory) + /** + * @param $inventory + * @return array + */ + public function getInventoryItemsQty($inventory): array { $itemQty = []; foreach ($inventory as $value) { diff --git a/src/EntityDbHelper/DbHelper/SurvivorHelper.php b/src/EntityDbHelper/DbHelper/SurvivorHelper.php index a8effa6..9d9e1a7 100644 --- a/src/EntityDbHelper/DbHelper/SurvivorHelper.php +++ b/src/EntityDbHelper/DbHelper/SurvivorHelper.php @@ -56,6 +56,5 @@ public function updateSurvivor($survivor) { $this->survivorConnection->update($survivor); } - } From bf9254b23d409d5f966356d47293872b3a9e8329 Mon Sep 17 00:00:00 2001 From: "Franco.vitelli" Date: Fri, 9 Jul 2021 11:56:18 +0200 Subject: [PATCH 23/23] Updated .gitignore --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index cbb9fa6..fd59ba4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /.docker/db -/.env \ No newline at end of file +/.env +/vendor \ No newline at end of file