Completed
Pull Request — master (#424)
by
unknown
02:08
created

Gzip::compress()   B

Complexity

Conditions 5
Paths 39

Size

Total Lines 32
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 19
nc 39
nop 0
dl 0
loc 32
rs 8.439
c 0
b 0
f 0
1
<?php
2
3
namespace Spatie\Backup\Tasks\Backup;
4
5
class Gzip
6
{
7
    /** @var string */
8
    public $originalFilePath;
9
10
    /** @var string */
11
    public $filePath;
12
13
    /** @var bool */
14
    public $failed;
15
16
    public function __construct(string $filePath)
17
    {
18
        $this->originalFilePath = $filePath;
19
20
        $this->filePath = $this->compress();
21
22
        $this->failed = $this->originalFilePath == $this->filePath;
23
    }
24
25
    /**
26
     * @return string
27
     */
28
    protected function compress()
29
    {
30
        $gzipPath = $this->originalFilePath.'.gz';
31
32
        $gzipOut = false;
33
        $gzipIn = false;
34
35
        try {
36
            $gzipOut = gzopen($gzipPath, 'w9');
37
            $gzipIn = fopen($this->originalFilePath, 'rb');
38
39
            while (!feof($gzipIn)) {
40
                gzwrite($gzipOut, fread($gzipIn, 1024 * 512));
41
            }
42
43
            fclose($gzipIn);
44
            gzclose($gzipOut);
45
        } catch (\Exception $exception) {
46
            if (is_resource($gzipOut)) {
47
                gzclose($gzipOut);
48
                unlink($gzipPath);
49
            }
50
51
            if (is_resource($gzipIn)) {
52
                fclose($gzipIn);
53
            }
54
55
            return $this->originalFilePath;
56
        }
57
58
        return $gzipPath;
59
    }
60
61
    /**
62
     * @return int
63
     */
64
    public function oldFileSize()
65
    {
66
        return filesize($this->originalFilePath);
67
    }
68
69
    /**
70
     * @return int
71
     */
72
    public function newFileSize()
73
    {
74
        return filesize($this->filePath);
75
    }
76
}
77