1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace WyriHaximus\Tactician\CommandHandler; |
4
|
|
|
|
5
|
|
|
use Doctrine\Common\Annotations\AnnotationReader; |
6
|
|
|
use Doctrine\Common\Annotations\Reader; |
7
|
|
|
use RecursiveDirectoryIterator; |
8
|
|
|
use RecursiveIteratorIterator; |
9
|
|
|
use ReflectionClass; |
10
|
|
|
use WyriHaximus\Tactician\CommandHandler\Annotations\Handler; |
11
|
|
|
|
12
|
|
|
final class Mapper |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @param $path |
16
|
|
|
* @param $namespace |
17
|
|
|
* @return array |
18
|
|
|
*/ |
19
|
|
|
public static function mapInstantiated($path, $namespace) |
20
|
|
|
{ |
21
|
|
|
$mapping = []; |
22
|
|
|
|
23
|
|
|
foreach (self::map($path, $namespace) as $command => $handler) { |
24
|
|
|
$mapping[$command] = new $handler(); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
return $mapping; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param $path |
32
|
|
|
* @param $namespace |
33
|
|
|
* @return array |
34
|
|
|
*/ |
35
|
|
|
public static function map($path, $namespace) |
36
|
|
|
{ |
37
|
|
|
$reader = new AnnotationReader(); |
38
|
|
|
$mapping = []; |
39
|
|
|
|
40
|
|
|
$directory = new RecursiveDirectoryIterator($path); |
41
|
|
|
$directory = new RecursiveIteratorIterator($directory); |
42
|
|
|
|
43
|
|
|
foreach ($directory as $node) { |
44
|
|
|
if (!is_file($node->getPathname())) { |
45
|
|
|
continue; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
$file = substr($node->getPathname(), strlen($path)); |
49
|
|
|
$file = ltrim($file, DIRECTORY_SEPARATOR); |
50
|
|
|
$file = rtrim($file, '.php'); |
51
|
|
|
|
52
|
|
|
$class = $namespace . '\\' . str_replace(DIRECTORY_SEPARATOR, '\\', $file); |
53
|
|
|
|
54
|
|
|
if (!class_exists($class)) { |
55
|
|
|
continue; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
$handler = self::getHandlerByCommand($class, $reader); |
59
|
|
|
|
60
|
|
|
if (!class_exists($handler)) { |
61
|
|
|
continue; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
$mapping[$class] = $handler; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return $mapping; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @param string $command |
72
|
|
|
* @param Reader $reader |
73
|
|
|
* @return string |
74
|
|
|
*/ |
75
|
2 |
|
public static function getHandlerByCommand($command, Reader $reader) |
76
|
|
|
{ |
77
|
2 |
|
$annotation = $reader->getClassAnnotation(new ReflectionClass($command), Handler::class); |
78
|
|
|
|
79
|
2 |
|
if (!($annotation instanceof Handler)) { |
80
|
1 |
|
return ''; |
81
|
|
|
} |
82
|
|
|
|
83
|
1 |
|
return $annotation->getHandler(); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|