Completed
Pull Request — master (#1163)
by
unknown
02:55
created

LaravelDatabaseRepository::all()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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