UsersController.php 2.78 KB
<?php

class UsersController {

    private $requestMethod;
    private $params;

    public function __construct($requestMethod, $params=null)
    {
        $this->requestMethod = $requestMethod;
        $this->params = $params;
    }

    public function processRequest()
    {
        switch ($this->requestMethod) {
            case 'GET':
                if (isset($this->params)) {
                    $response = $this->getUserById(($this->params)[0]);
                }else{
                    $response = $this->getAllUsers();
                }
                break;
            case 'POST':
                $response = $this->createUser($_POST['name'], $_POST['email']);
                break;
            case 'DELETE':
                if (isset($this->params)) {
                    $response = $this->deleteUser(($this->params)[0]);
                }
                break;
            case 'PUT':
                if (isset($this->params)) {
                    $response = $this->editUser(($this->params)[0], ($this->params)[1], ($this->params)[2]);
                }
                break;
            default:
                $response = $this->notFoundResponse();
                break;
        }
        header($response['status_code_header']);
        if ($response['body']) {
            echo $response['body'];
        }
    }

    private function createUser($name, $email)
    {
        $user = UserModel::createUser($name, $email);
        $response =[];
        $response['status_code_header']=http_response_code(200);
        $response['body'] = "User created";
        return $response;
    }

    private function editUser($id, $name, $email)
    {
        $user = UserModel::editUser($id, $name, $email);
        $response =[];
        $response['status_code_header']=http_response_code(200);
        $response['body'] = "User updated";
        return $response;
    }

    private function deleteUser($id)
    {
        $user = UserModel::deleteUser($id);
        $response =[];
        $response['status_code_header']=http_response_code(200);
        $response['body'] = "User deleted";
        return $response; 
    }

    private function getUserById($id)
    {
        $user = UserModel::getUserById($id);
        $response =[];
        $response['status_code_header']=http_response_code(200);
        $response['body'] = json_encode($user);
        return $response; 
    }

    private function getAllUsers()
    {
        $users = UserModel::getAllUsers();
        $response =[];
        $response['status_code_header']=http_response_code(200);
        $response['body'] = json_encode($users);
        return $response;
    }

    private function notFoundResponse()
    {
        $response['status_code_header'] = 'HTTP/1.1 404 Not Found';
        $response['body'] = null;
        return $response;
    }
}