BackupImporter::import()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
4
namespace floor12\backup\logic;
5
6
7
use floor12\backup\Exceptions\ConfigurationNotFoundException;
8
use floor12\backup\Exceptions\FileNotFoundException;
9
use floor12\backup\Exceptions\ModuleNotConfiguredException;
10
use floor12\backup\models\Backup;
11
use floor12\backup\models\BackupStatus;
12
use floor12\backup\Module;
13
use Yii;
14
15
class BackupImporter
16
{
17
    /** @var Backup */
18
    protected $model;
19
    /** @var string */
20
    protected $absoluteFilePath;
21
    /** @var string|null */
22
    protected $fileName;
23
    /** @var Module */
24
    protected $module;
25
    /** @var array */
26
    protected $currentConfig;
27
28
    /**
29
     * BackupImporter constructor.
30
     * @param string $config_id
31
     * @param string $absoluteFilePath
32
     */
33
    public function __construct(string $config_id, string $absoluteFilePath, string $fileName = null)
34
    {
35
        $this->module = Yii::$app->getModule('backup');
36
37
        if (!file_exists($absoluteFilePath))
38
            throw new FileNotFoundException();
39
40
        if (!is_array($this->module->configs) || empty($this->module->configs))
41
            throw new ModuleNotConfiguredException();
42
43
        if (!is_array($this->module->configs[$config_id]))
44
            throw new ConfigurationNotFoundException();
45
46
        $this->currentConfig = $this->module->configs[$config_id];
47
        $this->model = new Backup();
48
        $this->model->config_id = $config_id;
49
        $this->absoluteFilePath = $absoluteFilePath;
50
        $this->fileName = $fileName;
51
    }
52
53
    /**
54
     * @return bool
55
     */
56
    public function import()
57
    {
58
        $this->loadDataToBackup();
59
        return $this->model->save();
60
    }
61
62
63
    protected function loadDataToBackup()
64
    {
65
        $this->model->type = $this->currentConfig['type'];
66
        $this->model->type = $this->currentConfig['type'];
67
        $this->model->config_name = $this->currentConfig['title'];
68
        $this->model->size = filesize($this->absoluteFilePath);
69
        $this->model->date = date('Y-m-d H:i:s');
70
        $this->model->filename = $this->fileName ?: basename($this->absoluteFilePath);
71
        $this->model->status = $this->copyFile() ? BackupStatus::IMPORTED : BackupStatus::IMPORT_ERROR;
72
    }
73
74
    /**
75
     * @return bool
76
     */
77
    protected function copyFile()
78
    {
79
        return copy($this->absoluteFilePath, $this->model->getFullPath());
80
    }
81
82
}
83