1
|
|
|
<?php |
2
|
|
|
namespace MeadSteve\DiceApi; |
3
|
|
|
|
4
|
|
|
use League\CommonMark\CommonMarkConverter; |
5
|
|
|
use MeadSteve\DiceApi\Counters\DiceCounter; |
6
|
|
|
use MeadSteve\DiceApi\RequestHandler\DiceRequestHandler; |
7
|
|
|
use Slim\App; |
8
|
|
|
use Slim\Http\Request; |
9
|
|
|
use Slim\Http\Response; |
10
|
|
|
|
11
|
|
|
class DiceApp extends App |
12
|
|
|
{ |
13
|
|
|
private $diceCounter; |
14
|
|
|
private $diceRequestHandler; |
15
|
|
|
|
16
|
|
|
const DICE_PATH_REGEX = "{dice:(?:/[0-9]*[dD][^\/]+)+/?}"; |
17
|
|
|
|
18
|
|
|
public function __construct(DiceRequestHandler $diceRequestHandler, DiceCounter $diceCounter) |
19
|
|
|
{ |
20
|
|
|
parent::__construct(); |
21
|
|
|
|
22
|
|
|
$this->diceRequestHandler = $diceRequestHandler; |
23
|
|
|
$this->diceCounter = $diceCounter; |
24
|
|
|
|
25
|
|
|
$this->setupRoutes(); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function index(Request $request, Response $response) |
29
|
|
|
{ |
30
|
|
|
$indexFilePath = __DIR__ . "/generated-index.html"; |
31
|
|
|
if (!file_exists($indexFilePath)) { |
32
|
|
|
$converter = new CommonMarkConverter(); |
33
|
|
|
$indexBody = $converter->convertToHtml(file_get_contents(__DIR__ . "/../README.md")); |
34
|
|
|
$indexContent = file_get_contents(__DIR__ . "/../www/templates/index.html"); |
35
|
|
|
$indexContent = str_replace("{{body}}", $indexBody, $indexContent); |
36
|
|
|
file_put_contents($indexFilePath, $indexContent); |
37
|
|
|
$response->write($indexContent); |
38
|
|
|
} else { |
39
|
|
|
$indexContent = file_get_contents($indexFilePath); |
40
|
|
|
$response->write($indexContent); |
41
|
|
|
} |
42
|
|
|
return $response; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public function diceStats(Request $request, Response $response) |
46
|
|
|
{ |
47
|
|
|
$countData = $this->diceCounter->getCounts(); |
48
|
|
|
return $response->write(json_encode($countData)) |
49
|
|
|
->withHeader("Content-Type", "application/json"); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
private function setupRoutes() |
53
|
|
|
{ |
54
|
|
|
$diceRequestHandler = $this->diceRequestHandler; |
55
|
|
|
|
56
|
|
|
$this->get("/", [$this, 'index']); |
57
|
|
|
$this->get("/dice-stats", [$this, 'diceStats']); |
58
|
|
|
$this->get(self::DICE_PATH_REGEX, [$diceRequestHandler, 'getDice']); |
59
|
|
|
|
60
|
|
|
foreach ($this->diceRequestHandler->contentTypesForPaths() as $path => $contentType) { |
61
|
|
|
$this->get( |
62
|
|
|
"/{$path}" . self::DICE_PATH_REGEX, |
63
|
|
|
function (Request $request, $response, $args) use ($diceRequestHandler, $contentType) { |
64
|
|
|
return $diceRequestHandler->getDice( |
65
|
|
|
$request->withHeader('accept', $contentType), |
66
|
|
|
$response, |
67
|
|
|
$args |
68
|
|
|
); |
69
|
|
|
} |
70
|
|
|
); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|