WaitForDb   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 17
dl 0
loc 46
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A handle() 0 24 4
1
<?php
2
3
namespace Sfneal\Cruise\Commands;
4
5
use Exception;
6
use Illuminate\Console\Command;
7
use Illuminate\Support\Facades\DB;
8
9
class WaitForDb extends Command
10
{
11
    /**
12
     * The name and signature of the console command.
13
     *
14
     * @var string
15
     */
16
    protected $signature = 'db:wait {--max-attempts=20} {--interval=10}';
17
18
    /**
19
     * The console command description.
20
     *
21
     * @var string
22
     */
23
    protected $description = 'Wait for the DB connection to become available';
24
25
    /**
26
     * Execute the console command.
27
     *
28
     *
29
     * @throws Exception
30
     */
31
    public function handle(): int
32
    {
33
        $start = now();
34
35
        $this->info('Waiting for the DB connection to become available.');
36
37
        foreach (range(1, $this->option('max-attempts')) as $attempt) {
38
            try {
39
                DB::connection()->getPdo();
40
                $time = abs(now()->diffInSeconds($start));
41
                $this->info("Took {$time} seconds to connect to the DB.");
42
43
                return self::SUCCESS;
44
            } catch (Exception $exception) {
45
                if ($attempt == $this->option('max-attempts')) {
46
                    throw $exception;
47
                }
48
49
                $this->info("Connect to DB attempt #{$attempt} failed, trying again in {$this->option('interval')} seconds");
50
                sleep($this->option('interval'));
51
            }
52
        }
53
54
        return self::FAILURE;
55
    }
56
}
57