Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Controllers;
- use Exceptions\RestParameterException;
- use Models\User;
- class UserController extends ControllerBase
- {
- public function getUserById()
- {
- $response = $this->response;
- try {
- $id = $this->getJsonParameterFromPost('user_id', 'int', true);
- $user = User::findFirst(
- [
- "id = :id:",
- "bind" => [
- "id" => $id
- ]
- ]
- );
- if ($user) {
- $response->setStatusCode(200, "OK");
- $response->setJsonContent($user);
- } else {
- $response->setStatusCode(404, "Not found");
- $response->setJsonContent(array('status' => 'ERROR', 'messages' => "User you are looking for doesn't exist"));
- }
- } catch (\Exception $e) {
- $response = $this->getExceptionResponse($e);
- } finally {
- return $response;
- }
- }
- public function getUsersByLink(){
- $response = $this->response;
- try {
- $link = $this->getJsonParameterFromPost('link', 'string', true);
- $users = User::find(
- [
- "link = :link:",
- "bind" => [
- "link" => $link
- ]
- ]
- );
- if (sizeof($users)>0) {
- $response->setStatusCode(200, "OK");
- $response->setJsonContent($users);
- } else {
- $response->setStatusCode(404, "Not found");
- $response->setJsonContent(array('status' => 'ERROR', 'messages' => "Users you are looking for with that link don't exist"));
- }
- } catch (\Exception $e) {
- $response = $this->getExceptionResponse($e);
- } finally {
- return $response;
- }
- }
- public function registerNewUser()
- {
- $response = $this->response;
- try {
- $name = $this->getJsonParameterFromPost('name', 'string', true);
- $university_id = $this->getJsonParameterFromPost('university_id', 'int', true);
- $link = $this->getJsonParameterFromPost('link', 'string', true);
- $user = User::findFirst(
- [
- "name = :name: AND link=:link:",
- "bind" => [
- "name" => $name,
- "link" => $link
- ]
- ]
- );
- if ($user) {
- $response->setStatusCode(409, "Conflict");
- $response->setJsonContent(array('status' => 'ERROR', 'messages' => 'Such user already exists!'));
- return;
- }
- $user = new User();
- $user->name = $name;
- $user->link = $link;
- $user->university_id = $university_id;
- if ($user->save()) {
- $response->setStatusCode(201, "Created");
- $response->setJsonContent(array(
- 'status' => 'SUCCESS',
- 'messages' => 'Successfully registered a new user!',
- 'user'=>$user));
- } else {
- $response->setStatusCode(500, "Unexpected error");
- $response->setJsonContent(array('status' => 'ERROR', 'messages' => 'Something went wrong, user not registered!'));
- }
- } catch (\Exception $e) {
- $response = $this->getExceptionResponse($e);
- } finally {
- return $response;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement