Completed
Pull Request — master (#13)
by Andrea Marco
05:42
created

ModelsFinder::qualifyClassFromFile()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
namespace Rexlabs\Laravel\Smokescreen\Console;
4
5
use ReflectionClass;
6
use Symfony\Component\Finder\Finder;
7
use Symfony\Component\Finder\SplFileInfo;
8
9
/**
10
 * The models finder.
11
 *
12
 */
13
class ModelsFinder
14
{
15
    /**
16
     * Find the models in the given directory.
17
     *
18
     * @param string $directory
19
     * @return array
20
     */
21
    public function findInDirectory(string $directory) : array
22
    {
23
        $models = [];
24
        $iterator = Finder::create()->files()->name('*.php')->in($directory)->depth(0)->sortByName();
25
26
        foreach ($iterator as $file) {
27
            if (!class_exists($class = $this->qualifyClassFromFile($file))) {
28
                continue;
29
            }
30
31
            $isAbstract = (new ReflectionClass($class))->isAbstract();
32
            $isModel = is_subclass_of($class, 'Illuminate\Database\Eloquent\Model');
33
34
            if ($isModel && !$isAbstract) {
35
                $models[] = new $class;
36
            }
37
        }
38
39
        return $models;
40
    }
41
42
    /**
43
     * Retrieve the fully-qualified class name of the given file.
44
     *
45
     * @param SplFileInfo $file
46
     * @return string|null
47
     */
48
    protected function qualifyClassFromFile(SplFileInfo $file) : ?string
49
    {
50
        preg_match('/namespace (.*);/', $file->getContents(), $matches);
51
52
        if (is_null($namespace = $matches[1] ?? null)) {
53
            return null;
54
        }
55
56
        return $namespace . '\\' . rtrim($file->getFilename(), '.php');
57
    }
58
}
59