Passed
Push — master ( 07e0f1...85dc69 )
by Attila
02:46
created

BaseServiceProvider::areViewsEnabled()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * Contains the BaseServiceProvider class.
7
 *
8
 * @copyright   Copyright (c) 2016 Attila Fulop
9
 * @author      Attila Fulop
10
 * @license     MIT
11
 * @since       2016-12-29
12
 *
13
 */
14
15
namespace Konekt\Concord;
16
17
use Illuminate\Support\ServiceProvider;
18
use Konekt\Concord\Concerns\HasModuleConfig;
19
use Konekt\Concord\Contracts\Concord as ConcordContract;
20
use Konekt\Concord\Contracts\Convention;
21
use Konekt\Concord\Contracts\Module;
22
use Konekt\Concord\Module\Kind;
23
use Konekt\Concord\Module\Manifest;
24
use Konekt\Concord\Routing\RouteRegistrar;
25
use ReflectionClass;
26
27
abstract class BaseServiceProvider extends ServiceProvider implements Module
28
{
29
    use HasModuleConfig;
30
31
    /** @var  string */
32
    protected $basePath;
33
34
    /** @var  Manifest */
35
    protected $manifest;
36
37
    /** @var  string */
38
    protected $namespaceRoot;
39
40
    /** @var  string */
41
    protected $id;
42
43
    /** @var  array */
44
    protected $models = [];
45
46
    /** @var  array */
47
    protected $enums = [];
48
49
    /** @var  array */
50
    protected $requests = [];
51
52
    /** @var  ConcordContract */
53
    protected $concord;
54
55
    /** @var  Convention */
56
    protected $convention;
57
58
    /** @var  Kind */
59
    protected $kind;
60
61
    /**
62
     * ModuleServiceProvider class constructor
63
     *
64
     * @param \Illuminate\Contracts\Foundation\Application $app
65
     */
66
    public function __construct($app)
67
    {
68
        parent::__construct($app);
69
70
        $this->concord = $app->make(ConcordContract::class); // retrieve the concord singleton
71
        $this->convention = $this->concord->getConvention(); // storing to get rid of train wrecks
72
        $this->kind = Kind::create(static::$_kind);
73
        $this->basePath = dirname(dirname((new ReflectionClass(static::class))->getFileName()));
74
        $this->namespaceRoot = str_replace(
75
            sprintf(
76
                '\\%s\\ModuleServiceProvider',
77
                str_replace('/', '\\', $this->convention->providersFolder())
78
            ),
79
            '',
80
            static::class
81
        );
82
        $this->id = $this->getModuleId();
83
    }
84
85
    public function register()
86
    {
87
        $this->loadConfiguration();
88
89
        if (true === $this->config('event_listeners')) {
90
            $this->registerEventServiceProvider();
91
        }
92
    }
93
94
    /**
95
     * @inheritdoc
96
     */
97
    public function boot()
98
    {
99
        if ($this->areMigrationsEnabled()) {
100
            $this->registerMigrations();
101
        }
102
103
        if ($this->areModelsEnabled()) {
104
            $this->registerModels();
105
            $this->registerEnums();
106
            $this->registerRequestTypes();
107
        }
108
109
        if ($this->areViewsEnabled()) {
110
            $this->registerViews();
111
        }
112
113
        if ($routes = $this->config('routes', true)) {
114
            $this->registerRoutes($routes);
115
        }
116
117
        $this->publishes([
118
            $this->getBasePath() . '/' . $this->convention->migrationsFolder() =>
119
                database_path('migrations')
120
        ], 'migrations');
121
    }
122
123
    public function getId(): string
124
    {
125
        return $this->id;
126
    }
127
128
    /**
129
     * @return Manifest
130
     */
131
    public function getManifest(): Manifest
132
    {
133
        if (!$this->manifest) {
134
            $data = include($this->basePath . '/' . $this->convention->manifestFile());
135
136
            $name = $data['name'] ?? 'N/A';
137
            $version = $data['version'] ?? 'n/a';
138
139
            $this->manifest = new Manifest($name, $version);
140
        }
141
142
        return $this->manifest;
143
    }
144
145
    /**
146
     * Returns the root folder on the filesystem containing the module
147
     *
148
     * @return string
149
     */
150
    public function getBasePath(): string
151
    {
152
        return $this->basePath;
153
    }
154
155
    /**
156
     * @inheritdoc
157
     */
158
    public function getKind(): Kind
159
    {
160
        return $this->kind;
161
    }
162
163
    /**
164
     * Returns the folder where the module/box configuration files are
165
     *
166
     * @return string
167
     */
168
    public function getConfigPath(): string
169
    {
170
        return $this->getBasePath() . '/' . $this->convention->configFolder();
171
    }
172
173
    /**
174
     * Returns the module's root (topmost) namespace
175
     *
176
     * @return string
177
     */
178
    public function getNamespaceRoot(): string
179
    {
180
        return $this->namespaceRoot;
181
    }
182
183
    /**
184
     * Returns the short (abbreviated) name of the module
185
     * E.g. Konekt\AppShell => app_shell
186
     */
187
    public function shortName()
188
    {
189
        $id = $this->getModuleId();
190
        $p = strrpos($id, '.');
191
192
        return $p ? substr($id, $p + 1) : $id;
193
    }
194
195
    /**
196
     * Returns a standard module name based on the module provider's classname
197
     *
198
     * Eg.: '\Vendor\Module\Services\ModuleServiceProvider' -> 'vendor.module'
199
     *
200
     * @param string    $classname
201
     *
202
     * @see concord_module_id
203
     *
204
     * @return string
205
     */
206
    protected function getModuleId($classname = null)
207
    {
208
        return concord_module_id($classname ?: static::class);
209
    }
210
211
    /**
212
     * Register the module's migrations
213
     */
214
    protected function registerMigrations()
215
    {
216
        $path = $this->getBasePath() . '/' . $this->convention->migrationsFolder();
217
218
        if ($this->app->runningInConsole() && is_dir($path)) {
219
            $this->loadMigrationsFrom($path);
220
        }
221
    }
222
223
    /**
224
     * Register models in a box/module
225
     */
226
    protected function registerModels()
227
    {
228
        foreach ($this->models as $key => $model) {
229
            $contract = is_string($key) ? $key : $this->convention->contractForModel($model);
230
            $this->concord->registerModel($contract, $model, config('concord.register_route_models', true));
231
        }
232
    }
233
234
    /**
235
     * Register enums in a box/module
236
     */
237
    protected function registerEnums()
238
    {
239
        foreach ($this->enums as $key => $enum) {
240
            $contract = is_string($key) ? $key : $this->convention->contractForEnum($enum);
241
            $this->concord->registerEnum($contract, $enum);
242
        }
243
    }
244
245
    /**
246
     * Register request types in a box/module
247
     */
248
    protected function registerRequestTypes()
249
    {
250
        foreach ($this->requests as $key => $requestType) {
251
            $contract = is_string($key) ? $key : $this->convention->contractForRequest($requestType);
252
            $this->concord->registerRequest($contract, $requestType);
253
        }
254
    }
255
256
    /**
257
     * Register the views folder, in a separate namespace
258
     */
259
    protected function registerViews()
260
    {
261
        $path = $this->getBasePath() . '/' . $this->convention->viewsFolder();
262
        $namespace = $this->config('views.namespace', $this->shortName());
263
264
        if (is_dir($path)) {
265
            $this->loadViewsFrom($path, $namespace);
266
        }
267
    }
268
269
    /**
270
     * Registers the event service provider of the module/config (ie. event-listener bindings)
271
     */
272
    protected function registerEventServiceProvider()
273
    {
274
        $eventServiceProviderClass = sprintf(
275
            '%s\\%s\\EventServiceProvider',
276
            $this->namespaceRoot,
277
            str_replace('/', '\\', $this->convention->providersFolder())
278
        );
279
280
        if (class_exists($eventServiceProviderClass)) {
281
            $this->app->register($eventServiceProviderClass);
282
        }
283
    }
284
285
    protected function loadConfiguration()
286
    {
287
        $cfgFile = sprintf('%s/%s', $this->getConfigPath(), $this->configFileName);
288
289
        if (file_exists($cfgFile)) {
290
            $this->mergeConfigFrom($cfgFile, $this->getId());
291
        }
292
    }
293
294
    protected function registerRoutes($routes): void
295
    {
296
        $routeRegistrar = new RouteRegistrar($this, $this->convention);
297
        if (true === $routes) {
298
            $routeRegistrar->registerAllRoutes();
299
        } elseif (isset($routes['files'])) {
300
            $routeRegistrar->registerRoutes($this->config('routes.files'), $this->config('routes'));
301
        } elseif (isset($routes[0]) && is_array($routes[0])) {
302
            foreach ($routes as $route) {
303
                $routeRegistrar->registerRoutes($route['files'], $route);
304
            }
305
        }
306
    }
307
}
308