|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace PetrKnap\XzUtils; |
| 6 | + |
| 7 | +use Symfony\Component\Process\Exception\ProcessFailedException; |
| 8 | +use Symfony\Component\Process\Process; |
| 9 | +use Throwable; |
| 10 | + |
| 11 | +final class Xz |
| 12 | +{ |
| 13 | + /** |
| 14 | + * @param array<non-empty-string> $options |
| 15 | + * |
| 16 | + * @throws Exception\XzCouldNotCompressData |
| 17 | + */ |
| 18 | + public function compress( |
| 19 | + string $data, |
| 20 | + int|null $compressionPreset = null, |
| 21 | + array $options = [], |
| 22 | + ): string { |
| 23 | + $command = [ |
| 24 | + 'xz', |
| 25 | + '--compress', |
| 26 | + ]; |
| 27 | + if ($compressionPreset !== null) { |
| 28 | + $command[] = '-' . $compressionPreset; |
| 29 | + } |
| 30 | + try { |
| 31 | + return self::run(array_merge($command, $options), $data); |
| 32 | + } catch (Throwable $reason) { |
| 33 | + throw new Exception\XzCouldNotCompressData(__METHOD__, $data, $reason); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * @param array<non-empty-string> $options |
| 39 | + * |
| 40 | + * @throws Exception\XzCouldNotDecompressData |
| 41 | + */ |
| 42 | + public function decompress( |
| 43 | + string $data, |
| 44 | + array $options = [], |
| 45 | + ): string { |
| 46 | + $command = [ |
| 47 | + 'xz', |
| 48 | + '--decompress', |
| 49 | + ]; |
| 50 | + try { |
| 51 | + return self::run(array_merge($command, $options), $data); |
| 52 | + } catch (Throwable $reason) { |
| 53 | + throw new Exception\XzCouldNotDecompressData(__METHOD__, $data, $reason); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * @param non-empty-array<non-empty-string> $command |
| 59 | + * |
| 60 | + * @throws ProcessFailedException |
| 61 | + * |
| 62 | + * @todo move it to another package |
| 63 | + */ |
| 64 | + private static function run(array $command, string $input): string |
| 65 | + { |
| 66 | + $process = new Process($command); |
| 67 | + $process->setInput($input); |
| 68 | + $process->run(); |
| 69 | + if (!$process->isSuccessful()) { |
| 70 | + throw new ProcessFailedException($process); |
| 71 | + } |
| 72 | + return $process->getOutput(); |
| 73 | + } |
| 74 | +} |
0 commit comments