Password::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 14
rs 10
c 3
b 0
f 0
1
<?php
2
3
namespace Olssonm\BackupShield\Factories;
4
5
use Illuminate\Support\Collection;
6
use Olssonm\BackupShield\Encryption;
7
8
use \ZipArchive;
9
10
class Password
11
{
12
    /**
13
     * Path to .zip-file
14
     *
15
     * @var string
16
     */
17
    public $path;
18
19
    /**
20
     * The chosen password
21
     *
22
     * @var string
23
     */
24
    protected $password;
25
26
    /**
27
     * Read the .zip, apply password and encryption, then rewrite the file
28
     *
29
     * @param string     $path
30
     */
31
    function __construct(string $path)
32
    {
33
        $this->password = config('backup-shield.password');
34
35
        // If no password is set, just return the backup-path
36
        if (!$this->password) { 
37
            return $this->path = $path;
38
        }
39
40
        consoleOutput()->info('Applying password and encryption to zip using ZipArchive...');
41
        
42
        $this->makeZip($path);
43
44
        consoleOutput()->info('Successfully applied password and encryption to zip.');
45
    }
46
47
    /**
48
     * Use native PHP ZipArchive
49
     *
50
     * @return  void
51
     */
52
    protected function makeZip(string $path): void
53
    {
54
        $encryption = config('backup-shield.encryption');
55
56
        $zipArchive = new ZipArchive;
57
58
        $zipArchive->open($path, ZipArchive::OVERWRITE);
59
        $zipArchive->addFile($path, 'backup.zip');
60
        $zipArchive->setPassword($this->password);
61
        Collection::times($zipArchive->numFiles, function($i) use ($zipArchive, $encryption) {
62
            $zipArchive->setEncryptionIndex($i - 1, $encryption);
63
        });
64
        $zipArchive->close();
65
66
        $this->path = $path;
67
    }
68
}
69