UnzipCommandDecoder::getFiles()   B
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 33
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 33
rs 8.439
c 0
b 0
f 0
cc 6
eloc 20
nc 6
nop 1
1
<?php
2
3
namespace AlreadyExtract\Utils\ExtractorCommandDecoder;
4
5
use Symfony\Component\Process\Process;
6
7
/**
8
 * Created by PhpStorm.
9
 * User: mhor
10
 * Date: 02/08/17
11
 * Time: 23:32
12
 */
13
class UnzipCommandDecoder implements ExtractorCommandDecoderInterface
14
{
15
    /**
16
     *  {@inheritdoc}
17
     */
18
    public function getFiles($path)
19
    {
20
        $process = new Process(sprintf('unzip -l "%s"', $path));
21
        $process->run();
22
        if (!$process->isSuccessful()) {
23
            throw new \RuntimeException($process->getErrorOutput());
24
        }
25
26
        $files = [];
27
        $inFiles = false;
28
        $colSize = null;
29
        foreach (explode(PHP_EOL, trim($process->getOutput())) as $line) {
30
31
            if (strlen(str_replace([' ', '-'], '', $line)) === 0) {
32
                if ($inFiles === false) {
33
                    $colSize = $this->getColSize($line);
34
                }
35
                $inFiles = !$inFiles;
36
                continue;
37
            }
38
39
            if ($inFiles === false) {
40
                continue;
41
            }
42
43
            $files[] = (new File())
44
                ->setUnpackedSize((int) trim((substr($line, $colSize['length'], $colSize['date']))))
45
                ->setPath(trim((substr($line, $colSize['name']))))
46
            ;
47
        }
48
49
        return $files;
50
    }
51
52
    /**
53
     * @param $line
54
     * @return array
55
     */
56
    private function getColSize($line)
57
    {
58
59
        $cols = explode(' ',  preg_replace('~\s+~', ' ', $line));
60
        $length = strlen($cols[0]) + 2;
61
        $date = strlen($cols[1]) + $length + 1;
62
        $time = strlen($cols[2]) + $date + 3;
63
        return [
64
            'length' => 0,
65
            'date' => $length,
66
            'time' => $date,
67
            'name' => $time,
68
        ];
69
    }
70
}