BackupCreate::setUpActiveConfig()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 5
rs 10
cc 2
nc 2
nop 0
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: floor12
5
 * Date: 18.09.2018
6
 * Time: 20:35
7
 */
8
9
namespace floor12\backup\logic;
10
11
use ErrorException;
12
use floor12\backup\Exceptions\ConfigurationNotFoundException;
13
use floor12\backup\Exceptions\FolderDumpException;
14
use floor12\backup\Exceptions\ModuleNotConfiguredException;
15
use floor12\backup\Exceptions\MysqlDumpException;
16
use floor12\backup\Exceptions\PostgresDumpException;
17
use floor12\backup\models\Backup;
18
use floor12\backup\models\BackupStatus;
19
use floor12\backup\models\BackupType;
20
use floor12\backup\models\IOPriority;
21
use Throwable;
22
use Yii;
23
use yii\base\InvalidConfigException as InvalidConfigExceptionAlias;
24
use yii\db\Connection;
25
use yii\db\StaleObjectException;
26
27
/**
28
 * Class BackupCreate
29
 * @package floor12\backup\logic
30
 * @property Backup $model
31
 * @property array $configs
32
 * @property array $_config
33
 */
34
class BackupCreate
35
{
36
    /** @var array */
37
    private $configs = [];
38
    /** @var array */
39
    private $currentConfig = [];
40
    /** @var string */
41
    private $config_id;
42
    /** @var Backup */
43
    private $model;
44
45
    /**
46
     * BackupCreate constructor.
47
     * @param string $config_id
48
     * @throws InvalidConfigExceptionAlias
49
     * @throws ErrorException
50
     */
51
    public function __construct(string $config_id)
52
    {
53
        $this->config_id = $config_id;
54
        $this->loadConfigs();
55
        $this->setUpActiveConfig();
56
    }
57
58
    /**
59
     * @throws ModuleNotConfiguredException
60
     */
61
    protected function loadConfigs()
62
    {
63
        $this->configs = Yii::$app->getModule('backup')->configs;
0 ignored issues
show
Documentation Bug introduced by
It seems like Yii::app->getModule('backup')->configs can also be of type object. However, the property $configs is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
64
        if (!is_array($this->configs) || !sizeof($this->configs))
65
            throw new ModuleNotConfiguredException('Backup configs is empty');
66
    }
67
68
    /**
69
     * @param string $config_id
70
     * @throws ConfigurationNotFoundException
71
     */
72
    protected function setUpActiveConfig()
73
    {
74
        if (!is_array($this->configs[$this->config_id]))
75
            throw new ConfigurationNotFoundException("Configuration `{$this->config_id}` not found.");
76
        $this->currentConfig = $this->configs[$this->config_id];
77
    }
78
79
    /**
80
     * @return void
81
     * @throws InvalidConfigExceptionAlias
82
     * @throws Throwable
83
     * @throws StaleObjectException
84
     */
85
    public function run()
86
    {
87
        $this->deleteOldFiles();
88
        $this->createBackupItem();
89
90
        if (empty($this->currentConfig['io']))
91
            $this->currentConfig['io'] = IOPriority::IDLE;
92
        try {
93
            if ($this->currentConfig['type'] == BackupType::DB) {
94
                $connection = Yii::$app->{$this->currentConfig['connection']};
95
                Yii::createObject(DatabaseBackuper::class, [$this->model->getFullPath(), $connection, $this->currentConfig['io']])->backup();
96
            }
97
98
            if ($this->currentConfig['type'] == BackupType::FILES) {
99
                $targetPath = Yii::getAlias($this->currentConfig['path']);
100
                Yii::createObject(FolderBackupMaker::class, [$this->model->getFullPath(), $targetPath, $this->currentConfig['io']])->execute();
101
            }
102
        } catch (MysqlDumpException|PostgresDumpException|FolderDumpException $exception) {
103
            $this->setBackupFailed();
104
            throw new $exception;
105
        }
106
107
        $this->setBackupDone();
108
    }
109
110
    /**
111
     * Delete old files if current config has files count limit
112
     * @throws Throwable
113
     * @throws StaleObjectException
114
     */
115
    protected function deleteOldFiles()
116
    {
117
        if (!isset($this->currentConfig['limit']) || empty($this->currentConfig['limit']))
118
            return false;
119
        $backups = Backup::find()
120
            ->where(['config_id' => $this->config_id])
121
            ->orderBy('date DESC')
122
            ->offset($this->currentConfig['limit'] - 1)
123
            ->all();
124
125
        if ($backups)
126
            foreach ($backups as $backup)
127
                $backup->delete();
128
    }
129
130
    /**
131
     * @return bool
132
     */
133
    protected function createBackupItem()
134
    {
135
        $this->model = new Backup();
136
        $this->model->date = date('Y-m-d H:i:s');
137
        $this->model->status = BackupStatus::IN_PROCESS;
138
        $this->model->type = $this->currentConfig['type'];
139
        $this->model->config_id = $this->config_id;
140
        $this->model->config_name = $this->currentConfig['title'];
141
        $this->model->filename = $this->createFileName();
142
        return $this->model->save();
143
    }
144
145
    /** Generate filename
146
     * @return string
147
     */
148
    private function createFileName()
149
    {
150
        $extension = Backup::EXT_ZIP;
151
        if ($this->model->type == BackupType::DB) {
152
            $extension = Backup::EXT_TGZ;
153
            /** @var Connection $connection */
154
            $connection = Yii::$app->{$this->currentConfig['connection']};
155
            if ($connection->driverName == 'pgsql')
156
                $extension = Backup::EXT_DUMP;
157
        }
158
        $date = date("Y-m-d_H-i-s");
159
        $rand = substr(md5(rand(0, 9999)), 0, 3);
160
        return "{$this->config_id}_{$date}_{$rand}.{$extension}";
161
    }
162
163
    /**
164
     * @return bool
165
     */
166
    protected function setBackupDone()
167
    {
168
        $this->model->status = BackupStatus::DONE;
169
        $this->model->updateFileSize();
170
        return $this->model->save();
171
    }
172
173
    /**
174
     * @return bool
175
     */
176
    protected function setBackupFailed()
177
    {
178
        $this->model->status = BackupStatus::ERROR;
179
        @unlink($this->model->getFullPath());
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

179
        /** @scrutinizer ignore-unhandled */ @unlink($this->model->getFullPath());

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
180
        return $this->model->save();
181
    }
182
183
}
184