Completed
Push — master ( 953aec...166410 )
by Sebastian
13s
created

YandexDisk::setup()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4.0119

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 10
cts 11
cp 0.9091
rs 9.7333
c 0
b 0
f 0
cc 4
nc 4
nop 1
crap 4.0119
1
<?php
2
3
namespace phpbu\App\Backup\Sync;
4
5
use Arhitector\Yandex\Disk;
6
use phpbu\App\Backup\Collector;
7
use phpbu\App\Backup\Sync;
8
use phpbu\App\Backup\Target;
9
use phpbu\App\Result;
10
use phpbu\App\Util\Arr;
11
use phpbu\App\Util\Path;
12
13
/**
14
 * Yandex.Disk
15
 *
16
 * @package    phpbu
17
 * @subpackage Backup
18
 * @author     Sebastian Feldmann <[email protected]>
19
 * @author     Alexander Palchikov AxelPAL <[email protected]>
20
 * @copyright  Sebastian Feldmann <[email protected]>
21
 * @license    https://opensource.org/licenses/MIT The MIT License (MIT)
22
 * @link       http://phpbu.de/
23
 */
24
class YandexDisk implements Sync\Simulator
25
{
26
    use Cleanable;
27
    /**
28
     * API access token
29
     * Goto https://oauth.yandex.ru/client/new
30
     * create your app
31
     *  - Check all Disks permissions
32
     *  - generate access token:
33
     * 1) Goto https://oauth.yandex.ru/authorize?response_type=token&client_id=APP_ID (replace APP_ID with ID giving to you)
34
     * 2) Then you should get token parameter from GET-parameters of opened page
35
     *
36
     * @var  string
37
     */
38
    protected $token;
39
40
    /**
41
     * Remote path
42
     *
43
     * @var \phpbu\App\Backup\Path
44
     */
45
    protected $path;
46
47
    /**
48
     * @var Disk
49
     */
50
    protected $disk;
51
52
    /**
53
     * Unix timestamp of generating path from placeholder.
54
     *
55
     * @var int
56
     */
57
    protected $time;
58
59
    /**
60
     * (non-PHPDoc)
61
     *
62
     * @param array $config
63
     * @throws Exception
64
     * @throws \phpbu\App\Exception
65
     * @see    \phpbu\App\Backup\Sync::setup()
66
     */
67 8
    public function setup(array $config): void
68
    {
69 8
        if (!class_exists(Disk::class)) {
70
            throw new Exception('Yandex.Disk sdk not loaded: use composer to install "arhitector/yandex"');
71
        }
72 8
        if (!Arr::isSetAndNotEmptyString($config, 'token')) {
73 1
            throw new Exception('API access token is mandatory');
74
        }
75 7
        if (!Arr::isSetAndNotEmptyString($config, 'path')) {
76 1
            throw new Exception('yandex.disk path is mandatory');
77
        }
78 6
        $this->token = $config['token'];
79 6
        $this->path = new \phpbu\App\Backup\Path(Path::withLeadingSlash($config['path']), time());
80
81 6
        $this->setUpCleanable($config);
82 6
    }
83
84
    /**
85
     * (non-PHPDoc)
86
     *
87
     * @param Target $target
88
     * @param Result $result
89
     * @throws Exception
90
     * @see    \phpbu\App\Backup\Sync::sync()
91
     */
92 3
    public function sync(Target $target, Result $result): void
93
    {
94 3
        $sourcePath = $target->getPathname();
95 3
        $yandexDiskPath = $this->path . '/' . $target->getFilename();
96 3
        $this->createDisk();
97
98 3
        $size = null;
99 3
        if (stream_is_local($sourcePath) && file_exists($sourcePath)) {
100
            $size = filesize($sourcePath);
101
        }
102
103
        try {
104 3
            $this->createFolders();
105 3
            $file = $this->createDisk()->getResource($yandexDiskPath);
106 3
            $file->upload($sourcePath, true);
107 2
            if ($file->has()) {
108
                $result->debug('upload: done  (' . $size . ')');
109
            } else {
110 2
                $result->debug('upload: error while uploading file');
111
            }
112 2
            $this->cleanup($target, $result);
113 1
        } catch (\Exception $e) {
114 1
            throw new Exception($e->getMessage(), null, $e);
115
        }
116 2
    }
117
118 3
    private function createFolders(): void
119
    {
120 3
        $folderPath = '';
121 3
        $folderPaths = explode('/', $this->path->getPath());
122 3
        if (!empty($folderPaths)) {
123 3
            foreach ($folderPaths as $folderPathPart) {
124 3
                if (!empty($folderPathPart)) {
125
                    $folderPath .= "/$folderPathPart";
126
                    $file = $this->createDisk()->getResource($folderPath);
127
                    if (!$file->has()) {
128
                        $file->create();
129
                    }
130
                }
131
            }
132
        }
133 3
    }
134
135
    /**
136
     * Simulate the sync execution.
137
     *
138
     * @param Target $target
139
     * @param Result $result
140
     */
141 2 View Code Duplication
    public function simulate(Target $target, Result $result): void
142
    {
143 2
        $result->debug('sync backup to yandex disk' . PHP_EOL);
144
145 2
        $this->isSimulation = true;
146 2
        $this->simulateRemoteCleanup($target, $result);
147 2
    }
148
149
    /**
150
     * Creates the YandexDisk collector.
151
     *
152
     * @param Target $target
153
     * @return Collector
154
     */
155 1
    protected function createCollector(Target $target): Collector
156
    {
157 1
        $collector = new Collector\YandexDisk($target, $this->path, $this->createDisk());
158 1
        $collector->setSimulation($this->isSimulation);
159
160 1
        return $collector;
161
    }
162
163
    /**
164
     * Create a YandexDisk api client.
165
     *
166
     * @return Disk
167
     */
168
    protected function createDisk(): Disk
169
    {
170
        if (!$this->disk) {
171
            $this->disk = new Disk($this->token);
172
        }
173
        return $this->disk;
174
    }
175
}
176