-
Notifications
You must be signed in to change notification settings - Fork 1
/
site.php
128 lines (109 loc) · 2.78 KB
/
site.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
<?php
namespace TF;
use Phroute\Phroute\RouteCollector;
use Phroute\Phroute\Dispatcher;
use Twig_Function;
use Twig_Environment;
use Twig_Loader_Filesystem;
use Symfony\Component\VarDumper;
/**
* Sets up barebones routing and templating
*/
class Site
{
/**
* Twig environment
* @var Twig_Environment
*/
public $twig;
/**
* Twig loader
* @var Twig_Loader_Filesystem
*/
public $loader;
/**
* Router
* @var RouteCollector
*/
public $router;
/**
* The path of the url
* @var string
*/
public $page;
/**
* Name of the template to load
* @var string
*/
public $template;
/**
* Server request method
* @var string
*/
public $requestMethod;
public function __construct()
{
$this->loader = new Twig_Loader_Filesystem(__DIR__ . '/templates');
$this->twig = new Twig_Environment($this->loader);
$this->router = new RouteCollector();
$this->requestMethod = $_SERVER['REQUEST_METHOD'];
$this->page = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$this->template = $this->getTemplateFromUrl();
}
/**
* Fire it up
*/
public function start()
{
$this->twigFunctions();
$this->setupRouting();
}
/**
* Add any custom Twig functions
*/
private function twigFunctions()
{
/**
* Updates an assets url if using hot module reloading
* @var Twig_Function
*/
$assetHelper = new Twig_Function('assets', function ($path) {
if (file_exists(__DIR__ . '/hot')) {
return 'http://localhost:8080/public' . $path;
}
return $path;
});
/**
* Fancier way to dump things
* @var Twig_Function
*/
$dump = new Twig_Function('dump', function ($arg) {
return dump($arg);
});
$this->twig->addFunction($assetHelper);
$this->twig->addFunction($dump);
}
/**
* Handles routing, only basic GET requests
*/
private function setupRouting()
{
$this->router->get($this->page, function () {
return $this->twig->render($this->template);
});
$dispatcher = new Dispatcher($this->router->getData());
// listen for a request to generate a response
$response = $dispatcher->dispatch($this->requestMethod, $this->page);
echo $response;
}
/**
* Figures out the template to use from the url
* @return string
*/
private function getTemplateFromUrl()
{
$segments = explode('/', $this->page);
$lastSegment = array_pop($segments);
return $lastSegment === '' ? 'index.twig' : $lastSegment . '.twig';
}
}