Passed
Pull Request — 2.x (#924)
by Antonio Carlos
10:18
created

HasCapsules::loadCapsuleConfig()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 10
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 18
rs 9.9332
1
<?php
2
3
namespace A17\Twill\Services\Capsules;
4
5
use Illuminate\Support\Str;
6
7
trait HasCapsules
8
{
9
    protected function getAutoloader()
10
    {
11
        return app()->bound('autoloader')
12
            ? app('autoloader')
13
            : require base_path('vendor/autoload.php');
14
    }
15
16
    public function getCapsuleList()
17
    {
18
        $path = $this->getCapsulesPath();
19
20
        $list = collect(config('twill.capsules.list'));
21
22
        if (config('twill.capsules.loaded')) {
23
            return $list;
24
        }
25
26
        return $list
27
            ->where('enabled', true)
28
            ->map(function ($capsule) use ($path) {
29
                return $this->makeCapsule($capsule, $path);
30
            });
31
    }
32
33
    public function getCapsuleByModel($model)
34
    {
35
        return $this->getCapsuleList()
36
            ->where('singular', Str::studly($model))
37
            ->first();
38
    }
39
40
    public function getCapsuleByModule($module)
41
    {
42
        return $this->getCapsuleList()
43
            ->filter(function ($capsule) use ($module) {
44
                return Str::lower($capsule['plural']) == Str::lower($module);
45
            })
46
            ->first();
47
    }
48
49
    /**
50
     * @return \Illuminate\Config\Repository|\Illuminate\Contracts\Foundation\Application|mixed
51
     */
52
    public function getCapsulesPath()
53
    {
54
        return config('twill.capsules.path');
55
    }
56
57
    /**
58
     * @return \Illuminate\Config\Repository|\Illuminate\Contracts\Foundation\Application|mixed
59
     */
60
    public function getCapsulesSubdir()
61
    {
62
        $subdir = config('twill.capsules.namespaces.subdir');
63
64
        return $subdir;
65
    }
66
67
    public function makeCapsule($capsule, $basePath = null)
68
    {
69
        $basePath = $basePath ?? $this->getCapsulesPath();
70
71
        $capsule['name'] = Str::studly($capsule['name']);
72
73
        $capsule['module'] = Str::camel($capsule['name']);
74
75
        $capsule['plural'] = $name = $capsule['name'];
76
77
        $capsule['singular'] = $singular =
78
            $capsule['singular'] ?? Str::singular($name);
79
80
        $twillNamespace = config('twill.namespace');
0 ignored issues
show
Unused Code introduced by
The assignment to $twillNamespace is dead and can be removed.
Loading history...
81
82
        $capsule[
83
            'namespace'
84
        ] = $capsuleNamespace = $this->getManager()->capsuleNamespace(
0 ignored issues
show
Bug introduced by
The method capsuleNamespace() does not exist on Illuminate\Contracts\Foundation\Application. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

84
        ] = $capsuleNamespace = $this->getManager()->/** @scrutinizer ignore-call */ capsuleNamespace(

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
85
            $capsule['name']
86
        );
87
88
        $capsule['database_namespace'] = "$capsuleNamespace\Database";
89
90
        $capsule['seeds_namespace'] = "{$capsule['database_namespace']}\Seeds";
91
92
        $capsule['model'] = $capsule['models'] = $models =
93
            "{$capsuleNamespace}\\" .
94
            config('twill.capsules.namespaces.models');
95
        $capsule['repositories'] = $repositories =
96
            "{$capsuleNamespace}\\" .
97
            config('twill.capsules.namespaces.repositories');
98
        $capsule['controllers'] = $controllers =
99
            "{$capsuleNamespace}\\" .
100
            config('twill.capsules.namespaces.controllers');
101
        $capsule['requests'] = $requests =
102
            "{$capsuleNamespace}\\" .
103
            config('twill.capsules.namespaces.requests');
104
105
        $capsule['psr4_path'] =
106
            "$basePath/{$name}" .
107
            (filled($this->getCapsulesSubdir())
108
                ? $this->getCapsulesSubdir() . '/'
0 ignored issues
show
Bug introduced by
Are you sure $this->getCapsulesSubdir() of type Illuminate\Config\Reposi...ation\Application|mixed can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

108
                ? /** @scrutinizer ignore-type */ $this->getCapsulesSubdir() . '/'
Loading history...
109
                : '');
110
111
        $capsule['base_path'] = $basePath;
112
113
        $capsule['database_psr4_path'] = "$basePath/{$name}/database";
114
115
        $capsule['seeds_psr4_path'] = "{$capsule['database_psr4_path']}/seeds";
116
117
        $capsule['root_path'] = $root = $this->capsuleRootPath($capsule);
0 ignored issues
show
Unused Code introduced by
The assignment to $root is dead and can be removed.
Loading history...
118
119
        $capsule[
120
            'migrations_dir'
121
        ] = "{$capsule['root_path']}/database/migrations";
122
123
        $capsule['views_dir'] = "{$capsule['root_path']}/resources/views";
124
125
        $capsule['view_prefix'] = "{$name}.resources.views.admin";
126
127
        $capsule['routes_file'] = "{$capsule['root_path']}/routes/admin.php";
128
129
        $capsule['model'] = "{$models}\\{$singular}";
130
131
        $capsule['models_dir'] = $this->namespaceToPath($capsule, $models);
132
133
        $capsule['translation'] = "{$models}\\{$singular}Translation";
134
135
        $capsule['slug'] = "{$models}\\{$singular}Slug";
136
137
        $capsule['revision'] = "{$models}\\{$singular}Revision";
138
139
        $capsule['repository'] = "{$repositories}\\{$singular}Repository";
140
141
        $capsule['repositories_dir'] = $this->namespaceToPath(
142
            $capsule,
143
            $repositories
144
        );
145
146
        $capsule['controller'] = "{$controllers}\\{$singular}Controller";
147
148
        $capsule['controllers_dir'] = $this->namespaceToPath(
149
            $capsule,
150
            $controllers
151
        );
152
153
        $capsule['formRequest'] = "{$requests}\\{$singular}Request";
154
155
        $capsule['requests_dir'] = $this->namespaceToPath($capsule, $requests);
156
157
        $capsule['config_file'] = "$basePath/{$name}/config.php";
158
159
        $capsule['config'] = $this->loadCapsuleConfig($capsule);
160
161
        $this->registerPsr4Autoloader($capsule);
162
163
        return $capsule;
164
    }
165
166
    public function registerPsr4Autoloader($capsule)
167
    {
168
        $this->getAutoloader()->setPsr4(
0 ignored issues
show
Bug introduced by
The method setPsr4() does not exist on Illuminate\Contracts\Foundation\Application. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

168
        $this->getAutoloader()->/** @scrutinizer ignore-call */ setPsr4(

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
169
            $capsule['namespace'] . '\\',
170
            $capsule['psr4_path']
171
        );
172
173
        $this->getAutoloader()->setPsr4(
174
            $capsule['database_namespace'] . '\\',
175
            $capsule['database_psr4_path']
176
        );
177
178
        $this->getAutoloader()->setPsr4(
179
            $capsule['database_namespace'] . '\\Seeds\\',
180
            $capsule['database_psr4_path'] . '/seeds'
181
        );
182
    }
183
184
    public function capsuleRootPath($capsule)
185
    {
186
        return config('twill.capsules.path') . '/' . $capsule['name'] ?? null;
187
    }
188
189
    public function getCapsuleRepositoryClass($model)
190
    {
191
        return $this->getCapsuleByModel($model)['repository'] ?? null;
192
    }
193
194
    public function getCapsuleTranslationClass($model)
195
    {
196
        return $this->getCapsuleByModel($model)['translation'] ?? null;
197
    }
198
199
    public function getCapsuleSlugClass($model)
200
    {
201
        return $this->getCapsuleByModel($model)['slug'] ?? null;
202
    }
203
204
    public function getCapsuleRevisionClass($model)
205
    {
206
        return $this->getCapsuleByModel($model)['revision'] ?? null;
207
    }
208
209
    public function getCapsuleFormRequestClass($model)
210
    {
211
        return $this->getCapsuleByModel($model)['formRequest'] ?? null;
212
    }
213
214
    public function getCapsuleViewPrefix($capsule)
215
    {
216
        return $this->getCapsuleByModule(Str::studly($capsule))[
217
            'view_prefix'
218
        ] ?? null;
219
    }
220
221
    public function namespaceToPath($capsule, $namespace)
222
    {
223
        return $this->capsuleNamespaceToPath(
224
            $namespace,
225
            $capsule['namespace'],
226
            $capsule['root_path']
227
        );
228
    }
229
230
    public function capsuleNamespaceToPath(
231
        $namespace,
232
        $capsuleNamespace,
233
        $rootPath
234
    ) {
235
        $namespace = Str::after($namespace, $capsuleNamespace . '\\');
236
237
        $subdir = $this->getCapsulesSubdir();
238
239
        $subdir = filled($subdir) ? "{$subdir}/" : '';
240
241
        return "{$rootPath}/{$subdir}" . str_replace('\\', '/', $namespace);
242
    }
243
244
    public function getManager()
245
    {
246
        return $this->manager = $this->manager ?? app('twill.capsules.manager');
0 ignored issues
show
Bug Best Practice introduced by
The property manager does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
247
    }
248
249
    public function seedCapsules($illuminateSeeder)
250
    {
251
        $twillSeeder = app(CapsuleSeeder::class);
252
253
        $this->getCapsuleList()->each(function ($capsule) use (
254
            $twillSeeder,
255
            $illuminateSeeder
256
        ) {
257
            if (filled($capsuleSeeder = $this->makeCapsuleSeeder($capsule))) {
258
                $twillSeeder->setCommand($illuminateSeeder->command);
259
260
                $twillSeeder->call($capsuleSeeder);
261
            }
262
        });
263
    }
264
265
    public function makeCapsuleSeeder($capsule)
266
    {
267
        $seeder = "{$capsule['database_namespace']}\\Seeds\DatabaseSeeder";
268
269
        if (class_exists($seeder)) {
270
            return $seeder;
271
        }
272
273
        return null;
274
    }
275
276
    public function capsuleExists($module)
277
    {
278
        return filled($this->getCapsuleByModule($module));
279
    }
280
281
    public function loadCapsuleConfig($capsule)
282
    {
283
        $config = file_exists($file = $capsule['config_file'] ?? 'MISSING-CONFIG-FILE')
284
            ? require $file
285
            : [];
286
287
        $key =
288
            config('twill.capsules.capsule_config_prefix') .
289
            ".{$capsule['module']}";
290
291
        config([
292
            $key => array_replace_recursive(
293
                $config ?? [],
294
                $capsule['config'] ?? []
295
            ),
296
        ]);
297
298
        return $config;
299
    }
300
}
301