[Fix:#6] Get tasks from a given user id
parent
97088a6142
commit
3925592ade
|
@ -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');
|
||||
});
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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
|
||||
|
|
Loading…
Reference in New Issue