Completed
Pull Request — master (#1163)
by
unknown
09:19
created

LaravelDatabaseRepository::migrateFileToDatabase()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 5
nop 0
dl 0
loc 20
rs 9.6
c 0
b 0
f 0
1
<?php
2
3
namespace Nwidart\Modules\Laravel;
4
5
use Illuminate\Contracts\Filesystem\FileNotFoundException;
6
use Illuminate\Support\Facades\Schema;
7
use Illuminate\Support\Str;
8
use Nwidart\Modules\Collection;
9
use Nwidart\Modules\Contracts\ActivatorInterface;
10
use Nwidart\Modules\Contracts\DatabaseRepositoryInterface;
11
use Nwidart\Modules\Entities\ModuleEntity;
12
use Nwidart\Modules\Exceptions\ModuleNotFoundException;
13
use Nwidart\Modules\Generators\DatabaseModuleGenerator;
14
use Nwidart\Modules\Json;
15
16
class LaravelDatabaseRepository extends LaravelFileRepository implements DatabaseRepositoryInterface
17
{
18
    /**
19
     * {@inheritdoc}
20
     */
21
    protected function createModule(...$args)
22
    {
23
        return new DatabaseModule(...$args);
0 ignored issues
show
Bug introduced by
The call to DatabaseModule::__construct() misses some required arguments starting with $name.
Loading history...
Documentation introduced by
$args is of type array<integer,?>, but the function expects a object<Illuminate\Container\Container>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
24
    }
25
26
    /**
27
     * @return ModuleEntity
28
     */
29
    public function getModel()
30
    {
31
        return new ModuleEntity();
32
    }
33
34
    /**
35
     * Scan & get all available modules.
36
     */
37
    public function scan()
38
    {
39
        /**
40
         * @var ModuleEntity[] $rows
41
         */
42
        $rows = $this->getModel()->get();
43
        $modules = [];
44
        if (!empty($rows)) {
45
            foreach ($rows as $row) {
46
                if (file_exists($row->path)) {
47
                    $modules[$row->name] = $this->createModule($this->app, $row->name, $row->path);
48
                }
49
            }
50
        }
51
52
        return $modules;
53
    }
54
55
    /**
56
     * Determine whether the given module exist.
57
     *
58
     * @param $name
59
     *
60
     * @return bool
61
     */
62
    public function has($name): bool
63
    {
64
        return $this->getModel()->where('name', $name)->exists();
65
    }
66
67
    /**
68
     * @inheritDoc
69
     */
70
    public function find(string $name)
71
    {
72
        /** @var ModuleEntity $module */
73
        $module = $this->getModel()->where('name', $name)->first();
74
        if (!$module) {
75
            return null;
76
        }
77
        if (!file_exists($module->path)) {
78
            return null;
79
        }
80
81
        return $this->createModule($this->app, $module->name, $module->path);
82
    }
83
84
    /**
85
     * Get all modules as laravel collection instance.
86
     *
87
     * @param $status
88
     *
89
     * @return Collection
90
     */
91
    public function collections($status = 1): Collection
92
    {
93
        return new Collection($this->getByStatus($status));
94
    }
95
96
    /**
97
     * Get module path for a specific module.
98
     *
99
     * @param $name
100
     *
101
     * @return string
102
     */
103
    public function getModulePath($name)
104
    {
105
        $module = $this->find($name);
106
        if ($module) {
107
            return $module->getPath() . '/';
108
        }
109
110
        return $this->getPath() . '/' . Str::studly($name) . '/';
111
    }
112
113
    /**
114
     * Get modules by status.
115
     *
116
     * @param $status
117
     *
118
     * @return array
119
     */
120 View Code Duplication
    public function getByStatus($status): array
121
    {
122
        $modules = [];
123
124
        foreach ($this->all() as $name => $module) {
125
            if ($module->isStatus($status) == $status) {
126
                $modules[$name] = $module;
127
            }
128
        }
129
130
        return $modules;
131
    }
132
133
    /**
134
     * Format the cached data as array of modules.
135
     *
136
     * @param array $cached
137
     *
138
     * @return array
139
     */
140
    protected function formatCached($cached)
141
    {
142
        $modules = [];
143
144
        foreach ($cached as $moduleEntity) {
145
            $module = $this->createModule($this->app, $moduleEntity['name'], $moduleEntity['path']);
146
            $module->setAttributes($moduleEntity->toArray());
147
            $modules[$moduleEntity['name']] = $module;
148
        }
149
150
        return $modules;
151
    }
152
153
    /**
154
     * Get cached modules from database.
155
     *
156
     * @return ModuleEntity[]
157
     */
158
    public function getCached()
159
    {
160
        return $this->app['cache']->remember($this->config('cache.key'), $this->config('cache.lifetime'), function () {
161
            return $this->getModel()->all();
162
        });
163
    }
164
165
    public function all(): array
166
    {
167
        // Do not load or register if there are no modules table yet.
168
        if (!Schema::hasTable('modules')) {
169
            return [];
170
        }
171
172
        return parent::all();
173
    }
174
175
    public function create($params, $force = true, $isApi = true, $isPlain = true)
176
    {
177
        $moduleType = $this->getModuleType($isApi, $isPlain); // Custom later.
178
        /** @var DatabaseModuleGenerator $generator */
179
        $generator = with(new DatabaseModuleGenerator($params['name']));
180
        $code = $generator
181
            ->setFilesystem(app('files'))
182
            ->setModule($this)
183
            ->setConfig(app('config'))
184
            ->setActivator(app(ActivatorInterface::class))
185
            ->setForce($force)
186
            ->setType($moduleType)
187
            ->setActive($params['is_active'])
188
            ->setSilentOutput(true) // Don't use console output
189
            ->generate();
190
191
        return $code ? $this->find($params['name']) : false;
192
    }
193
194
    /**
195
     * Get module type .
196
     *
197
     * @param bool $isApi
198
     * @param bool $isPlain
199
     *
200
     * @return string
201
     */
202
    public function getModuleType($isApi = true, $isPlain = true)
203
    {
204
        if ($isPlain && $isApi) {
205
            return 'web';
206
        }
207
        if ($isPlain) {
208
            return 'plain';
209
        } elseif ($isApi) {
210
            return 'api';
211
        } else {
212
            return 'web';
213
        }
214
    }
215
216
    /**
217
     * Get module used for cli session.
218
     * @return string
219
     * @throws ModuleNotFoundException|FileNotFoundException
220
     */
221
    public function getUsedNow(): string
222
    {
223
        $module = $this->getFiles()->get($this->getUsedStoragePath());
224
        if (!$module) {
225
            return '';
226
        }
227
228
        return $this->findOrFail($module);
229
    }
230
231
    public function migrateFileToDatabase()
232
    {
233
        $paths = $this->getScanPaths();
234
        $modules = [];
235
236
        foreach ($paths as $key => $path) {
237
            $manifests = $this->getFiles()->glob("{$path}/module.json");
238
239
            is_array($manifests) || $manifests = [];
240
241
            foreach ($manifests as $manifest) {
242
                $json = Json::make($manifest);
243
                $data = $json->getAttributes();
244
                $data['path'] = str_replace('module.json', '', $json->getPath());
245
                $modules[] = $this->getModel()->create($data);
246
            }
247
        }
248
249
        return $modules;
250
    }
251
}
252