|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace AppBundle; |
|
4
|
|
|
|
|
5
|
|
|
class CodeReader |
|
6
|
|
|
{ |
|
7
|
|
|
const BOUND_FORM_BUILDER = 'form_builder'; |
|
8
|
|
|
const BOUND_FORM_DEFINITION = 'form_definition'; |
|
9
|
|
|
const BOUND_FULL_METHOD = 'full_method'; |
|
10
|
|
|
|
|
11
|
|
|
private $bounds = [ |
|
12
|
|
|
self::BOUND_FORM_BUILDER => [12, 2, -5], |
|
13
|
|
|
self::BOUND_FORM_DEFINITION => [8, 1, -4], |
|
14
|
|
|
self::BOUND_FULL_METHOD => [4, -4, 4], |
|
15
|
|
|
]; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @var \ReflectionClass[] |
|
19
|
|
|
*/ |
|
20
|
|
|
private $cache = []; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @param string $spec AppBundle:Controller:action |
|
24
|
|
|
* @param string $bound |
|
25
|
|
|
* |
|
26
|
|
|
* @return string |
|
27
|
|
|
*/ |
|
28
|
|
|
public function readMethod($spec, $bound = self::BOUND_FORM_BUILDER) |
|
29
|
|
|
{ |
|
30
|
|
|
list($bundle, $controller, $method) = explode(':', $spec); |
|
31
|
|
|
|
|
32
|
|
|
$controllerClass = sprintf('%s\Controller\%sController', $bundle, $controller); |
|
33
|
|
|
|
|
34
|
|
|
return $this->readSource($controllerClass, $method, $this->bounds[$bound]); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* @param string $className |
|
39
|
|
|
* |
|
40
|
|
|
* @return string |
|
41
|
|
|
*/ |
|
42
|
|
|
public function readClass($className) |
|
43
|
|
|
{ |
|
44
|
|
|
return trim(file_get_contents($this->getReflectionClass($className)->getFileName())); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* @param string $class |
|
49
|
|
|
* @param string $method |
|
50
|
|
|
* @param array $bounds |
|
51
|
|
|
* |
|
52
|
|
|
* @return string |
|
53
|
|
|
*/ |
|
54
|
|
|
private function readSource($class, $method, array $bounds) |
|
55
|
|
|
{ |
|
56
|
|
|
$rc = $this->getReflectionClass($class); |
|
57
|
|
|
$rm = $rc->getMethod($method); |
|
58
|
|
|
|
|
59
|
|
|
// Read method source. |
|
60
|
|
|
$source = file($rc->getFileName()); |
|
61
|
|
|
$source = array_slice($source, $rm->getStartLine() + $bounds[1], $rm->getEndLine() - $rm->getStartLine() + $bounds[2]); |
|
|
|
|
|
|
62
|
|
|
|
|
63
|
|
|
// Remove indent. |
|
64
|
|
|
$source = array_map(function ($line) use ($bounds) { |
|
65
|
|
|
return preg_replace("/^ {{$bounds[0]}}/", '', $line); |
|
66
|
|
|
}, $source); |
|
67
|
|
|
|
|
68
|
|
|
return trim(implode('', $source)); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* @param string $class |
|
73
|
|
|
* |
|
74
|
|
|
* @return \ReflectionClass |
|
75
|
|
|
*/ |
|
76
|
|
|
private function getReflectionClass($class) |
|
77
|
|
|
{ |
|
78
|
|
|
if (!isset($this->cache[$class])) { |
|
79
|
|
|
$this->cache[$class] = new \ReflectionClass($class); |
|
80
|
|
|
} |
|
81
|
|
|
|
|
82
|
|
|
return $this->cache[$class]; |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
|