-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDelegates.class.php
More file actions
executable file
·68 lines (61 loc) · 1.86 KB
/
Delegates.class.php
File metadata and controls
executable file
·68 lines (61 loc) · 1.86 KB
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
<?php namespace web\rest;
use lang\{IllegalArgumentException, Reflection};
/**
* Matches request and routes to correct delegate
*/
class Delegates {
private static $METHODS= [
'get' => 'param',
'head' => 'param',
'post' => 'entity',
'put' => 'entity',
'patch' => 'entity',
'delete' => 'param',
'options' => 'param'
];
public $patterns= [];
/**
* Routes to instance methods based on annotations
*
* @param object $instance
* @param string $base
* @return self
* @throws lang.IllegalArgumentException
*/
public function with($instance, $base= '/') {
if (!is_object($instance)) {
throw new IllegalArgumentException('Expected an object, have '.typeof($instance));
}
$base= rtrim($base, '/');
foreach (Reflection::type($instance)->methods() as $method) {
foreach ($method->annotations() as $annotation) {
$verb= $annotation->name();
if (null === ($source= self::$METHODS[$verb] ?? null)) continue;
$segment= $annotation->argument(0);
if (null === $segment) {
$pattern= $base.'(/.+)?';
} else if ('/' === $segment || '' === $segment) {
$pattern= $base.'/?';
} else {
$pattern= $base.preg_replace(['/\{([^:}]+):([^}]+)\}/', '/\{([^}]+)\}/'], ['(?<$1>$2)', '(?<$1>[^/]+)'], $segment);
}
$this->patterns['#^'.$verb.$pattern.'$#']= new Delegate($instance, $method, $source);
}
}
return $this;
}
/**
* Returns target for a given HTTP verb and path
*
* @param string $verb
* @param string $path
* @return web.frontend.Delegate or NULL
*/
public function target($verb, $path) {
$match= $verb.$path;
foreach ($this->patterns as $pattern => $delegate) {
if (preg_match($pattern, $match, $matches)) return [$delegate, $matches];
}
return null;
}
}