Completed
Push — master ( 58e332...227694 )
by Steve
02:48 queued 32s
created

DiceApp::__construct()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

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