Completed
Push — master ( f1dd26...2cc827 )
by Dmitri
03:03
created

CodeReader::readMethod()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
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