-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAnnotationReader.class.php
350 lines (306 loc) · 9.34 KB
/
AnnotationReader.class.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
<?php
/**
* Michael Zijlstra 03 May 2017
*
* Refactoring to use PHP Attributes instead of doc comment annotations
* mzijlstra 2024 Jan 09
*/
#[Attribute(Attribute::TARGET_CLASS)]
class Controller
{
public string $path;
public function __construct(string $path = '')
{
$this->path = $path;
}
}
#[Attribute(Attribute::TARGET_CLASS)]
class Repository {}
#[Attribute(Attribute::TARGET_PROPERTY)]
class Inject
{
public string $name;
public function __construct(string $name)
{
$this->name = $name;
}
}
#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
class Request
{
public string $method;
public string $uri;
public string $sec;
public function __construct(string $method, string $uri = '', string $sec = 'none')
{
$this->method = $method;
$this->uri = $uri;
$this->sec = $sec;
}
public function __toString(): string
{
return $this->method.' '.$this->uri.' '.$this->sec;
}
}
#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
class Get extends Request
{
public function __construct(string $uri, string $sec = 'none')
{
parent::__construct('GET', $uri, $sec);
}
}
#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
class Post extends Request
{
public function __construct(string $uri, string $sec = 'none')
{
parent::__construct('POST', $uri, $sec);
}
}
#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
class Put extends Request
{
public function __construct(string $uri, string $sec = 'none')
{
parent::__construct('PUT', $uri, $sec);
}
}
#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
class Delete extends Request
{
public function __construct(string $uri, string $sec = 'none')
{
parent::__construct('DELETE', $uri, $sec);
}
}
class AnnotationReader
{
private array $REQ_TYPES = ['GET', 'POST', 'PUT', 'DELETE'];
public array $mappings = [];
public array $repositories = [];
public array $controllers = [];
public string $context = '';
/**
* Constructor, initiallizes internal mappings arrays
*/
public function __construct()
{
foreach ($this->REQ_TYPES as $req) {
$this->mappings[$req] = [];
}
}
/**
* Checks the properties of a class for Inject attributes
*
* @param type $reflect_class
* @return type
*/
private function to_inject(ReflectionClass $reflect_class): array
{
$result = [];
foreach ($reflect_class->getProperties() as $prop) {
$attrs = $prop->getAttributes();
foreach ($attrs as $attr) {
if ($attr->getName() == 'Inject') {
$result[$prop->getName()] = $attr->getArguments()[0];
}
}
}
return $result;
}
/**
* Validate the content of a Request annotation
*
* @global type $SEC_LVLS
*
* @throws Exception
*/
private function validate_request_annotation(Request $request): void
{
global $SEC_LVLS;
if (! in_array($request->method, $this->REQ_TYPES)) {
throw new Exception("Bad request attribute method value in: $request");
}
if ($request->uri == '') {
throw new Exception("Request attribute missing uri in: $request");
}
if (! in_array($request->sec, $SEC_LVLS)) {
throw new Exception("Bad sec value in @GET or @POST found in: $request");
}
}
/**
* Maps Request annotations to the internal mappings array
*
* @param Reflection_Class $reflect_class
*/
private function map_requests(ReflectionClass $reflect_class, string $path): void
{
foreach ($reflect_class->getMethods() as $m) {
$attrs = $m->getAttributes();
foreach ($attrs as $a) {
$req = $a->newInstance();
if (! ($req instanceof Request)) {
continue;
}
$this->validate_request_annotation($req);
$method_loc = $reflect_class->getName().'@'.$m->getName();
$mapping = ['sec' => $req->sec, 'route' => $method_loc];
$uri = '!'.$path.$req->uri.'!';
$this->mappings[$req->method][$uri] = $mapping;
}
}
}
/**
* Checks if a class has an Repository annotation, if it does adds it to
* the array of repositories
*
* @param string $class
*/
private function check_repository($class)
{
$r = new ReflectionClass($class);
$attrs = $r->getAttributes();
foreach ($attrs as $a) {
if ($a->getName() == 'Repository') {
$to_inject = $this->to_inject($r);
$this->repositories[$class] = $to_inject;
}
}
}
/**
* Checks if classes have a Controller annotation, and
* processes them as needed
*
* @param string $class
*/
private function check_controller($class)
{
$r = new ReflectionClass($class);
$attrs = $r->getAttributes();
foreach ($attrs as $a) {
if ($a->getName() == 'Controller') {
$to_inject = $this->to_inject($r);
$this->controllers[$class] = $to_inject;
$path = $a->newInstance()->path;
$this->map_requests($r, $path);
}
}
}
/**
* Scan for PHP classes in a directory, calling the passed function on them
*
* @param string $directory
* @param function $function
*/
private function scan_classes($directory, $function)
{
$files = scandir($directory);
foreach ($files as $file) {
$mats = [];
// skip hidden files, directories, files that are not .class.php
if (
$file[0] === '.' || is_dir($file) ||
! preg_match("#(.*)\.class\.php#i", $file, $mats)
) {
continue;
}
$this->{$function}($mats[1]);
}
}
/**
* Scans the standard directories, reading .php files for annotations
*
* @return AnnotationContext self for call chaining
*/
public function scan()
{
$this->scan_classes('model', 'check_repository');
$this->scan_classes('control', 'check_controller');
return $this;
}
/**
* Generate code for the retrievable classes to the context class
*
* @param type $classes
*/
private function add_classes_to_context($classes)
{
foreach ($classes as $class => $injects) {
$this->context .= <<< IF_START
if (\$id === "$class" && !isset(\$this->objects["$class"])) {
\$this->objects["$class"] = new $class();
IF_START;
foreach ($injects as $prop => $id) {
$this->context .=
" \$this->objects[\"$class\"]->$prop = "
."\$this->get(\"$id\");\n";
}
$this->context .= " }\n"; // close if statement
}
}
/**
* Creates the context in memory
*
* @return AnnotationContext self for call chaining
*/
public function create_context()
{
$this->context .= <<< 'WARNING'
/*******************************************************************************
* DO NOT MODIFY THIS FILE, IT IS GENERATED
*
* When DEVELOPMENT=true this file is generated based on the settings in
* frontController.php and the annotations found in the class files in the
* control and model directories
******************************************************************************/
WARNING;
// generate the mappings array
$this->context .= "\$mappings = array(\n";
foreach ($this->mappings as $method => $items) {
$this->context .= "\t\"$method\" => array(\n";
foreach ($items as $uri => $mapping) {
$sec = $mapping['sec'];
$route = $mapping['route'];
$this->context .= "\t\t'$uri' => \n\t\t\t";
$this->context .= "['sec' => '$sec', 'route' => '$route'],\n";
}
$this->context .= "\t),\n";
}
$this->context .= ");\n";
// these values are set in frontController.php
$dsn = DSN;
$user = DB_USER;
$pass = DB_PASS;
$this->context .= <<< HEADER
class Context {
private \$objects = array();
public function __construct() {
\$db = new PDO("$dsn", "$user", "$pass");
\$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
\$this->objects["DB"] = \$db;
}
public function get(\$id) {
HEADER;
$this->add_classes_to_context($this->repositories);
$this->add_classes_to_context($this->controllers);
$this->context .= <<< 'FOOTER'
return $this->objects[$id];
} // close get method
} // close Context class
FOOTER;
return $this;
}
/**
* Writes the context (as found by scan) to a file
*
* @param string $filename
* @return AnnotationContext self for call chaining
*/
public function write($filename)
{
$data = "<?php\n".$this->context;
file_put_contents($filename, $data);
return $this;
}
}