Passed
Pull Request — master (#129)
by Serhii
09:00
created

SearchableListFactory   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
dl 0
loc 70
ccs 20
cts 20
cp 1
rs 10
c 1
b 0
f 0
wmc 8

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getProjectClasses() 0 11 3
A make() 0 3 1
A find() 0 6 2
A __construct() 0 4 1
A isSearchableModel() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Matchish\ScoutElasticSearch\Searchable;
6
7
use Illuminate\Support\Collection;
8
use Illuminate\Support\Str;
9
use function in_array;
10
use Laravel\Scout\Searchable;
11
use Symfony\Component\Finder\Finder;
12
13
final class SearchableListFactory
14
{
15
    /**
16
     * @var array
17
     */
18
    private static $declaredClasses;
19
    /**
20
     * @var string
21
     */
22
    private $namespace;
23
    /**
24
     * @var string
25
     */
26
    private $appPath;
27
28
    /**
29
     * @param string $namespace
30
     */
31 11
    public function __construct(string $namespace, string $appPath)
32
    {
33 11
        $this->namespace = $namespace;
34 11
        $this->appPath = $appPath;
35 11
    }
36
37
    /**
38
     * Get a list of searchable models.
39
     *
40
     * @return string[]
41
     */
42 11
    private function find(): array
43
    {
44 11
        $appNamespace = $this->namespace;
45
46 11
        return array_values(array_filter($this->getProjectClasses(), function (string $class) use ($appNamespace) {
47 11
            return Str::startsWith($class, $appNamespace) && $this->isSearchableModel($class);
48 11
        }));
49
    }
50
51
    /**
52
     * @param  string $class
53
     *
54
     * @return bool
55
     */
56 11
    private function isSearchableModel($class): bool
57
    {
58 11
        return in_array(Searchable::class, class_uses_recursive($class), true);
59
    }
60
61
    /**
62
     * @return array
63
     */
64 11
    private function getProjectClasses(): array
65
    {
66 11
        if (self::$declaredClasses === null) {
0 ignored issues
show
introduced by
The condition self::declaredClasses === null is always false.
Loading history...
67 1
            $configFiles = Finder::create()->files()->name('*.php')->in($this->appPath);
68 1
            foreach ($configFiles->files() as $file) {
69 1
                require_once $file;
70
            }
71 1
            self::$declaredClasses = get_declared_classes();
72
        }
73
74 11
        return self::$declaredClasses;
75
    }
76
77
    /**
78
     * @return Collection
79
     */
80 11
    public function make(): Collection
81
    {
82 11
        return new Collection($this->find());
83
    }
84
}
85