/
TaskService.php
93 lines (78 loc) · 2.69 KB
/
TaskService.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php declare(strict_types=1);
namespace App\Service;
use App\Exception\TaskException;
use App\Repository\TaskRepository;
class TaskService extends BaseService
{
/**
* @var TaskRepository
*/
protected $taskRepository;
public function __construct(TaskRepository $taskRepository)
{
$this->taskRepository = $taskRepository;
}
protected function getTaskRepository(): TaskRepository
{
return $this->taskRepository;
}
protected function checkAndGetTask(int $taskId, int $userId)
{
return $this->getTaskRepository()->checkAndGetTask($taskId, $userId);
}
public function getTasks(int $userId): array
{
return $this->getTaskRepository()->getTasks($userId);
}
public function getTask(int $taskId, int $userId)
{
return $this->checkAndGetTask($taskId, $userId);
}
public function searchTasks(string $tasksName, int $userId): array
{
return $this->getTaskRepository()->searchTasks($tasksName, $userId);
}
public function createTask(array $input)
{
$task = new \stdClass();
$data = json_decode(json_encode($input), false);
if (empty($data->name)) {
throw new TaskException('The field "name" is required.', 400);
}
$task->name = self::validateTaskName($data->name);
$task->description = null;
if (isset($data->description)) {
$task->description = $data->description;
}
$task->status = 0;
if (isset($data->status)) {
$task->status = self::validateTaskStatus($data->status);
}
$task->userId = $data->decoded->sub;
return $this->getTaskRepository()->createTask($task);
}
public function updateTask(array $input, int $taskId)
{
$task = $this->checkAndGetTask($taskId, (int) $input['decoded']->sub);
$data = json_decode(json_encode($input), false);
if (!isset($data->name) && !isset($data->status)) {
throw new TaskException('Enter the data to update the task.', 400);
}
if (isset($data->name)) {
$task->name = self::validateTaskName($data->name);
}
if (isset($data->description)) {
$task->description = $data->description;
}
if (isset($data->status)) {
$task->status = self::validateTaskStatus($data->status);
}
$task->userId = $data->decoded->sub;
return $this->getTaskRepository()->updateTask($task);
}
public function deleteTask(int $taskId, int $userId): string
{
$this->checkAndGetTask($taskId, $userId);
return $this->getTaskRepository()->deleteTask($taskId, $userId);
}
}