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

TemplateDispatcher::setContentType()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
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