Passed
Push — master ( f218e6...f51c1b )
by Arthur
04:59
created

DemoSeedCommand::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Foundation\Console;
4
5
use Foundation\Contracts\DemoSeederContract;
6
use Foundation\Exceptions\Exception;
7
use Foundation\Services\BootstrapRegistrarService;
8
use Illuminate\Console\Command;
9
use Illuminate\Database\Eloquent\Model;
10
11
class DemoSeedCommand extends Command
12
{
13
14
    /**
15
     * The console command name.
16
     *
17
     * @var string
18
     */
19
    protected $name = 'db:seed:demo';
20
21
    /**
22
     * The service that registers all module entities.
23
     *
24
     * @var BootstrapRegistrarService
25
     */
26
    protected $service;
27
28
    public function __construct(BootstrapRegistrarService $service)
29
    {
30
        parent::__construct();
31
        $this->service = $service;
32
    }
33
34
    /**
35
     * Execute the console command.
36
     *
37
     * @return void
38
     */
39
    public function handle()
40
    {
41
        Model::unguarded(function () {
42
            $seeders = $this->getSeeders();
43
44
            $priorities = [];
45
            $prioritySeeders = [];
46
            $nonPrioritySeeders = [];
47
            foreach ($seeders as $seeder) {
48
                $priority = get_class_property($seeder, 'priority');
49
                if (!is_int($priority) && $priority !== null) {
50
                    throw new Exception('Priority on seeder must be integer');
51
                } elseif ($priority !== null && in_array($priority, $priorities)) {
52
                    throw new Exception("Duplicate priority on seeder $seeder with $prioritySeeders[$priority]");
53
                } elseif ($priority === null) {
54
                    $nonPrioritySeeders[] = $seeder;
55
                } else {
56
                    $priorities[] = $priority;
57
                    $prioritySeeders[$priority] = $seeder;
58
                }
59
            }
60
            ksort($prioritySeeders);
61
            $seeders = array_merge($prioritySeeders, $nonPrioritySeeders);
62
63
            foreach ($seeders as $seeder) {
64
                $seeder = $this->laravel->make($seeder);
65
                $seeder->__invoke();
66
                if (class_implements_interface($seeder, DemoSeederContract::class))
67
                    $seeder->runDemo();
68
            }
69
        });
70
71
        $this->info('Database seeding completed successfully.');
72
    }
73
74
    protected function getSeeders(): array
75
    {
76
        $this->service = $this->laravel->make(BootstrapRegistrarService::class);
77
78
        return $this->service->getSeeders() ?? [];
79
    }
80
}
81