Refactor service definition

pull/16/head
sundowndev 2018-08-05 01:17:58 +02:00
parent fbc45a0557
commit 6a0f72f271
8 changed files with 105 additions and 97 deletions

View File

@ -0,0 +1,53 @@
<?php
namespace App\Controller;
use App\Service\Database;
use App\Service\JsonResponse;
use App\Service\Request;
use App\Service\Session;
/**
* Class Controller
* @package App\Controller
*/
class Controller
{
/**
* @var Database
*/
protected $db;
/**
* @var JsonResponse
*/
protected $jsonResponse;
/**
* @var Request
*/
protected $request;
/**
* @var Session
*/
protected $session;
/**
* @var \App\Service\Security
*/
protected $security;
/**
* Controller constructor.
*/
public function __construct()
{
$this->db = new Database();
$this->request = new Request();
$this->jsonResponse = new JsonResponse();
$this->session = new Session($this->db, $this->jsonResponse);
$this->security = $this->session->security;
}
}

View File

@ -2,23 +2,14 @@
namespace App\Controller; namespace App\Controller;
use App\Service\JsonResponse; class DefaultController extends Controller
class DefaultController
{ {
private $jsonResponse;
public function __construct()
{
$this->jsonResponse = new JsonResponse();
}
/** /**
* API homepage * API homepage
*/ */
public function index() public function index()
{ {
print $this->jsonResponse->create(200, 'Hello! :)'); return $this->jsonResponse->create(200, 'Hello! :)');
} }
/** /**
@ -26,6 +17,6 @@ class DefaultController
*/ */
public function error() public function error()
{ {
print $this->jsonResponse->create(404, 'Resource not found.'); return $this->jsonResponse->create(404, 'Resource not found.');
} }
} }

View File

@ -4,30 +4,18 @@ namespace App\Controller;
use App\Repository\SessionRepository; use App\Repository\SessionRepository;
use App\Repository\UserRepository; use App\Repository\UserRepository;
use App\Service\Database;
use App\Service\JsonResponse;
use App\Service\Request;
use App\Service\Session;
class SessionController class SessionController extends Controller
{ {
private $db;
private $jsonResponse;
private $sessionRepository;
private $request;
private $session;
private $security;
private $userRepository; private $userRepository;
private $sessionRepository;
public function __construct() public function __construct()
{ {
$this->db = new Database(); parent::__construct();
$this->request = new Request();
$this->jsonResponse = new JsonResponse();
$this->session = new Session($this->db, $this->jsonResponse);
$this->security = $this->session->security;
$this->sessionRepository = new SessionRepository($this->db, $this->security);
$this->userRepository = new UserRepository($this->db); $this->userRepository = new UserRepository($this->db);
$this->sessionRepository = new SessionRepository($this->db, $this->security);
} }
/** /**
@ -38,15 +26,13 @@ class SessionController
$body = $this->request->getContent()->jsonToArray(); $body = $this->request->getContent()->jsonToArray();
if (empty($body['username']) || empty($body['password'])) { if (empty($body['username']) || empty($body['password'])) {
print $this->jsonResponse->create(400, 'Please provide an username and password.'); return $this->jsonResponse->create(400, 'Please provide an username and password.');
exit();
} }
$user = $this->userRepository->findOneByUsername($body['username']); $user = $this->userRepository->findOneByUsername($body['username']);
if (is_null($user) || !$this->security->passwordVerify($body['password'], $user['password'])) { if (is_null($user) || !$this->security->passwordVerify($body['password'], $user['password'])) {
print $this->jsonResponse->create(403, 'Bad credentials.'); return $this->jsonResponse->create(403, 'Bad credentials.');
exit();
} }
$token = $this->security->generateToken($user['id']); $token = $this->security->generateToken($user['id']);
@ -56,7 +42,7 @@ class SessionController
$this->sessionRepository->create($user['id'], $token, $expire_at->format('Y-m-d H:i:s'), $_SERVER['REMOTE_ADDR']); $this->sessionRepository->create($user['id'], $token, $expire_at->format('Y-m-d H:i:s'), $_SERVER['REMOTE_ADDR']);
print $this->jsonResponse->create(200, 'Welcome ' . $user['name'], [ return $this->jsonResponse->create(200, 'Welcome ' . $user['name'], [
'token' => $token, 'token' => $token,
'expire_at' => $expire_at, 'expire_at' => $expire_at,
]); ]);
@ -70,8 +56,7 @@ class SessionController
$body = $this->request->getContent()->jsonToArray(); $body = $this->request->getContent()->jsonToArray();
if (empty($body['username']) || empty($body['email']) || empty($body['password'])) { if (empty($body['username']) || empty($body['email']) || empty($body['password'])) {
print $this->jsonResponse->create(400, 'Please provide an username, email and password.'); return $this->jsonResponse->create(400, 'Please provide an username, email and password.');
exit();
} }
$user = [ $user = [
@ -81,13 +66,12 @@ class SessionController
]; ];
if (!is_null($this->userRepository->findOneByEmail($user['email']))) { if (!is_null($this->userRepository->findOneByEmail($user['email']))) {
print $this->jsonResponse->create(403, 'Email already registered!'); return $this->jsonResponse->create(403, 'Email already registered!');
exit();
} }
$this->userRepository->create($user['username'], $user['email'], $user['password']); $this->userRepository->create($user['username'], $user['email'], $user['password']);
print $this->jsonResponse->create(200, 'Success. Now send your credentials to /auth to sign in.', [ return $this->jsonResponse->create(200, 'Success. Now send your credentials to /auth to sign in.', [
'username' => $user['username'], 'username' => $user['username'],
'email' => $user['email'], 'email' => $user['email'],
]); ]);
@ -99,13 +83,12 @@ class SessionController
public function signout() public function signout()
{ {
if (!$this->security->isLogged()) { if (!$this->security->isLogged()) {
print $this->security->NotAllowedRequest(); return $this->security->NotAllowedRequest();
exit();
} }
$this->sessionRepository->deleteByToken($this->security->getBearerToken()); $this->sessionRepository->deleteByToken($this->security->getBearerToken());
print $this->jsonResponse->create(200, 'Good bye.', []); return $this->jsonResponse->create(200, 'Good bye.', []);
} }
/** /**
@ -114,10 +97,9 @@ class SessionController
public function me() public function me()
{ {
if (!$this->security->isLogged()) { if (!$this->security->isLogged()) {
print $this->security->NotAllowedRequest(); return $this->security->NotAllowedRequest();
exit();
} }
print $this->jsonResponse->create(200, 'hello!', $this->session->getUser()); return $this->jsonResponse->create(200, 'hello!', $this->session->getUser());
} }
} }

View File

@ -2,33 +2,21 @@
namespace App\Controller; namespace App\Controller;
use App\Service\JsonResponse;
use App\Service\Database;
use App\Repository\TaskRepository; use App\Repository\TaskRepository;
use App\Service\Request;
use App\Service\Session;
/** /**
* Class TaskController * Class TaskController
* @package App\Controller * @package App\Controller
*/ */
class TaskController class TaskController extends Controller
{ {
private $db;
private $request;
private $jsonResponse;
private $session;
private $security;
private $repository; private $repository;
public function __construct() public function __construct()
{ {
$this->db = new Database(); parent::__construct();
$this->request = new Request();
$this->jsonResponse = new JsonResponse();
$this->repository = new TaskRepository($this->db); $this->repository = new TaskRepository($this->db);
$this->session = new Session($this->db, $this->jsonResponse);
$this->security = $this->session->security;
} }
/** /**
@ -43,7 +31,7 @@ class TaskController
$message = "Here are the tasks!"; $message = "Here are the tasks!";
$data = $this->repository->findAll(); $data = $this->repository->findAll();
print $this->jsonResponse->create($code, $message, $data); return $this->jsonResponse->create($code, $message, $data);
} }
/** /**
@ -58,7 +46,7 @@ class TaskController
$code = ($data != null) ? 200 : 404; $code = ($data != null) ? 200 : 404;
$message = ($data != null) ? "Task found." : "Task not found."; $message = ($data != null) ? "Task found." : "Task not found.";
print $this->jsonResponse->create($code, $message, $data); return $this->jsonResponse->create($code, $message, $data);
} }
/** /**
@ -70,8 +58,7 @@ class TaskController
public function post() public function post()
{ {
if (!$this->security->isLogged()) { if (!$this->security->isLogged()) {
print $this->security->NotAllowedRequest(); return $this->security->NotAllowedRequest();
exit();
} }
$body = $this->request->getContent()->jsonToArray(); $body = $this->request->getContent()->jsonToArray();
@ -80,8 +67,7 @@ class TaskController
$code = 400; $code = 400;
$message = 'Bad parameters.'; $message = 'Bad parameters.';
print $this->jsonResponse->create($code, $message); return $this->jsonResponse->create($code, $message);
exit();
} }
$user = $this->session->getUser(); $user = $this->session->getUser();
@ -97,7 +83,7 @@ class TaskController
$message = 'Success!'; $message = 'Success!';
$data = $task; $data = $task;
print $this->jsonResponse->create($code, $message, $data); return $this->jsonResponse->create($code, $message, $data);
} }
/** /**
@ -109,16 +95,14 @@ class TaskController
public function put($id) public function put($id)
{ {
if (!$this->security->isLogged()) { if (!$this->security->isLogged()) {
print $this->security->NotAllowedRequest(); return $this->security->NotAllowedRequest();
exit();
} }
$task = $this->repository->findOneById($id); $task = $this->repository->findOneById($id);
$user = $this->session->getUser(); $user = $this->session->getUser();
if ($task['user_id'] !== $user['id']) { if ($task['user_id'] !== $user['id']) {
print $this->security->NotAllowedRequest(); return $this->security->NotAllowedRequest();
exit();
} }
$body = $this->request->getContent()->jsonToArray(); $body = $this->request->getContent()->jsonToArray();
@ -133,7 +117,7 @@ class TaskController
$message = "Task edited."; $message = "Task edited.";
$data = $task; $data = $task;
print $this->jsonResponse->create($code, $message, $data); return $this->jsonResponse->create($code, $message, $data);
} }
/** /**
@ -145,16 +129,14 @@ class TaskController
public function delete($id) public function delete($id)
{ {
if (!$this->security->isLogged()) { if (!$this->security->isLogged()) {
print $this->security->NotAllowedRequest(); return $this->security->NotAllowedRequest();
exit();
} }
$task = $this->repository->findOneById($id); $task = $this->repository->findOneById($id);
$user = $this->session->getUser(); $user = $this->session->getUser();
if ($task['user_id'] !== $user['id']) { if ($task['user_id'] !== $user['id']) {
print $this->security->NotAllowedRequest(); return $this->security->NotAllowedRequest();
exit();
} }
$this->repository->deleteById($id); $this->repository->deleteById($id);
@ -163,6 +145,6 @@ class TaskController
$message = "Task deleted."; $message = "Task deleted.";
$data = []; $data = [];
print $this->jsonResponse->create($code, $message, $data); return $this->jsonResponse->create($code, $message, $data);
} }
} }

View File

@ -3,21 +3,17 @@
namespace App\Controller; namespace App\Controller;
use App\Repository\TaskRepository; use App\Repository\TaskRepository;
use App\Service\Database;
use App\Service\JsonResponse;
use App\Repository\UserRepository; use App\Repository\UserRepository;
class UserController class UserController extends Controller
{ {
private $db;
private $jsonResponse;
private $repository; private $repository;
private $taskRepository; private $taskRepository;
public function __construct() public function __construct()
{ {
$this->db = new Database(); parent::__construct();
$this->jsonResponse = new JsonResponse();
$this->repository = new UserRepository($this->db); $this->repository = new UserRepository($this->db);
$this->taskRepository = new TaskRepository($this->db); $this->taskRepository = new TaskRepository($this->db);
} }
@ -34,7 +30,7 @@ class UserController
$code = ($user != null) ? 200 : 404; $code = ($user != null) ? 200 : 404;
$message = ($user != null) ? "User found." : "User not found."; $message = ($user != null) ? "User found." : "User not found.";
print $this->jsonResponse->create($code, $message, [ return $this->jsonResponse->create($code, $message, [
'id' => $user['id'], 'id' => $user['id'],
'username' => $user['name'], 'username' => $user['name'],
'email' => $user['email'], 'email' => $user['email'],
@ -49,12 +45,11 @@ class UserController
$code = ($data != null) ? 200 : 404; $code = ($data != null) ? 200 : 404;
$message = ($data != null) ? "User found." : "User not found."; $message = ($data != null) ? "User found." : "User not found.";
print $this->jsonResponse->create($code, $message, []); return $this->jsonResponse->create($code, $message, []);
exit();
} }
$tasks = $this->taskRepository->findByUserId($id); $tasks = $this->taskRepository->findByUserId($id);
print $this->jsonResponse->create(200, 'Here are the tasks.', $tasks); return $this->jsonResponse->create(200, 'Here are the tasks.', $tasks);
} }
} }

View File

@ -30,7 +30,7 @@ class SessionRepository
* TaskRepository constructor. * TaskRepository constructor.
* @param $db * @param $db
*/ */
public function __construct($db, Security $security) public function __construct(Database $db, Security $security)
{ {
$this->db = $db; $this->db = $db;
$this->security = $security; $this->security = $security;

View File

@ -64,7 +64,7 @@ class UserRepository
public function findOneByUsername($username) public function findOneByUsername($username)
{ {
$stmt = $this->db->getConnection()->prepare('SELECT * FROM ' . $this->tableName . ' WHERE name = :username'); $stmt = $this->db->getConnection()->prepare('SELECT * FROM ' . $this->tableName . ' WHERE name = :username');
$stmt->bindParam(':username', $username, \PDO::PARAM_INT); $stmt->bindParam(':username', $username, \PDO::PARAM_STR);
$stmt->execute(); $stmt->execute();
$user = $stmt->fetch(\PDO::FETCH_ASSOC); $user = $stmt->fetch(\PDO::FETCH_ASSOC);
@ -83,7 +83,7 @@ class UserRepository
public function findOneByEmail($email) public function findOneByEmail($email)
{ {
$stmt = $this->db->getConnection()->prepare('SELECT * FROM ' . $this->tableName . ' WHERE email = :email'); $stmt = $this->db->getConnection()->prepare('SELECT * FROM ' . $this->tableName . ' WHERE email = :email');
$stmt->bindParam(':email', $email, \PDO::PARAM_INT); $stmt->bindParam(':email', $email, \PDO::PARAM_STR);
$stmt->execute(); $stmt->execute();
$user = $stmt->fetch(\PDO::FETCH_ASSOC); $user = $stmt->fetch(\PDO::FETCH_ASSOC);
@ -103,9 +103,9 @@ class UserRepository
public function create($username, $email, $password) public function create($username, $email, $password)
{ {
$stmt = $this->db->getConnection()->prepare('INSERT INTO ' . $this->tableName . ' (`name`, `email`, `password`) VALUES(:name, :email, :password)'); $stmt = $this->db->getConnection()->prepare('INSERT INTO ' . $this->tableName . ' (`name`, `email`, `password`) VALUES(:name, :email, :password)');
$stmt->bindParam(':name', $username); $stmt->bindParam(':name', $username, \PDO::PARAM_STR);
$stmt->bindParam(':email', $email); $stmt->bindParam(':email', $email, \PDO::PARAM_STR);
$stmt->bindParam(':password', $password); $stmt->bindParam(':password', $password, \PDO::PARAM_STR);
$stmt->execute(); $stmt->execute();
} }
} }

View File

@ -8,7 +8,7 @@ namespace App\Service;
*/ */
class JsonResponse class JsonResponse
{ {
public function create(int $code, string $message = null, array $data = []) public function create(int $code, string $message = null, array $data = []): ?string
{ {
$response = [ $response = [
'code' => $code, 'code' => $code,
@ -16,11 +16,16 @@ class JsonResponse
'data' => $data 'data' => $data
]; ];
header('Access-Control-Allow-Origin: ' . getenv('ALLOW_ORIGIN')); //header('Access-Control-Allow-Origin: ' . getenv('ALLOW_ORIGIN'));
header("Access-Control-Allow-Origin: http://localhost:3000");
header("Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization");
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Max-Age: 1');
header('Accept: application/json'); header('Accept: application/json');
header('Content-Type: application/json'); header('Content-Type: application/json');
http_response_code($code); http_response_code($code);
return json_encode($response); print json_encode($response);
exit();
} }
} }