Advertisement
Beewan2608

Code

Jul 5th, 2024
761
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 9.50 KB | Source Code | 0 0
  1. <?php
  2.  
  3. namespace App\Controllers;
  4.  
  5. use App\Controllers\BaseController;
  6. use App\Plugins\Http\Exceptions;
  7. use App\Plugins\Http\Response as Status;
  8. use PDO;
  9. use PDOException;
  10.  
  11. class FacilityController extends BaseController
  12. {
  13.     public function __construct()
  14.     {
  15.         SELF::validateapi();
  16.     }
  17.  
  18.     /**
  19.      * @param int $cursor
  20.      * @param int $limit
  21.      * @param string $search
  22.      */
  23.     public function index()
  24.     {
  25.         // Validate and sanitize cursor
  26.         $cursor = isset($_REQUEST['cursor']) ? intval($_REQUEST['cursor']) : null;
  27.         if ($cursor !== null  && !is_int($cursor)) {
  28.             (new Status\BadRequest(['message' => 'Invalid Cursor']))->send();
  29.             exit();
  30.         }
  31.         // Validate and sanitize limit
  32.         $limit = isset($_REQUEST['limit']) ? intval($_REQUEST['limit']) : 10;
  33.         if ($limit <= 0) {
  34.             (new Status\BadRequest(['message' => 'Limit should be a positive number']))->send();
  35.         }
  36.         //validate and sanitize search
  37.         $search = (isset($_REQUEST['search']) && !empty($_REQUEST['search']) ? SELF::sanitizeString($_REQUEST['search']) : "");
  38.  
  39.         // Fetch facility details with cursor pagination
  40.         $facilities = SELF::getFacilityDetails($cursor, $limit, $search);
  41.  
  42.         // Extract the last facility's ID as the cursor for the next page
  43.         $nextCursor = null;
  44.  
  45.         if (!empty($facilities)) {
  46.  
  47.             $lastfacility = end($facilities);
  48.             $nextCursor = $lastfacility['facility_id'];
  49.         }
  50.         // (new Status\Ok(['data' => $facilities]))->send();
  51.         (new Status\Ok(['data' => $facilities, "next_cursor" => $nextCursor]))->send();
  52.     }
  53.  
  54.     /**
  55.      * Controller function to Create Facility API
  56.      * @param string $name
  57.      * @param string $tag_name
  58.      */
  59.     public function create()
  60.     {
  61.         if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  62.             // Get the data from the request body
  63.             $data = json_decode(file_get_contents('php://input'), true);
  64.             $validatedRequest = SELF::ValidateRequest($data);
  65.             if ($validatedRequest) {
  66.                 // validate and clean data    
  67.                 $facilityname = isset($data['name']) && !empty($data['name']) ? SELF::sanitizeString($data['name']) : "";
  68.                 $tag_name = isset($data['tag_name']) && !empty($data['tag_name']) ? SELF::sanitizeString($data['tag_name']) : "";
  69.                 $datatime = date('Y-m-d H:i:s');
  70.  
  71.                 //Get Tag ID
  72.                 $TagId = SELF::getTag($tag_name);
  73.                 if (empty($TagId)) {
  74.                     (new Status\BadRequest(['message' => 'Tag id is not avaliable']))->send();
  75.                     exit();
  76.                 }
  77.                 // Get the Location ID    
  78.                 $LocationId = SELF::setLocation($data);
  79.                 if (empty($LocationId)) {
  80.                     (new Status\BadRequest(['message' => 'Location Id is not avaliable']))->send();
  81.                     exit();
  82.                 }
  83.  
  84.                 //Insert in Facility table
  85.                 $query = "INSERT INTO facility (name, creation_date, location_id)
  86.                    VALUES (?,?,?)";
  87.                 $bind = array($facilityname, $datatime, $LocationId);
  88.                 // Execute query
  89.                 $result = $this->db->executeQuery($query, $bind);
  90.                 $FacilityId = $this->db->getLastInsertedId();
  91.                 if (empty($FacilityId)) {
  92.                     (new Status\BadRequest(['message' => 'Somthing went wrong']))->send();
  93.                     exit();
  94.                 }
  95.  
  96.                 //Insert in Facility tag table            
  97.                 $query = "INSERT INTO facility_tag (facility_id,tag_id)
  98.                VALUES (?,?)";
  99.                 $bind = array($FacilityId, $TagId);
  100.                 $this->db->executeQuery($query, $bind);
  101.  
  102.                 // Respond with 200 (OK):
  103.                 (new Status\Ok(['message' => 'Added Successfully!']))->send();
  104.             }
  105.         } else {
  106.             // Respond with 400 (BadRequest):
  107.             (new Status\BadRequest(['message' => 'Whoops! Something went wrong!']))->send();
  108.         }
  109.     }
  110.  
  111.     /**
  112.      * Function to Get Facility details
  113.      */
  114.     function getFacilityDetails($cursor = null, $limit = 10, $search = "")
  115.     {
  116.         $query = "SELECT f.facility_id, f.name AS facility_name, tag.tag_id,
  117.          tag.tag_name, loc.location_id, loc.city, loc.address, loc.zip_code,
  118.          loc.country_code, loc.phone_number
  119.          FROM facility f
  120.          LEFT JOIN facility_Tag ft ON f.facility_id = ft.facility_id
  121.          LEFT JOIN tag ON ft.tag_id = tag.tag_id
  122.          LEFT JOIN location loc ON f.location_id = loc.location_id
  123.          WHERE f.name LIKE :search OR tag.tag_name LIKE :search ";
  124.         if ($cursor) {
  125.             $query .= ' and f.facility_id > :cursor ';
  126.         }
  127.         $query .= "ORDER BY f.facility_id ASC LIMIT $limit";
  128.  
  129.         $bind = array(':cursor' => $cursor, ':search' => '%' . $search . '%');
  130.  
  131.         // Execute the query
  132.         $reult = $this->db->executeQuery($query, $bind);
  133.  
  134.         // Fetch all rows as an associative array
  135.         $facilities = $this->db->getStatement()->fetchAll(PDO::FETCH_ASSOC);
  136.         return $facilities;
  137.     }
  138.  
  139.     /**
  140.      * Tag Methods
  141.      */
  142.     function getTag($tagName)
  143.     {
  144.         try {
  145.             $tag_query = "SELECT tag_id from tag where tag_name = '" . $tagName . "'";
  146.             $bind = array();
  147.             $this->db->executeQuery($tag_query, $bind);
  148.             $results = $this->db->getStatement()->fetch(PDO::FETCH_ASSOC);
  149.             // print_r( $results)   exit();
  150.             if (isset($results['tag_id']) && !empty($results['tag_id'])) {
  151.                 return $results['tag_id'];
  152.             } else {
  153.                 $query =   "INSERT INTO tag (tag_name)
  154.                     VALUES (?)";
  155.                 $bind = array($tagName);
  156.                 $this->db->executeQuery($query, $bind);
  157.                 return $this->db->getLastInsertedId();
  158.             }
  159.         } catch (PDOException $e) {
  160.             // GetMessage to throw
  161.             $ErrorMessage = $e->getMessage(); // Get the error message from the exception
  162.             // Log the error or return it to the client  
  163.             (new Status\BadRequest(['Error' => $ErrorMessage]))->send();
  164.         }
  165.     }
  166.  
  167.     /**
  168.      * To get location
  169.      * @param string $address
  170.      * @param string $city
  171.      * @param string $zip_code
  172.      * @param string $phone_number
  173.      * @param string $country_code
  174.      */
  175.     function setLocation($data)
  176.     {
  177.         try {
  178.             //Fetching required data for Location
  179.             $address = isset($data['address']) && !empty($data['address']) ? SELF::sanitizeString($data['address']) : "";
  180.             $city = isset($data['city']) && !empty($data['city']) ? SELF::sanitizeString($data['city']) : "";
  181.             $zip_code = isset($data['zip_code']) && !empty($data['zip_code']) ? SELF::sanitizeString($data['zip_code']) : "";
  182.             $phone_number = isset($data['phone_number']) && !empty($data['phone_number']) ? SELF::sanitizeString($data['phone_number']) : "";
  183.             $country_code = isset($data['country_code']) && !empty($data['country_code']) ? SELF::sanitizeString($data['country_code']) : "";
  184.             $currentdatetime = date('Y-m-d H:i:s');
  185.             //Query to insert in Location
  186.             $query =  "INSERT INTO location (city,address,zip_code,country_code,phone_number,creation_date)
  187.            VALUES (?,?,?,?,?,?)";
  188.             $bind = array($city, $address, $zip_code, $country_code, $phone_number, $currentdatetime);
  189.             //Execute Query  
  190.             $this->db->executeQuery($query, $bind);
  191.             return $this->db->getLastInsertedId();
  192.         } catch (PDOException $e) {
  193.             // GetMessage to throw
  194.             $ErrorMessage = $e->getMessage(); // Get the error message from the exception
  195.             // Log the error or return it to the client  
  196.             (new Status\BadRequest(['Error' => $ErrorMessage]))->send();
  197.         }
  198.     }
  199.     /**
  200.      * Validate Request
  201.      */
  202.     function  ValidateRequest($data)
  203.     {
  204.         $errors = [];
  205.  
  206.         if (!isset($data['name']) || empty($data['name'])) {
  207.             $errors['name'] = "Facility name is required";
  208.         }
  209.         if (!isset($data['tag_name']) || empty($data['tag_name'])) {
  210.             $errors['tag_name'] = "Tag name is required";
  211.         }
  212.         if (!isset($data['address']) || empty($data['address'])) {
  213.             $errors['address'] = "Address is required";
  214.         }
  215.         if (!isset($data['city']) || empty($data['city'])) {
  216.             $errors['city'] = "City name is required";
  217.         }
  218.         if (!isset($data['zip_code']) || empty($data['zip_code'])) {
  219.             $errors['zip_code'] = "Zip code is required";
  220.         }
  221.         if (!isset($data['phone_number']) || empty($data['phone_number'])) {
  222.             $errors['phone_number'] = "Phone number is required";
  223.         }
  224.         if (!isset($data['country_code']) || empty($data['country_code'])) {
  225.             $errors['country_code'] = "Country code is required";
  226.         }
  227.         if (!empty($errors)) {
  228.             (new Status\BadRequest(['message' => $errors]))->send();
  229.             exit();
  230.         }
  231.         return true;
  232.     }
  233.     /**
  234.      * sanitize input string for prevention of xss attack
  235.      */
  236.     public function sanitizeString($input)
  237.     {
  238.         return  htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
  239.     }
  240. }
  241.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement