Passed
Push — master ( e5cdcf...8113ff )
by Carlos C
02:33 queued 11s
created

XlsxToCsvFolderConverter::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpCfdi\SatCatalogosPopulate\Converters;
6
7
use PhpCfdi\SatCatalogosPopulate\Utils\ShellExec;
8
use PhpCfdi\SatCatalogosPopulate\Utils\WhichTrait;
9
use RuntimeException;
10
11
class XlsxToCsvFolderConverter
12
{
13
    use WhichTrait;
14
15
    /** @var string Location of xlsx2csvPath executable */
16
    private string $xlsx2csvPath;
17
18 4
    public function __construct(string $xlsx2csvPath = '')
19
    {
20 4
        if ('' === $xlsx2csvPath) {
21 4
            $xlsx2csvPath = $this->which('xlsx2csv');
22
        }
23 4
        $this->xlsx2csvPath = $xlsx2csvPath;
24
    }
25
26 4
    public function xlsx2csvPath(): string
27
    {
28 4
        return $this->xlsx2csvPath;
29
    }
30
31 4
    public function convert(string $source, string $destination): void
32
    {
33 4
        if ('' === $destination) {
34
            throw new RuntimeException('Destination is empty');
35
        }
36 4
        if (! is_dir($destination) || ! is_writable($destination)) {
37
            throw new RuntimeException("Destination directory $destination is not a directory or is not writable");
38
        }
39
40 4
        $command = escapeshellarg($this->xlsx2csvPath()) . ' ' . implode(' ', array_map('escapeshellarg', [
41
            '--ignoreempty',
42
            '--escape',
43
            '--all',
44
            '--dateformat',
45
            '%Y-%m-%d',
46
            $source,
47
            $destination,
48
        ]));
49
50 4
        $execution = ShellExec::run($command);
51 4
        if (0 !== $execution->exitStatus()) {
52
            throw new RuntimeException(
53
                "Execution of xlsx2csv conversion return a non zero status code [{$execution->exitStatus()}]"
54
            );
55
        }
56
57
        // remove spaces on exported file name
58 4
        $csvFiles = glob($destination . '/*.csv') ?: [];
59 4
        foreach ($csvFiles as $csvFile) {
60 4
            $renamed = $destination . '/' . preg_replace('/\s*(.*?)\s*\.csv+/', '$1.csv', basename($csvFile));
61 4
            if (! file_exists($renamed) && $csvFile !== $renamed) {
62 1
                rename($csvFile, $renamed);
63
            }
64
        }
65
    }
66
}
67