Passed
Pull Request — 2.x (#1446)
by Harings
13:09
created

TwillPackageServiceProvider   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 55
rs 10
wmc 9

6 Methods

Rating   Name   Duplication   Size   Complexity  
A registerCapsules() 0 8 2
A boot() 0 3 2
A getClassName() 0 4 1
A registerCapsule() 0 8 1
A getCapsuleNamespace() 0 5 1
A getPackageDirectory() 0 11 2
1
<?php
2
3
namespace A17\Twill;
4
5
use Illuminate\Support\Facades\Storage;
6
use Illuminate\Support\ServiceProvider;
7
use Illuminate\Support\Str;
8
use ReflectionClass;
9
10
abstract class TwillPackageServiceProvider extends ServiceProvider
11
{
12
    protected $autoRegisterCapsules = true;
13
14
    public function boot(): void {
15
        if ($this->autoRegisterCapsules) {
16
            $this->registerCapsules('Twill/Capsules');
17
        }
18
    }
19
20
    protected function registerCapsule(string $name): void {
21
        $namespace = $this->getCapsuleNamespace();
22
23
        $namespace .= '\\Twill\\Capsules\\' . $name;
24
25
        $dir = $this->getPackageDirectory() . '/src/Twill/Capsules/' . $name;
26
27
        \A17\Twill\Facades\TwillCapsules::registerPackageCapsule($name, $namespace, $dir);
28
    }
29
30
    protected function registerCapsules(string $directory): void {
31
        $storage = Storage::build([
32
            'driver' => 'local',
33
            'root' => $this->getPackageDirectory() . '/src/' . $directory,
34
        ]);
35
36
        foreach ($storage->directories() as $capsuleName) {
37
            $this->registerCapsule($capsuleName);
38
        }
39
    }
40
41
    protected function getClassName(): string {
42
        $provider = explode('\\', get_class($this));
43
44
        return array_pop($provider);
45
    }
46
47
    protected function getCapsuleNamespace(): string {
48
        $provider = explode('\\', get_class($this));
49
        array_pop($provider);
50
51
        return implode('\\', $provider);
52
    }
53
54
    protected function getPackageDirectory(): string
55
    {
56
        $class = new ReflectionClass(get_class($this));
57
58
        $path = Str::replaceLast('/' . $this->getClassName() . '.php', '', $class->getFileName());
59
60
        if (Str::endsWith($path, '/src')) {
61
            $path = Str::replaceLast('/src', '', $path);
62
        }
63
64
        return $path;
65
    }
66
}
67