|
1 | 1 | <?php
|
2 |
| -if(isset($_SERVER['argv'][0]) && $_SERVER['argv'][0] === 'server.php') { |
| 2 | +$scriptInvokedFromCli = |
| 3 | + isset($_SERVER['argv'][0]) && $_SERVER['argv'][0] === 'server.php'; |
| 4 | + |
| 5 | +if($scriptInvokedFromCli) { |
| 6 | + echo 'server listening on port 3000'; |
3 | 7 | exec('php -S localhost:3000 -t public server.php');
|
| 8 | +} else { |
| 9 | + return routeRequest(); |
4 | 10 | }
|
5 | 11 |
|
6 |
| -$comments = file_get_contents('_comments.json'); |
7 |
| -switch($_SERVER["REQUEST_URI"]) { |
8 |
| - case '/': |
9 |
| - echo file_get_contents('./public/index.html'); |
10 |
| - break; |
11 |
| - case '/comments.json': |
12 |
| - if($_SERVER['REQUEST_METHOD'] === 'POST') { |
13 |
| - $commentsDecoded = json_decode($comments, true); |
14 |
| - $commentsDecoded[] = ['author' => $_POST['author'], |
15 |
| - 'text' => $_POST['text']]; |
| 12 | +function routeRequest() |
| 13 | +{ |
| 14 | + $comments = file_get_contents('_comments.json'); |
| 15 | + switch($_SERVER["REQUEST_URI"]) { |
| 16 | + case '/': |
| 17 | + echo file_get_contents('./public/index.html'); |
| 18 | + break; |
| 19 | + case '/comments.json': |
| 20 | + if($_SERVER['REQUEST_METHOD'] === 'POST') { |
| 21 | + $commentsDecoded = json_decode($comments, true); |
| 22 | + $commentsDecoded[] = ['author' => $_POST['author'], |
| 23 | + 'text' => $_POST['text']]; |
16 | 24 |
|
17 |
| - $comments = json_encode($commentsDecoded); |
18 |
| - file_put_contents('_comments.json', $comments); |
19 |
| - } |
20 |
| - header('Content-Type: application/json'); |
21 |
| - echo $comments; |
22 |
| - break; |
23 |
| - default: |
24 |
| - return false; |
| 25 | + $comments = json_encode($commentsDecoded); |
| 26 | + file_put_contents('_comments.json', $comments); |
| 27 | + } |
| 28 | + header('Content-Type: application/json'); |
| 29 | + echo $comments; |
| 30 | + break; |
| 31 | + default: |
| 32 | + return false; |
| 33 | + } |
25 | 34 | }
|
| 35 | + |
0 commit comments