Completed
Push — master ( 227694...ab8ba8 )
by Steve
07:03
created

DiceApp::setupRoutes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 21
rs 9.3143
cc 1
eloc 14
nc 1
nop 0
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
    public function __construct(DiceRequestHandler $diceRequestHandler, DiceCounter $diceCounter)
17
    {
18
        parent::__construct();
19
20
        $this->diceRequestHandler = $diceRequestHandler;
21
        $this->diceCounter = $diceCounter;
22
23
        $this->setupRoutes();
24
    }
25
26
    public function index(Request $request, Response $response)
27
    {
28
        $indexFilePath = __DIR__ . "/generated-index.html";
29
        if (!file_exists($indexFilePath)) {
30
            $converter = new CommonMarkConverter();
31
            $indexBody = $converter->convertToHtml(file_get_contents(__DIR__ . "/../README.md"));
32
            $indexContent = file_get_contents(__DIR__ . "/../www/templates/index.html");
33
            $indexContent = str_replace("{{body}}", $indexBody, $indexContent);
34
            file_put_contents($indexFilePath, $indexContent);
35
            $response->write($indexContent);
36
        } else {
37
            $indexContent = file_get_contents($indexFilePath);
38
            $response->write($indexContent);
39
        }
40
        return $response;
41
    }
42
43
    public function diceStats(Request $request, Response $response)
44
    {
45
        $countData = $this->diceCounter->getCounts();
46
        return $response->write(json_encode($countData))
47
            ->withHeader("Content-Type", "application/json");
48
    }
49
50
    private function setupRoutes()
51
    {
52
        $this->get("/", [$this, 'index']);
53
        $this->get("/dice-stats", [$this, 'diceStats']);
54
        $this->get("{dice:(?:/[0-9]*[dD][0-9]+)+/?}", [$this->diceRequestHandler, 'getDice']);
55
56
        $this->get("/html{dice:(?:/[0-9]*[dD][0-9]+)+/?}", function (Request $request, $response, $args) {
57
            return $this->diceRequestHandler->getDice(
58
                $request->withHeader('accept', 'text/html'),
59
                $response,
60
                $args
61
            );
62
        });
63
        $this->get("/json{dice:(?:/[0-9]*[dD][0-9]+)+/?}", function (Request $request, $response, $args) {
64
            return $this->diceRequestHandler->getDice(
65
                $request->withHeader('accept', 'application/json'),
66
                $response,
67
                $args
68
            );
69
        });
70
    }
71
}
72