Passed
Push — master ( 9382b9...cf32f2 )
by Quentin
11:18 queued 04:19
created

HasCapsules::getCapsuleByPath()   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['base_namespace'] = config('twill.capsules.namespaces.base');
83
84
        $capsule[
85
            'namespace'
86
        ] = $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

86
        ] = $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...
87
            $capsule['name']
88
        );
89
90
        $capsule['database_namespace'] = "$capsuleNamespace\Database";
91
92
        $capsule['seeds_namespace'] = "{$capsule['database_namespace']}\Seeds";
93
94
        $capsule['model'] = $capsule['models'] = $models =
95
        "{$capsuleNamespace}\\" .
96
        config('twill.capsules.namespaces.models');
97
        $capsule['repositories'] = $repositories =
98
        "{$capsuleNamespace}\\" .
99
        config('twill.capsules.namespaces.repositories');
100
        $capsule['controllers'] = $controllers =
101
        "{$capsuleNamespace}\\" .
102
        config('twill.capsules.namespaces.controllers');
103
        $capsule['requests'] = $requests =
104
        "{$capsuleNamespace}\\" .
105
        config('twill.capsules.namespaces.requests');
106
107
        $capsule['psr4_path'] =
108
            "$basePath/{$name}" .
109
            (filled($this->getCapsulesSubdir())
110
            ? $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

110
            ? /** @scrutinizer ignore-type */ $this->getCapsulesSubdir() . '/'
Loading history...
111
            : '');
112
113
        $capsule['base_path'] = $basePath;
114
115
        $capsule['database_psr4_path'] = "$basePath/{$name}/database";
116
117
        $capsule['seeds_psr4_path'] = "{$capsule['database_psr4_path']}/seeds";
118
119
        $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...
120
121
        $capsule[
122
            'migrations_dir'
123
        ] = "{$capsule['root_path']}/database/migrations";
124
125
        $capsule['views_dir'] = "{$capsule['root_path']}/resources/views";
126
127
        $capsule['view_prefix'] = "{$name}.resources.views.admin";
128
129
        $capsule['routes_file'] = "{$capsule['root_path']}/routes/admin.php";
130
131
        $capsule['model'] = "{$models}\\{$singular}";
132
133
        $capsule['models_dir'] = $this->namespaceToPath($capsule, $models);
134
135
        $capsule['translation'] = "{$models}\\{$singular}Translation";
136
137
        $capsule['slug'] = "{$models}\\{$singular}Slug";
138
139
        $capsule['revision'] = "{$models}\\{$singular}Revision";
140
141
        $capsule['repository'] = "{$repositories}\\{$singular}Repository";
142
143
        $capsule['repositories_dir'] = $this->namespaceToPath(
144
            $capsule,
145
            $repositories
146
        );
147
148
        $capsule['controller'] = "{$controllers}\\{$singular}Controller";
149
150
        $capsule['controllers_dir'] = $this->namespaceToPath(
151
            $capsule,
152
            $controllers
153
        );
154
155
        $capsule['formRequest'] = "{$requests}\\{$singular}Request";
156
157
        $capsule['requests_dir'] = $this->namespaceToPath($capsule, $requests);
158
159
        $capsule['config_file'] = "$basePath/{$name}/config.php";
160
161
        $capsule['config'] = $this->loadCapsuleConfig($capsule);
162
163
        $this->registerPsr4Autoloader($capsule);
164
165
        return $capsule;
166
    }
167
168
    public function registerPsr4Autoloader($capsule)
169
    {
170
        $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

170
        $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...
171
            $capsule['namespace'] . '\\',
172
            $capsule['psr4_path']
173
        );
174
175
        $this->getAutoloader()->setPsr4(
176
            $capsule['database_namespace'] . '\\',
177
            $capsule['database_psr4_path']
178
        );
179
180
        $this->getAutoloader()->setPsr4(
181
            $capsule['database_namespace'] . '\\Seeds\\',
182
            $capsule['database_psr4_path'] . '/seeds'
183
        );
184
    }
185
186
    public function capsuleRootPath($capsule)
187
    {
188
        return config('twill.capsules.path') . '/' . $capsule['name'] ?? null;
189
    }
190
191
    public function getCapsuleRepositoryClass($model)
192
    {
193
        return $this->getCapsuleByModel($model)['repository'] ?? null;
194
    }
195
196
    public function getCapsuleTranslationClass($model)
197
    {
198
        return $this->getCapsuleByModel($model)['translation'] ?? null;
199
    }
200
201
    public function getCapsuleSlugClass($model)
202
    {
203
        return $this->getCapsuleByModel($model)['slug'] ?? null;
204
    }
205
206
    public function getCapsuleRevisionClass($model)
207
    {
208
        return $this->getCapsuleByModel($model)['revision'] ?? null;
209
    }
210
211
    public function getCapsuleFormRequestClass($model)
212
    {
213
        return $this->getCapsuleByModel($model)['formRequest'] ?? null;
214
    }
215
216
    public function getCapsuleViewPrefix($capsule)
217
    {
218
        return $this->getCapsuleByModule(Str::studly($capsule))[
219
            'view_prefix'
220
        ] ?? null;
221
    }
222
223
    public function namespaceToPath($capsule, $namespace)
224
    {
225
        return $this->capsuleNamespaceToPath(
226
            $namespace,
227
            $capsule['namespace'],
228
            $capsule['root_path']
229
        );
230
    }
231
232
    public function capsuleNamespaceToPath(
233
        $namespace,
234
        $capsuleNamespace,
235
        $rootPath
236
    ) {
237
        $namespace = Str::after($namespace, $capsuleNamespace . '\\');
238
239
        $subdir = $this->getCapsulesSubdir();
240
241
        $subdir = filled($subdir) ? "{$subdir}/" : '';
242
243
        return "{$rootPath}/{$subdir}" . str_replace('\\', '/', $namespace);
244
    }
245
246
    public function getManager()
247
    {
248
        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...
249
    }
250
251
    public function seedCapsules($illuminateSeeder)
252
    {
253
        $twillSeeder = app(CapsuleSeeder::class);
254
255
        $this->getCapsuleList()->each(function ($capsule) use (
256
            $twillSeeder,
257
            $illuminateSeeder
258
        ) {
259
            if (filled($capsuleSeeder = $this->makeCapsuleSeeder($capsule))) {
260
                $twillSeeder->setCommand($illuminateSeeder->command);
261
262
                $twillSeeder->call($capsuleSeeder);
263
            }
264
        });
265
    }
266
267
    public function makeCapsuleSeeder($capsule)
268
    {
269
        $seeder = "{$capsule['database_namespace']}\\Seeds\DatabaseSeeder";
270
271
        if (class_exists($seeder)) {
272
            return $seeder;
273
        }
274
275
        return null;
276
    }
277
278
    public function capsuleExists($module)
279
    {
280
        return filled($this->getCapsuleByModule($module));
281
    }
282
283
    public function capsule($string)
284
    {
285
        if (file_exists($string)) {
286
            return $this->getCapsuleByPath($string);
287
        }
288
289
        if (class_exists($string)) {
290
            return $this->getCapsuleByClass($string);
291
        }
292
293
        return $this->getCapsuleByModule($string);
294
    }
295
296
    public function getCapsuleByPath($path)
297
    {
298
        $capsule = $this->getCapsuleList()->first();
299
300
        if (!Str::startsWith($path, $capsule['base_path'])) {
301
            return null;
302
        }
303
304
        $name = Str::before(
305
            Str::after(Str::after($path, $capsule['base_path']), '/'),
306
            '/'
307
        );
308
309
        $name = "{$capsule['base_path']}/$name";
310
311
        return $this->getCapsuleList()
312
            ->where('root_path', $name)
313
            ->first();
314
    }
315
316
    public function getCapsuleByClass($class)
317
    {
318
        $capsule = $this->getCapsuleList()->first();
319
320
        $namespace = Str::beforeLast($class, '\\');
0 ignored issues
show
Unused Code introduced by
The assignment to $namespace is dead and can be removed.
Loading history...
321
322
        if (!Str::startsWith($class, $capsule['base_namespace'])) {
323
            return null;
324
        }
325
326
        $name = Str::before(
327
            Str::after(Str::after($class, $capsule['base_namespace']), '\\'),
328
            '\\'
329
        );
330
331
        $name = "{$capsule['base_namespace']}\\$name";
332
333
        return $this->getCapsuleList()
334
            ->where('namespace', $name)
335
            ->first();
336
    }
337
338
    public function loadCapsuleConfig($capsule)
339
    {
340
        $config = file_exists($file = $capsule['config_file'] ?? 'MISSING-CONFIG-FILE')
341
        ? require $file
342
        : [];
343
344
        $key =
345
            config('twill.capsules.capsule_config_prefix') .
346
            ".{$capsule['module']}";
347
348
        config([
349
            $key => array_replace_recursive(
350
                $config ?? [],
351
                $capsule['config'] ?? []
352
            ),
353
        ]);
354
355
        return $config;
356
    }
357
}
358