-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTodoResource.php
84 lines (69 loc) · 1.99 KB
/
TodoResource.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
<?php
namespace Demo\Resource;
use Demo\Api\Todo;
use Demo\Db\TodoDbm;
use Demo\Weather\Client\WeatherClient;
use Fliglio\Http\Exceptions\NotFoundException;
use Fliglio\Http\Http;
use Fliglio\Http\ResponseWriter;
use Fliglio\Logging\FLog;
use Fliglio\Web\Entity;
use Fliglio\Web\GetParam;
use Fliglio\Web\PathParam;
class TodoResource {
use FLog;
private $db;
private $weather;
public function __construct(TodoDbm $db, WeatherClient $weather) {
$this->db = $db;
$this->weather = $weather;
}
// GET /todo
public function getAll(GetParam $status = null) {
$todos = $this->db->findAll(is_null($status) ? null : $status->get());
return array_map(function($todo) {
return $todo->marshal();
}, $todos);
}
// GET /todo/weather
public function getWeatherAppropriate(GetParam $city, GetParam $state, GetParam $status = null) {
$status = is_null($status) ? null : $status->get();
$weather = $this->weather->getWeather($city->get(), $state->get());
$this->log()->debug(print_r($weather->marshal(), true));
$outdoorWeather = $weather->getDescription() == "Clear";
$todos = $this->db->findAll($status, $outdoorWeather);
return array_map(function($todo) {
return $todo->marshal();
}, $todos);
}
// GET /todo/:id
public function get(PathParam $id) {
$todo = $this->db->find($id->get());
if (is_null($todo)) {
throw new NotFoundException();
}
return $todo->marshal();
}
// POST /todo
public function add(Entity $entity, ResponseWriter $resp) {
$todo = $entity->bind(Todo::getClass());
$this->db->save($todo);
$resp->setStatus(Http::STATUS_CREATED);
return $todo->marshal();
}
// PUT /todo/:id
public function update(PathParam $id, Entity $entity) {
$todo = $entity->bind(Todo::getClass());
$todo->setId($id->get());
$this->db->save($todo);
return $todo->marshal();
}
// DELETE /todo/:id
public function delete(PathParam $id) {
$todo = $this->db->find($id->get());
if (is_null($todo)) {
throw new NotFoundException();
}
$this->db->delete($todo);
}
}