Completed
Push — master ( e93715...b31e78 )
by Francesco
14:21
created

FeaturesViewScanner::getFeaturesForView()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 3
nop 1
1
<?php
2
3
namespace LaravelFeature\Service;
4
5
use Illuminate\Config\Repository;
6
use LaravelFeature\Domain\FeatureManager;
7
8
class FeaturesViewScanner
9
{
10
    /** @var FeatureManager */
11
    private $featureManager;
12
13
    /** @var Repository */
14
    private $config;
15
16
    /**
17
     * FeaturesViewScanner constructor.
18
     *
19
     * @param FeatureManager $featureManager
20
     * @param Repository $config
21
     */
22
    public function __construct(FeatureManager $featureManager, Repository $config)
23
    {
24
        $this->featureManager = $featureManager;
25
        $this->config = $config;
26
    }
27
28
    public function scan()
29
    {
30
        $pathsToBeScanned = $this->config->get('features.scanned_paths', [ 'resources/views' ]);
31
32
        $foundDirectives = [];
33
34
        foreach ($pathsToBeScanned as $path) {
35
            $views = $this->getAllBladeViewsInPath($path);
36
37
            foreach ($views as $view) {
38
                $foundDirectives = array_merge($foundDirectives, $this->getFeaturesForView($view));
39
            }
40
        }
41
42
        $foundDirectives = array_unique($foundDirectives);
43
44
        foreach ($foundDirectives as $directive) {
45
            $this->featureManager->add($directive, $this->config->get('features.scanned_default_enabled'));
46
        }
47
48
        return $foundDirectives;
49
    }
50
51
    private function getAllBladeViewsInPath($path)
52
    {
53
        $files = scandir($path);
54
        $files = array_diff($files, ['..', '.']);
55
56
        $bladeViews = [];
57
58
        foreach ($files as $file) {
59
            $itemPath = $path . DIRECTORY_SEPARATOR . $file;
60
61
            if (is_dir($itemPath)) {
62
                $bladeViews = array_merge($bladeViews, $this->getAllBladeViewsInPath($itemPath));
63
            }
64
65
            if (is_file($itemPath) && ends_with($file, '.blade.php')) {
66
                $bladeViews[] = $itemPath;
67
            }
68
        }
69
70
        return $bladeViews;
71
    }
72
73
    private function getFeaturesForView($view)
74
    {
75
        $fileContents = file_get_contents($view);
76
        preg_match_all('/@feature\(["\'](.+)["\']\)/', $fileContents, $results);
77
78
        $features = [];
79
        foreach ($results[1] as $result) {
80
            if ($result !== '') {
81
                $features[] = $result;
82
            }
83
        }
84
85
        return $features;
86
    }
87
}
88