Gz::handler()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 33
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 5
eloc 17
c 1
b 1
f 0
nc 5
nop 2
dl 0
loc 33
rs 9.3888
1
<?php
2
3
namespace Cesargb\Log\Compress;
4
5
use Exception;
6
7
class Gz
8
{
9
    public const EXTENSION_COMPRESS = 'gz';
10
11
    public function handler(string $filename, ?int $level = null): string
12
    {
13
        $filenameCompress = $filename.'.'.self::EXTENSION_COMPRESS;
14
15
        $fd = fopen($filename, 'r');
16
17
        if ($fd === false) {
18
            throw new Exception("file {$filename} not can read.", 100);
19
        }
20
21
        $level = $level ?? '';
22
23
        $gz = gzopen($filenameCompress, "wb{$level}");
24
25
        if ($gz === false) {
26
            fclose($fd);
27
28
            throw new Exception("file {$filenameCompress} not can open.", 101);
29
        }
30
31
        while (!feof($fd)) {
32
            $data = fread($fd, 1024 * 512);
33
34
            $data = $data === false ? '' : $data;
35
36
            gzwrite($gz, $data);
37
        }
38
39
        gzclose($gz);
40
        fclose($fd);
41
        unlink($filename);
42
43
        return $filenameCompress;
44
    }
45
}
46