1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Rinvex\Support\Traits; |
6
|
|
|
|
7
|
|
|
use Closure; |
8
|
|
|
use Exception; |
9
|
|
|
use Illuminate\Support\Facades\Schema; |
10
|
|
|
use Illuminate\Database\Eloquent\Model; |
11
|
|
|
|
12
|
|
|
trait SeederHelper |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* Seed the given resources. |
16
|
|
|
* |
17
|
|
|
* @param \Illuminate\Database\Eloquent\Model $model |
18
|
|
|
* @param string $seeder |
19
|
|
|
* @param array $initialExclude |
20
|
|
|
* @param \Closure $callback |
|
|
|
|
21
|
|
|
* |
22
|
|
|
* @throws \Exception |
23
|
|
|
* |
24
|
|
|
* @return void |
25
|
|
|
*/ |
26
|
|
|
protected function seedResources(Model $model, string $seeder, array $initialExclude = [], Closure $callback = null) |
27
|
|
|
{ |
28
|
|
|
if (! file_exists($seeder)) { |
29
|
|
|
throw new Exception("Resources seeder file '{$seeder}' does NOT exist!"); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
$this->warn('Seeding: '.str_after($seeder, $this->laravel->basePath().'/')); |
|
|
|
|
33
|
|
|
|
34
|
|
|
// Create new resources |
35
|
|
|
foreach (json_decode(file_get_contents($seeder), true) as $resource) { |
36
|
|
|
$model->firstOrCreate(array_except($resource, $initialExclude), array_only($resource, $initialExclude)); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
$this->info('Seeded: '.str_after($seeder, $this->laravel->basePath().'/')); |
|
|
|
|
40
|
|
|
|
41
|
|
|
! $callback || call_user_func($callback); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Ensure existing database tables. |
46
|
|
|
* |
47
|
|
|
* @param string $package |
48
|
|
|
* |
49
|
|
|
* @return bool |
50
|
|
|
*/ |
51
|
|
|
protected function ensureExistingDatabaseTables(string $package) |
52
|
|
|
{ |
53
|
|
|
if (! $this->hasDatabaseTables($package)) { |
54
|
|
|
$package = explode('/', $package); |
55
|
|
|
$this->call("{$package[0]}:migrate:{$package[1]}"); |
|
|
|
|
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
return true; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Check if all required database tables exists. |
63
|
|
|
* |
64
|
|
|
* @param string $package |
65
|
|
|
* |
66
|
|
|
* @return bool |
67
|
|
|
*/ |
68
|
|
|
protected function hasDatabaseTables(string $package) |
69
|
|
|
{ |
70
|
|
|
$package = explode('/', $package); |
71
|
|
|
|
72
|
|
|
foreach (config("{$package[0]}.{$package[1]}.tables") as $table) { |
73
|
|
|
if (! Schema::hasTable($table)) { |
74
|
|
|
return false; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return true; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
This check looks for
@param
annotations where the type inferred by our type inference engine differs from the declared type.It makes a suggestion as to what type it considers more descriptive.
Most often this is a case of a parameter that can be null in addition to its declared types.