Skip to content

Commit

Permalink
feat: add sieve utils
Browse files Browse the repository at this point in the history
Signed-off-by: Daniel Kesselberg <[email protected]>
  • Loading branch information
kesselb committed Sep 18, 2024
1 parent aea8fe8 commit d03ec29
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
38 changes: 38 additions & 0 deletions lib/Sieve/SieveUtils.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Mail\Sieve;

class SieveUtils {
/**
* Escape a string for use in a Sieve script
*
* @see https://www.rfc-editor.org/rfc/rfc5228#section-2.4.2
*/
public static function escapeString(string $subject): string {
$subject = preg_replace(
['/\\\\/', '/"/'],
['\\\\\\\\', '\\"'],
$subject
);

return (string)$subject;
}

/**
* Return a string list for use in a Sieve script
*
* @see https://www.rfc-editor.org/rfc/rfc5228#section-2.4.2.1
*/
public static function stringList(array $values): string {
$values = array_map([__CLASS__, 'escapeString'], $values);

return '["' . implode('", "', $values) . '"]';
}
}
51 changes: 51 additions & 0 deletions tests/Unit/Sieve/SieveUtilsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace Unit\Sieve;

use ChristophWurst\Nextcloud\Testing\TestCase;
use OCA\Mail\Sieve\SieveUtils;

class SieveUtilsTest extends TestCase {
/**
* @dataProvider providerEscapeString
*/
public function testEscapeString(string $subject, string $expected): void {
$actual = SieveUtils::escapeString($subject);
$this->assertSame($expected, $actual);
}

public static function providerEscapeString(): array {
return [
['foo"bar', 'foo\"bar'],
['foo\\bar', 'foo\\\\bar'],
['foo"\\bar', 'foo\"\\\\bar'],
['foobar', 'foobar'],
['', ''],
];
}

/**
* @dataProvider providerStringList
*/
public function testStringList(array $values, string $expected): void {
$actual = SieveUtils::stringList($values);
$this->assertSame($expected, $actual);
}

public static function providerStringList(): array {
return [
[['Hello', 'World'], '["Hello", "World"]'],
[['foo"bar', 'foo\\bar'], '["foo\"bar", "foo\\\\bar"]'],
[['foo"bar', 'foo\\bar', 'foo"\\bar'], '["foo\"bar", "foo\\\\bar", "foo\"\\\\bar"]'],
[['foobar'], '["foobar"]'],
[[], '[""]'],
];
}
}

0 comments on commit d03ec29

Please sign in to comment.