Completed
Push — master ( bb1ab9...4cd17e )
by Sinnarasa
02:25
created

TemplateDispatcher::call()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 3
Metric Value
c 5
b 0
f 3
dl 0
loc 9
rs 9.6666
cc 3
eloc 7
nc 4
nop 0
1
<?php
2
3
namespace JetFire\Routing\Dispatcher;
4
5
6
use JetFire\Routing\ResponseInterface;
7
use JetFire\Routing\Route;
8
9
/**
10
 * Class TemplateDispatcher
11
 * @package JetFire\Routing\Dispatcher
12
 */
13
class TemplateDispatcher implements DispatcherInterface
14
{
15
16
    /**
17
     * @var Route
18
     */
19
    private $route;
20
21
    /**
22
     * @var ResponseInterface
23
     */
24
    private $response;
25
26
    /**
27
     * @var array
28
     */
29
    protected $types = [
30
        'json' => 'application/json',
31
        'xml' => 'application/xml',
32
        'txt' => 'text/plain',
33
        'html' => 'text/html'
34
    ];
35
36
    /**
37
     * @param Route $route
38
     */
39
    public function __construct(Route $route,ResponseInterface $response)
40
    {
41
        $this->route = $route;
42
        $this->response = $response;
43
    }
44
45
    /**
46
     * @description call template file
47
     */
48
    public function call()
49
    {
50
        if ($this->response->getStatusCode() == 202)
51
            $this->setContentType($this->route->getTarget('extension'));
52
        if (isset($this->route->getTarget()['callback'][$this->route->getTarget('extension')]))
53
            $this->response->setContent(call_user_func_array($this->route->getTarget()['callback'][$this->route->getTarget('extension')], [$this->route]));
54
        else
55
            $this->response->setContent(require($this->route->getTarget('template')));
56
    }
57
58
    /**
59
     * @param $extension
60
     */
61
    public function setContentType($extension){
62
        $this->response->setStatusCode(200);
63
        isset($this->types[$extension])
64
            ? $this->response->setHeaders(['Content-Type' => $this->types[$extension]])
65
            : $this->response->setHeaders(['Content-Type' => $this->types['html']]);
66
    }
67
68
}
69