[Fix:#6] Get tasks from a given user id

pull/13/head
sundowndev 2018-07-26 17:11:22 +02:00
parent 97088a6142
commit 3925592ade
3 changed files with 70 additions and 8 deletions

View File

@ -72,13 +72,9 @@ $router->mount('/tasks', function () use ($router) {
* User resource
*/
$router->mount('/users', function () use ($router) {
// Create user (register)
$router->post('/', 'DefaultController@index');
// Get one user
$router->get('/(\d+)', 'DefaultController@index');
$router->get('/(\d+)', 'UserController@get');
// Get one task's tasks
$router->get('/(\d+)/tasks', 'DefaultController@index');
});
$router->get('/(\d+)/tasks', 'UserController@getTasks');
});

View File

@ -2,7 +2,59 @@
namespace App\Controller;
use App\Repository\TaskRepository;
use App\Service\Database;
use App\Service\JsonResponse;
use App\Repository\UserRepository;
class UserController
{
//
private $db;
private $jsonResponse;
private $repository;
private $taskRepository;
public function __construct()
{
$this->db = new Database();
$this->jsonResponse = new JsonResponse();
$this->repository = new UserRepository($this->db);
$this->taskRepository = new TaskRepository($this->db);
}
/**
* Get user by id
*
* Route: /users/$id
* Method: GET
*/
public function get($id)
{
$user = $this->repository->findOneById($id) ?? [];
$code = ($user != null) ? 200 : 404;
$message = ($user != null) ? "User found." : "User not found.";
print $this->jsonResponse->create($code, $message, [
'id' => $user['id'],
'username' => $user['name'],
'email' => $user['email'],
]);
}
public function getTasks($id)
{
$user = $this->repository->findOneById($id) ?? [];
if (is_null($user)) {
$code = ($data != null) ? 200 : 404;
$message = ($data != null) ? "User found." : "User not found.";
print $this->jsonResponse->create($code, $message, []);
exit();
}
$tasks = $this->taskRepository->findByUserId($id);
print $this->jsonResponse->create(200, 'Here are the tasks.', $tasks);
}
}

View File

@ -58,6 +58,20 @@ class TaskRepository
}
}
public function findByUserId($userId){
$stmt = $this->db->getConnection()->prepare('SELECT * FROM ' . $this->tableName . ' WHERE user_id = :user_id');
$stmt->bindParam(':user_id', $userId, \PDO::PARAM_INT);
$stmt->execute();
$task = $stmt->fetchAll(\PDO::FETCH_ASSOC);
if (!$task) {
return null;
} else {
return $task;
}
}
/**
* @param $data
* @return mixed