Test Failed
Push — master ( 052ffd...55ff26 )
by Jodie
02:51
created

ModelsFinder::determineClassFromFile()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 7
rs 10
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
class ModelsFinder
10
{
11
    /**
12
     * Find the models in the given directory.
13
     *
14
     * @param string $directory
15
     *
16
     * @return array|string[]
17
     * @throws \ReflectionException
18
     */
19
    public function findInDirectory(string $directory): array
20
    {
21
        $models = [];
22
        $iterator = Finder::create()->files()->name('*.php')->in($directory)->depth(0)->sortByName();
23
24
        foreach ($iterator as $file) {
25
            $class = $this->determineClassFromFile($file);
26
            if ($class !== null && class_exists($class) && $this->isModelClass($class)) {
27
                $models[] = $class;
28
            }
29
        }
30
31
        return $models;
32
    }
33
34
    /**
35
     * Retrieve the fully-qualified class name of the given file.
36
     *
37
     * @param SplFileInfo $file
38
     *
39
     * @return string|null
40
     */
41
    protected function determineClassFromFile(SplFileInfo $file)
42
    {
43
        if (!preg_match('/namespace (.*);/', $file->getContents(), $matches)) {
44
            return null;
45
        }
46
47
        return $matches[1] . '\\' . rtrim($file->getFilename(), '.php');
48
    }
49
50
    /**
51
     * Determine if the given class is an eloquent model.
52
     *
53
     * @param string $class
54
     *
55
     * @return bool
56
     * @throws \ReflectionException
57
     */
58
    protected function isModelClass(string $class): bool
59
    {
60
        if (!is_subclass_of($class, \Illuminate\Database\Eloquent\Model::class)) {
61
            // Must extend Model
62
            return false;
63
        }
64
65
        if ((new ReflectionClass($class))->isAbstract()) {
66
            // Exclude abstract classes
67
            return false;
68
        }
69
70
        return true;
71
    }
72
}
73