Completed
Push — master ( efdc7e...8e7c5b )
by Maarten
01:54 queued 12s
created

ClassReader::getMethods()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.7333
c 0
b 0
f 0
cc 2
nc 1
nop 1
1
<?php
2
3
namespace Mtolhuys\LaravelSchematics\Services;
4
5
use Illuminate\Support\Collection;
6
use ReflectionException;
7
use ReflectionMethod;
8
use ReflectionClass;
9
10
class ClassReader
11
{
12
    /**
13
     * @param string $path
14
     * @return string
15
     */
16
    public static function getClassName(string $path): string
17
    {
18
        $namespace = $class = '';
19
        $contents = file_get_contents($path);
20
        $hasNamespace = $hasClass = false;
21
22
        foreach (token_get_all($contents) as $token) {
23
            if (is_array($token) && $token[0] === T_NAMESPACE) {
24
                $hasNamespace = true;
25
            }
26
27
            if (is_array($token) && $token[0] === T_CLASS) {
28
                $hasClass = true;
29
            }
30
31
            if ($hasNamespace) {
32
                if (is_array($token) && in_array($token[0], [T_STRING, T_NS_SEPARATOR], true)) {
33
                    $namespace .= $token[1];
34
                } else if ($token === ';') {
35
                    $hasNamespace = false;
36
                }
37
            }
38
39
            if ($hasClass && is_array($token) && $token[0] === T_STRING) {
40
                $class = $token[1];
41
                break;
42
            }
43
        }
44
45
        return $namespace ? $namespace . '\\' . $class : $class;
46
    }
47
48
    /**
49
     * @param string $className
50
     * @return Collection
51
     * @throws ReflectionException
52
     */
53
    public static function getMethods(string $className): Collection
54
    {
55
        $class = new ReflectionClass($className);
56
57
        return Collection::make($class->getMethods(ReflectionMethod::IS_PUBLIC))
58
            ->merge(Collection::make($class->getTraits())
59
                ->map(static function (ReflectionClass $trait) {
60
                    return Collection::make(
61
                        $trait->getMethods(ReflectionMethod::IS_PUBLIC)
62
                    );
63
                })->flatten()
64
            )
65
            ->reject(static function (ReflectionMethod $method) use ($className) {
66
                return $method->class !== $className || $method->getNumberOfParameters() > 0;
67
            });
68
    }
69
}
70