Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
6.9 kB
1
Indexable
Never
<?php
/**
   * Tells the browser to allow code from any origin to access
   */

  header("Access-Control-Allow-Origin: *");

  /**
   * Tells browsers whether to expose the response to the frontend JavaScript code
   * when the request's credentials mode (Request.credentials) is include
   */
  header("Access-Control-Allow-Credentials: true");
 /**
   * Specifies one or more methods allowed when accessing a resource in response to a preflight request
   */
  header("Access-Control-Allow-Methods: POST, GET, PUT, DELETE");
 
  /**
   * Used in response to a preflight request which includes the Access-Control-Request-Headers to
   * indicate which HTTP headers can be used during the actual request
   */
  header("Access-Control-Allow-Headers: Content-Type");

  require_once('MysqliDb.php');
  class API {
    public $db;
    public function __construct() {
        $this->db = new MysqliDb('localhost', 'root', '', 'employee');
    }

    /**
       * HTTP GET Request
       *
       * @param $payload
       */
      public function httpGet($payload = array())
      {
       
          // execute query
          $query = $this->db->get('information');
       
          // check if query is success or fail
          if ($query) {
            return json_encode(array(
                'method' => 'GET',
                'status' => 'success',
                'data' => $query,
            ));
        } else {
            return json_encode(array(
                'method' => 'GET',
                'status' => 'fail',
                'data' => [],
                'message' => 'ID does not exist'
            ));
        }
    }

   /**
       * HTTP POST Request
       *
       * @param $payload
       */
      public function httpPost($payload)
      {
          // Check if payload contains null values
          foreach ($payload as $value) {
              if ($value === null) {
                  return json_encode(array(
                      'method' => 'POST',
                      'status' => 'fail',
                      'data' => [],
                      'message' => 'Payload contains null values'
                  ));
              }
          }
      
          //Execute Query
          $payload['id'] = $this->db->insert('information', $payload);
      
          //check if query is success or fail
          if ($payload) {
              return json_encode(array(
                  'method' => 'POST',
                  'status' => 'success',
                  'data' => $payload,
              ));
          } else {
              return  json_encode(array(
                  'method' => 'POST',
                  'status' => 'fail',
                  'data' => [],
                  'message' => 'Failed to Insert'
              ));
          }
      }
      
/**
       * HTTP PUT Request
       *
       * @param $id
       * @param $payload
       */
      public function httpPut($id, $payload)
      {
        //error response
        if(!is_array($payload)){
            return json_encode(array(
                'method' => 'PUT',
                'status' => 'fail',
                'data' => [],
                'message' => 'Failed to update, no existing Id',
            ));
        }
        {
            // Check if the 'id' field in the payload matches the 'id' parameter
            if ($payload['id'] !== $id) {
                return json_encode(array(
                    'method' => 'PUT',
                    'status' => 'fail',
                    'data' => [],
                    'message' => 'Id does not match',
                ));
            }
        }
          // Prepare and execute the query
          $this->db->where('id', $id);
          $query = $this->db->update('information', $payload);      
          $result = $query;
          // Check if the query was successful or not
          if ($result) {
              return json_encode(array(
                  'method' => 'PUT',
                  'status' => 'success',
                  'data' => $payload,
              ));
          } else {
              return json_encode(array(
                  'method' => 'PUT',
                  'status' => 'fail',
                  'data' => [],
                  'message' => 'Failed to update',
              ));
          }
    }
    
      /**
       * HTTP DELETE Request
       *
       * @param $id
       * @param $payload
       */
      public function httpDelete($id, $payload)
      {
        if (empty($id) || !is_numeric($id)) {
            return json_encode(array(
                'method' => 'DELETE',
                'status' => 'fail',
                'data' => [],
                'message' => 'Invalid ID provided'
            ));
        }
          $selected_id = ['id' => is_string($id) ? explode(",", $id) : null];  
// Check if there are any selected ids in the $selected_id array
if (isset($selected_id['id']) && count($selected_id['id'])) {
    // If there are, use the IN operator to search for those specific ids in the 'id' column
    $this->db->where('id', $selected_id['id'], 'IN');
} else {
    // If there are no selected ids, return an error message
    return json_encode(array(
        'method' => 'DELETE',
        'status' => 'fail',
        'data' => [],
        'message' => 'No ID provided'
    ));
}

// Execute query
$query = $this->db->delete('information');

// check if success or fail
if ($query) {
    return json_encode(array(
        'method' => 'DELETE',
        'status' => 'success',
        'data' => $payload,
    ));
} else {
    return json_encode(array(
        'method' => 'DELETE',
        'status' => 'fail',
        'data' => [],
        'message' => 'Failed to Delete'
    ));
          }
      }
  }  
/*
 //Identifier if what type of request
 $request_method = $_SERVER['REQUEST_METHOD'];

 // For GET,POST,PUT & DELETE Request
  if ($request_method === 'GET') {
      $received_data = $_GET;
  } else {
      //check if method is PUT or DELETE, and get the ids on URL
      if ($request_method === 'PUT' || $request_method === 'DELETE') {
          $request_uri = $_SERVER['REQUEST_URI'];


          $ids = null;
          $exploded_request_uri = array_values(explode("/", $request_uri));


          $last_index = count($exploded_request_uri) - 1;


          $ids = $exploded_request_uri[$last_index];


          }
      }


      //payload data
      $received_data = json_decode(file_get_contents('php://input'), true);
    
    $api = new API;
 //Checking if what type of request and designating to specific functions
  switch ($request_method) {
      case 'GET':
          $api->httpGet($received_data);
          break;
      case 'POST':
          $api->httpPost($received_data);
          break;
      case 'PUT':
          $api->httpPut($ids, $received_data);
          break;
      case 'DELETE':
          $api->httpDelete($ids, $received_data);
          break;
  }
*/
?>