Skip to content

Commit

Permalink
feat: support compression with zstd (#99)
Browse files Browse the repository at this point in the history
  • Loading branch information
tinect authored Dec 4, 2024
1 parent dec77b6 commit 4afee60
Showing 1 changed file with 23 additions and 8 deletions.
31 changes: 23 additions & 8 deletions src/Services/EmlFileManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@

class EmlFileManager
{
private const COMPRESSION_EXT_GZIP = 'gz';
private const COMPRESSION_EXT_ZSTD = 'zst';

public function __construct(
#[Autowire(service: 'frosh_platform_mail_archive.filesystem.private')]
private readonly FilesystemOperator $filesystem,
Expand All @@ -21,15 +24,21 @@ public function __construct(
*/
public function writeFile(string $id, string $content): string
{
$content = \gzcompress($content, 9);
if (\function_exists('zstd_compress')) {
$content = \zstd_compress($content);
$extension = '.' . self::COMPRESSION_EXT_ZSTD;
} else {
$content = \gzcompress($content, 9);
$extension = '.' . self::COMPRESSION_EXT_GZIP;
}

if ($content === false) {
throw new \RuntimeException('Cannot compress eml file');
}

$folderParts = \array_slice(\str_split($id, 2), 0, 3);

$emlFilePath = 'mails/' . \implode('/', $folderParts) . '/' . $id . '.eml.gz';
$emlFilePath = 'mails/' . \implode('/', $folderParts) . '/' . $id . '.eml' . $extension;

$this->filesystem->write($emlFilePath, $content);

Expand All @@ -38,11 +47,19 @@ public function writeFile(string $id, string $content): string

public function getEmlFileAsString(string $emlFilePath): false|string
{
if (!$this->filesystem->fileExists($emlFilePath)) {
try {
$extension = \pathinfo($emlFilePath, PATHINFO_EXTENSION);

$content = $this->filesystem->read($emlFilePath);

if ($extension === self::COMPRESSION_EXT_ZSTD) {
return \zstd_uncompress($content);
}

return \gzuncompress($content);
} catch (\Throwable) {
return false;
}

return \gzuncompress($this->filesystem->read($emlFilePath));
}

public function getEmlAsMessage(string $emlFilePath): false|IMessage
Expand All @@ -62,9 +79,7 @@ public function getEmlAsMessage(string $emlFilePath): false|IMessage
fwrite($emlResource, $content);
rewind($emlResource);

$parser = new MailMimeParser();

return $parser->parse($emlResource, false);
return (new MailMimeParser())->parse($emlResource, false);
}

public function deleteEmlFile(string $emlFilePath): void
Expand Down

0 comments on commit 4afee60

Please sign in to comment.