Completed
Push — master ( 34b930...ab3e16 )
by Avtandil
05:13
created

DbDump::getPath()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 15
ccs 0
cts 13
cp 0
rs 9.4285
cc 3
eloc 9
nc 3
nop 1
crap 12
1
<?php
2
/*
3
 * This file is part of the Laravel Lodash package.
4
 *
5
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
declare(strict_types=1);
11
12
namespace Longman\LaravelLodash\Commands;
13
14
use Carbon\Carbon;
15
use DB;
16
use Illuminate\Console\Command;
17
use Symfony\Component\Process\Exception\ProcessFailedException;
18
use Symfony\Component\Process\Process;
19
20
class DbDump extends Command
21
{
22
    /**
23
     * The name and signature of the console command.
24
     *
25
     * @var string
26
     */
27
    protected $signature = 'db:dump {--database= : The database connection to use.}
28
                    {--path= : Folder path for store database dump files.}';
29
30
    /**
31
     * The console command description.
32
     *
33
     * @var string
34
     */
35
    protected $description = 'Dump database to sql file using mysqldump CLI utility.';
36
37
    /**
38
     * Execute the console command.
39
     *
40
     * @return mixed
41
     */
42
    public function handle()
43
    {
44
        $db_conn = $this->getDatabase();
45
        $connection = DB::connection($db_conn);
46
        $db_name = $connection->getConfig('database');
47
        $filename = $db_name . '_' . Carbon::now()->format('Ymd_His') . '.sql';
48
49
        $path = $this->getPath($filename);
50
51
        $process = new Process('mysqldump --host=' . $connection->getConfig('host') . ' --user=' . $connection->getConfig('username') . ' --password=' . $connection->getConfig('password') . ' ' . $db_name . ' > ' . $path);
52
        $process->run();
53
54
        // Executes after the command finishes
55
        if (! $process->isSuccessful()) {
56
            throw new ProcessFailedException($process);
57
        }
58
59
        $this->info('Database backup saved to: ' . $path);
60
    }
61
62
    protected function getPath(string $filename): string
63
    {
64
        $path = $this->input->getOption('path');
65
        if ($path) {
66
            if (! is_dir(base_path($path))) {
67
                mkdir(base_path($path), 0777, true);
68
            }
69
70
            $path = base_path($path . DIRECTORY_SEPARATOR . $filename);
71
        } else {
72
            $path = storage_path($filename);
73
        }
74
75
        return $path;
76
    }
77
78
    protected function getDatabase(): string
79
    {
80
        $database = $this->input->getOption('database');
81
82
        return $database ?: $this->laravel['config']['database.default'];
83
    }
84
}
85