-
Notifications
You must be signed in to change notification settings - Fork 15
/
server.php
112 lines (93 loc) · 1.91 KB
/
server.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
header( 'Content-Type: application/json' );
$allowedResourceTypes = [
'books',
'authors',
'genres',
];
$resourceType = $_GET['resource_type'];
if ( !in_array( $resourceType, $allowedResourceTypes ) ) {
http_response_code( 400 );
echo json_encode(
[
'error' => "$resourceType is un unkown",
]
);
die;
}
$books = [
1 => [
'titulo' => 'Lo que el viento se llevo',
'id_autor' => 2,
'id_genero' => 2,
],
2 => [
'titulo' => 'La Iliada',
'id_autor' => 1,
'id_genero' => 1,
],
3 => [
'titulo' => 'La Odisea',
'id_autor' => 1,
'id_genero' => 1,
],
];
$resourceId = array_key_exists('resource_id', $_GET ) ? $_GET['resource_id'] : '';
$method = $_SERVER['REQUEST_METHOD'];
switch ( strtoupper( $method ) ) {
case 'GET':
if ( "books" !== $resourceType ) {
http_response_code( 404 );
echo json_encode(
[
'error' => $resourceType.' not yet implemented :(',
]
);
die;
}
if ( !empty( $resourceId ) ) {
if ( array_key_exists( $resourceId, $books ) ) {
echo json_encode(
$books[ $resourceId ]
);
} else {
http_response_code( 404 );
echo json_encode(
[
'error' => 'Book '.$resourceId.' not found :(',
]
);
}
} else {
echo json_encode(
$books
);
}
die;
break;
case 'POST':
$json = file_get_contents( 'php://input' );
$books[] = json_decode( $json );
echo array_keys($books)[count($books)-1];
break;
case 'PUT':
if ( !empty($resourceId) && array_key_exists( $resourceId, $books ) ) {
$json = file_get_contents( 'php://input' );
$books[ $resourceId ] = json_decode( $json, true );
echo $resourceId;
}
break;
case 'DELETE':
if ( !empty($resourceId) && array_key_exists( $resourceId, $books ) ) {
unset( $books[ $resourceId ] );
}
break;
default:
http_response_code( 404 );
echo json_encode(
[
'error' => $method.' not yet implemented :(',
]
);
break;
}