From 84bc90d9df5a5b9b8fd13ffb0fb445f1bb666dc9 Mon Sep 17 00:00:00 2001 From: Steve Bauman Date: Fri, 20 Nov 2026 11:43:30 -0500 Subject: [PATCH 1/5] Preserve text values in IMAP searches --- src/Connection/ConnectionInterface.php | 8 ++ src/Connection/ImapCommand.php | 28 ++++- src/Connection/ImapCommandArgument.php | 32 +++++ src/Connection/ImapConnection.php | 10 ++ src/Connection/ImapQueryBuilder.php | 117 ++++++++++++++++-- src/MessageQuery.php | 6 +- src/QueriesMessages.php | 2 +- src/Support/Assert.php | 22 +++- src/Support/Str.php | 13 +- tests/Unit/Connection/ImapConnectionTest.php | 17 +++ .../Unit/Connection/ImapQueryBuilderTest.php | 31 +++++ tests/Unit/MessageQueryTest.php | 54 ++++++++ tests/Unit/Support/StrTest.php | 15 ++- 13 files changed, 332 insertions(+), 23 deletions(-) create mode 100644 src/Connection/ImapCommandArgument.php diff --git a/src/Connection/ConnectionInterface.php b/src/Connection/ConnectionInterface.php index f04ce094..3a7495fc 100644 --- a/src/Connection/ConnectionInterface.php +++ b/src/Connection/ConnectionInterface.php @@ -108,6 +108,10 @@ public function capability(): UntaggedResponse; * * Execute a search request. * + * When compiled criteria are the first argument, declare UTF-8 for non-ASCII literals. + * + * @param array $params + * * @see https://datatracker.ietf.org/doc/html/rfc9051#name-search-command */ public function search(array $params): UntaggedResponse; @@ -117,6 +121,8 @@ public function search(array $params): UntaggedResponse; * * Execute a sort request using RFC 5256. * + * @param array $params + * * @see https://datatracker.ietf.org/doc/html/rfc5256 */ public function sort(ImapSortKey $key, string $direction, array $params): UntaggedResponse; @@ -204,6 +210,8 @@ public function size(int|array $ids): ResponseCollection; /** * Send an IMAP command. + * + * @param array $tokens */ public function send(string $name, array $tokens = [], ?string &$tag = null): void; diff --git a/src/Connection/ImapCommand.php b/src/Connection/ImapCommand.php index 507c534b..b1c848de 100644 --- a/src/Connection/ImapCommand.php +++ b/src/Connection/ImapCommand.php @@ -16,6 +16,8 @@ class ImapCommand implements Stringable /** * Constructor. + * + * @param array $tokens */ public function __construct( protected string $tag, @@ -41,6 +43,8 @@ public function command(): string /** * Get the IMAP tokens. + * + * @return array */ public function tokens(): array { @@ -65,7 +69,7 @@ public function compile(): array $line = trim("{$this->tag} {$this->command}"); - foreach ($this->tokens as $token) { + foreach ($this->parts() as $token) { if (is_array($token)) { // For tokens provided as arrays, the first element is a placeholder // (for example, "{20}") that signals a literal value will follow. @@ -75,7 +79,7 @@ public function compile(): array Assert::hasNoControlCharacters($length); $lines[] = new ImapCommandLine( - value: "{$line} {$length}", + value: $line.$length, synchronizing: ! str_contains($length, '+'), ); @@ -83,7 +87,7 @@ public function compile(): array } else { Assert::hasNoControlCharacters($token); - $line .= " {$token}"; + $line .= $token; } } @@ -92,6 +96,24 @@ public function compile(): array return $this->compiled = $lines; } + /** + * Separate command arguments with spaces while preserving their internal syntax. + * + * @return iterable + */ + protected function parts(): iterable + { + foreach ($this->tokens as $token) { + yield ' '; + + if ($token instanceof ImapCommandArgument) { + yield from $token->parts; + } else { + yield $token; + } + } + } + /** * Get a redacted version of the command for safe exposure. */ diff --git a/src/Connection/ImapCommandArgument.php b/src/Connection/ImapCommandArgument.php new file mode 100644 index 00000000..70a430c6 --- /dev/null +++ b/src/Connection/ImapCommandArgument.php @@ -0,0 +1,32 @@ + $parts Syntax fragments or pairs of literal markers and payloads. + */ + public function __construct( + public readonly array $parts, + ) {} + + /** + * Determine if any literal contains non-ASCII bytes. + */ + public function hasNonAsciiLiteral(): bool + { + foreach ($this->parts as $part) { + if (is_array($part) && preg_match('/[\x80-\xFF]/', $part[1])) { + return true; + } + } + + return false; + } +} diff --git a/src/Connection/ImapConnection.php b/src/Connection/ImapConnection.php index fd3d04f3..2939bee9 100644 --- a/src/Connection/ImapConnection.php +++ b/src/Connection/ImapConnection.php @@ -493,6 +493,12 @@ public function size(int|array $ids): ResponseCollection */ public function search(array $params): UntaggedResponse { + $criteria = reset($params); + + if ($criteria instanceof ImapCommandArgument && $criteria->hasNonAsciiLiteral()) { + array_unshift($params, 'CHARSET UTF-8'); + } + $this->send('UID SEARCH', $params, tag: $tag); $this->assertTaggedResponse($tag); @@ -751,6 +757,10 @@ protected function assertTaggedResponse(string $tag, ?callable $exception = null */ protected function assertContinuationResponse(ImapCommand $command): void { + if (in_array(strtoupper($command->command()), ['LOGIN', 'AUTHENTICATE'], true)) { + $command = $command->redacted(); + } + $this->assertNextResponse( fn (Response $response) => ( $response instanceof ContinuationResponse || ( diff --git a/src/Connection/ImapQueryBuilder.php b/src/Connection/ImapQueryBuilder.php index fd2db7fe..932b5344 100644 --- a/src/Connection/ImapQueryBuilder.php +++ b/src/Connection/ImapQueryBuilder.php @@ -7,6 +7,7 @@ use Carbon\CarbonInterface; use DateTimeInterface; use DirectoryTree\ImapEngine\Enums\ImapSearchKey; +use DirectoryTree\ImapEngine\Support\Assert; use DirectoryTree\ImapEngine\Support\Str; class ImapQueryBuilder @@ -353,13 +354,35 @@ public function isEmpty(): bool } /** - * Transform the instance into an IMAP-compatible query string. + * Compile the criteria as a single query string. */ public function toImap(): string { return $this->compileWheres($this->wheres); } + /** + * Compile search criteria for transmission, preserving literal arguments. + * + * @return list + */ + public function toImapTokens(): array + { + if ($this->usesLegacyCompiler()) { + return [$this->toImap()]; + } + + $parts = $this->compileWhereParts(); + + foreach ($parts as $part) { + if (is_array($part)) { + return [new ImapCommandArgument($parts)]; + } + } + + return [trim(implode('', $parts), ' ')]; + } + /** * Create a new query instance (like Eloquent's newQuery). */ @@ -373,23 +396,40 @@ protected function newQuery(): static */ protected function addBasicCondition(string $boolean, mixed $column, mixed $value, bool $not = false): void { - $value = $this->prepareWhereValue($value); - - $column = Str::enum($column); + $rawValue = $this->usesLegacyCompiler() ? null : $this->normalizeWhereValue($value); $this->wheres[] = [ 'type' => 'basic', 'not' => $not, - 'key' => $column, - 'value' => $value, + 'key' => Str::enum($column), + 'value' => $this->prepareWhereValue($rawValue ?? $value), + 'rawValue' => $rawValue, 'boolean' => $boolean, ]; } /** - * Prepare the where value, escaping it as needed. + * Preserve the string compiler hooks for subclasses unless they opt into literals. + */ + protected function usesLegacyCompiler(): bool + { + return static::class !== self::class; + } + + /** + * Prepare the where value for the string compiler. */ protected function prepareWhereValue(mixed $value): RawQueryValue|string|null + { + $value = $this->normalizeWhereValue($value); + + return is_string($value) ? Str::escape($value) : $value; + } + + /** + * Normalize the where value for compilation. + */ + protected function normalizeWhereValue(mixed $value): RawQueryValue|string|null { if (is_null($value)) { return null; @@ -411,7 +451,7 @@ protected function prepareWhereValue(mixed $value): RawQueryValue|string|null $value = $value->format($this->dateFormat); } - return Str::escape($value); + return $value; } /** @@ -524,4 +564,65 @@ protected function compileBasic(array $where): string return $part; } + + /** + * Compile the search expression into syntax and literal arguments. + * + * @return list + */ + protected function compileWhereParts(): array + { + $parts = []; + + foreach ($this->wheres as $where) { + $expression = $where['type'] === 'nested' + ? $where['query']->compileWhereParts() + : $this->compileBasicParts($where); + + if ($parts === []) { + $parts = $expression; + } elseif ($where['boolean'] === 'OR') { + $parts = ['OR (', ...$parts, ') (', ...$expression, ')']; + } elseif ($expression !== []) { + array_push($parts, ' ', ...$expression); + } + } + + return $parts; + } + + /** + * Compile a basic where condition into syntax and literal arguments. + * + * @param array{key: string, not: bool, rawValue: RawQueryValue|string|null} $where + * @return list + */ + protected function compileBasicParts(array $where): array + { + $key = strtoupper($where['key']); + $part = ($where['not'] ? 'NOT ' : '').$key; + $value = $where['rawValue']; + + if ($value instanceof RawQueryValue) { + return [$part.' '.$value->value]; + } + + if ($value === null) { + return [$part]; + } + + if ($key === 'KEYWORD' || $key === 'UNKEYWORD') { + Assert::isValidKeyword($value); + + return [$part.' '.$value]; + } + + if (in_array(explode(' ', $key, 2)[0], ['BCC', 'BODY', 'CC', 'FROM', 'HEADER', 'SUBJECT', 'TEXT', 'TO'], true)) { + return [$part.' ', Str::literal($value)]; + } + + Assert::hasNoControlCharacters($value); + + return [$part.' "'.Str::toImapUtf7(Str::escape($value)).'"']; + } } diff --git a/src/MessageQuery.php b/src/MessageQuery.php index 5280774c..94a5bbda 100644 --- a/src/MessageQuery.php +++ b/src/MessageQuery.php @@ -463,9 +463,7 @@ protected function search(): Collection $this->query->all(); } - $response = $this->connection()->search([ - $this->query->toImap(), - ]); + $response = $this->connection()->search($this->query->toImapTokens()); return new Collection(array_map( fn (Token $token) => $token->value, @@ -491,7 +489,7 @@ protected function sort(): Collection $response = $this->connection()->sort( $this->sortKey, $this->sortDirection, - [$this->query->toImap()] + $this->query->toImapTokens() ); return new Collection(array_map( diff --git a/src/QueriesMessages.php b/src/QueriesMessages.php index 1c45b72b..7d0b3d30 100644 --- a/src/QueriesMessages.php +++ b/src/QueriesMessages.php @@ -66,7 +66,7 @@ trait QueriesMessages /** * The methods that should be returned from query builder. */ - protected array $passthru = ['toimap', 'isempty']; + protected array $passthru = ['toimap', 'toimaptokens', 'isempty']; /** * The sort key for server-side sorting (RFC 5256). diff --git a/src/Support/Assert.php b/src/Support/Assert.php index 2d166b21..5b297d33 100644 --- a/src/Support/Assert.php +++ b/src/Support/Assert.php @@ -23,11 +23,31 @@ public static function isValidFlag(string $flag): void { $atom = str_starts_with($flag, '\\') ? substr($flag, 1) : $flag; - if ($atom === '' || preg_match('/[^\x21-\x7E]/', $atom) || strpbrk($atom, '(){%*"\\]') !== false) { + if (! static::isAtom($atom)) { throw new InvalidArgumentException('Invalid IMAP flag.'); } } + /** + * Ensure a search keyword contains a valid IMAP atom. + * + * @throws InvalidArgumentException + */ + public static function isValidKeyword(string $keyword): void + { + if (! static::isAtom($keyword)) { + throw new InvalidArgumentException('Invalid IMAP keyword.'); + } + } + + /** + * Determine if the value is a valid IMAP atom. + */ + protected static function isAtom(string $value): bool + { + return $value !== '' && ! preg_match('/[^\x21-\x7E]/', $value) && strpbrk($value, '(){%*"\\]') === false; + } + /** * Ensure a sequence set contains valid message numbers and ranges. */ diff --git a/src/Support/Str.php b/src/Support/Str.php index 7b515979..2f536b35 100644 --- a/src/Support/Str.php +++ b/src/Support/Str.php @@ -4,6 +4,7 @@ use BackedEnum; use Illuminate\Support\Collection; +use InvalidArgumentException; class Str { @@ -38,7 +39,11 @@ public static function flags(array $flags): string } /** - * Make one or more literals. + * Encode one or more strings as quoted strings or IMAP literals. + * + * Each literal contains a byte-count marker and the original string. + * + * @throws InvalidArgumentException */ public static function literal(array|string $string): array|string { @@ -52,7 +57,11 @@ public static function literal(array|string $string): array|string return $result; } - if (str_contains($string, "\n")) { + if (str_contains($string, "\0")) { + throw new InvalidArgumentException('IMAP strings cannot contain NUL bytes.'); + } + + if (preg_match('/[^\x20-\x7E]/', $string)) { return ['{'.strlen($string).'}', $string]; } diff --git a/tests/Unit/Connection/ImapConnectionTest.php b/tests/Unit/Connection/ImapConnectionTest.php index d8f2573d..03d6892a 100644 --- a/tests/Unit/Connection/ImapConnectionTest.php +++ b/tests/Unit/Connection/ImapConnectionTest.php @@ -146,6 +146,23 @@ $connection->login('foo', 'bar'); })->throws(ImapCommandException::class, 'IMAP command "TAG1 LOGIN [redacted] [redacted]" failed. Response: "TAG1 BAD Authentication failed"'); +test('login redacts credentials when the server rejects a literal', function () { + $stream = new FakeStream; + $stream->open(); + $stream->feed([ + '* OK Welcome to IMAP', + 'TAG1 NO Authentication unavailable', + ]); + + $connection = new ImapConnection($stream); + $connection->connect('imap.example.com'); + + expect(fn () => $connection->login('username', 'café-password')) + ->toThrow(ImapCommandException::class, "TAG1 LOGIN [redacted] [redacted]\r\n[redacted]"); + + $stream->assertNotWritten('café-password'); +}); + test('logout success', function () { $stream = new FakeStream; $stream->open(); diff --git a/tests/Unit/Connection/ImapQueryBuilderTest.php b/tests/Unit/Connection/ImapQueryBuilderTest.php index 95a401d2..e97dfcd1 100644 --- a/tests/Unit/Connection/ImapQueryBuilderTest.php +++ b/tests/Unit/Connection/ImapQueryBuilderTest.php @@ -26,6 +26,25 @@ expect($builder->toImap())->toBe('SUBJECT "hello"'); }); +test('preserves protected compiler overrides when sending subclass criteria', function () { + $builder = new class extends ImapQueryBuilder + { + protected function compileWheres(array $wheres): string + { + return 'SEEN '.parent::compileWheres($wheres); + } + + protected function compileBasic(array $where): string + { + return 'NOT '.parent::compileBasic($where); + } + }; + + $builder->subject('He said "Hello"'); + + expect($builder->toImapTokens())->toBe(['SEEN NOT SUBJECT "He said \\"Hello\\""']); +}); + test('compiles a single criteria', function () { $builder = new ImapQueryBuilder; @@ -327,6 +346,18 @@ function (ImapQueryBuilder $q) { expect((new ImapQueryBuilder)->unkeyword('important')->toImap())->toBe('UNKEYWORD "important"'); }); +test('sends search keywords as atoms', function () { + $builder = (new ImapQueryBuilder)->keyword('important')->unkeyword('$Junk'); + + expect($builder->toImapTokens())->toBe(['KEYWORD important UNKEYWORD $Junk']); +}); + +test('rejects malformed search keywords', function (string $keyword) { + $builder = (new ImapQueryBuilder)->keyword($keyword); + + expect(fn () => $builder->toImapTokens())->toThrow(InvalidArgumentException::class); +})->with(['two words', "\\Seen", "first\nsecond"]); + test('compiles a SENTON condition with unquoted date', function () { expect((new ImapQueryBuilder)->sentOn(Carbon::create(2024, 4, 4))->toImap())->toBe('SENTON 04-Apr-2024'); }); diff --git a/tests/Unit/MessageQueryTest.php b/tests/Unit/MessageQueryTest.php index 519f39f7..d1b35f96 100644 --- a/tests/Unit/MessageQueryTest.php +++ b/tests/Unit/MessageQueryTest.php @@ -32,6 +32,7 @@ function query(?Mailbox $mailbox = null): MessageQuery expect($query->toImap())->toBe(''); expect($query->isEmpty())->toBeTrue(); + expect($query->subject('hello')->toImapTokens())->toBe(['SUBJECT "hello"']); }); test('where', function () { @@ -367,6 +368,37 @@ function query(?Mailbox $mailbox = null): MessageQuery $stream->assertWritten('TAG2 UID SEARCH UID 42:4294967295'); }); +test('search preserves literal values inside nested criteria', function (string $subject, string $charset) { + $stream = new FakeStream; + $stream->open(); + $stream->feed([ + '* OK Welcome to IMAP', + 'TAG1 OK Logged in', + '+ Ready for literal data', + '+ Ready for literal data', + '* SEARCH 1', + 'TAG2 OK SEARCH completed', + ]); + + $mailbox = Mailbox::make(); + $mailbox->connect(new ImapConnection($stream)); + + $count = query($mailbox) + ->body("first\nsecond") + ->orWhere('subject', $subject) + ->header('Message-ID', '0') + ->count(); + + expect($count)->toBe(1); + + $stream->assertWritten("TAG2 UID SEARCH {$charset}OR (BODY {12}\r\n"); + $stream->assertWritten("first\nsecond) (SUBJECT {10}\r\n"); + $stream->assertWritten("{$subject}) HEADER MESSAGE-ID \"0\"\r\n"); +})->with([ + 'ASCII' => ["third\rline", ''], + 'UTF-8' => ["café\rline", 'CHARSET UTF-8 '], +]); + test('unmarkFlagged unflags all matching messages', function () { $stream = new FakeStream; $stream->open(); @@ -540,6 +572,28 @@ function query(?Mailbox $mailbox = null): MessageQuery $stream->assertWritten('TAG3 UID SORT (DATE) UTF-8 ALL'); }); +test('sort sends literal search values using its existing charset', function () { + $stream = new FakeStream; + $stream->open(); + $stream->feed([ + '* OK Welcome to IMAP', + 'TAG1 OK Logged in', + '* CAPABILITY IMAP4rev1 SORT', + 'TAG2 OK CAPABILITY completed', + '+ Ready for literal data', + '* SORT', + 'TAG3 OK SORT completed', + ]); + + $mailbox = Mailbox::make(); + $mailbox->connect(new ImapConnection($stream)); + + expect(query($mailbox)->text("café")->sortBy('date')->get())->toBeEmpty(); + + $stream->assertWritten("TAG3 UID SORT (DATE) UTF-8 TEXT {5}\r\n"); + $stream->assertWritten("café\r\n"); +}); + test('sortBy sends correct sort command with descending order', function () { $stream = new FakeStream; $stream->open(); diff --git a/tests/Unit/Support/StrTest.php b/tests/Unit/Support/StrTest.php index 8825f615..2a3bcf40 100644 --- a/tests/Unit/Support/StrTest.php +++ b/tests/Unit/Support/StrTest.php @@ -81,10 +81,17 @@ expect(Str::literal('He said: "Hi"'))->toBe('"He said: \\"Hi\\""'); }); -test('literal returns a literal indicator and the original string if it contains a newline', function () { - $input = "hello\nworld"; - $expected = ['{'.strlen($input).'}', $input]; - expect(Str::literal($input))->toBe($expected); +test('literal preserves strings that cannot be sent as quoted ASCII', function (string $input, int $length) { + expect(Str::literal($input))->toBe(['{'.$length.'}', $input]); +})->with([ + ["hello\nworld", 11], + ["hello\rworld", 11], + ["hello\tworld", 11], + ['café', 5], +]); + +test('literal rejects NUL bytes', function () { + expect(fn () => Str::literal("hello\0world"))->toThrow(InvalidArgumentException::class); }); test('literal handles an array of literals', function () { From d05fc88625dc03b85ea095b772c94b7678bcd7dd Mon Sep 17 00:00:00 2001 From: stevebauman <6421846+stevebauman@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:43:50 +0000 Subject: [PATCH 2/5] Fix code style --- tests/Unit/Connection/ImapQueryBuilderTest.php | 2 +- tests/Unit/MessageQueryTest.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Unit/Connection/ImapQueryBuilderTest.php b/tests/Unit/Connection/ImapQueryBuilderTest.php index e97dfcd1..eadea764 100644 --- a/tests/Unit/Connection/ImapQueryBuilderTest.php +++ b/tests/Unit/Connection/ImapQueryBuilderTest.php @@ -356,7 +356,7 @@ function (ImapQueryBuilder $q) { $builder = (new ImapQueryBuilder)->keyword($keyword); expect(fn () => $builder->toImapTokens())->toThrow(InvalidArgumentException::class); -})->with(['two words', "\\Seen", "first\nsecond"]); +})->with(['two words', '\\Seen', "first\nsecond"]); test('compiles a SENTON condition with unquoted date', function () { expect((new ImapQueryBuilder)->sentOn(Carbon::create(2024, 4, 4))->toImap())->toBe('SENTON 04-Apr-2024'); diff --git a/tests/Unit/MessageQueryTest.php b/tests/Unit/MessageQueryTest.php index d1b35f96..c7c3ae38 100644 --- a/tests/Unit/MessageQueryTest.php +++ b/tests/Unit/MessageQueryTest.php @@ -588,7 +588,7 @@ function query(?Mailbox $mailbox = null): MessageQuery $mailbox = Mailbox::make(); $mailbox->connect(new ImapConnection($stream)); - expect(query($mailbox)->text("café")->sortBy('date')->get())->toBeEmpty(); + expect(query($mailbox)->text('café')->sortBy('date')->get())->toBeEmpty(); $stream->assertWritten("TAG3 UID SORT (DATE) UTF-8 TEXT {5}\r\n"); $stream->assertWritten("café\r\n"); From 9caaf734227abcd0b1a952750d8ca47ab5043743 Mon Sep 17 00:00:00 2001 From: Steve Bauman Date: Fri, 20 Nov 2026 14:16:17 -0500 Subject: [PATCH 3/5] Extract IMAP search compilation into a grammar --- src/Connection/ImapQueryBuilder.php | 196 ++---------------- src/Connection/ImapSearchGrammar.php | 105 ++++++++++ .../Unit/Connection/ImapQueryBuilderTest.php | 19 +- 3 files changed, 126 insertions(+), 194 deletions(-) create mode 100644 src/Connection/ImapSearchGrammar.php diff --git a/src/Connection/ImapQueryBuilder.php b/src/Connection/ImapQueryBuilder.php index 932b5344..b568614d 100644 --- a/src/Connection/ImapQueryBuilder.php +++ b/src/Connection/ImapQueryBuilder.php @@ -7,7 +7,6 @@ use Carbon\CarbonInterface; use DateTimeInterface; use DirectoryTree\ImapEngine\Enums\ImapSearchKey; -use DirectoryTree\ImapEngine\Support\Assert; use DirectoryTree\ImapEngine\Support\Str; class ImapQueryBuilder @@ -358,7 +357,7 @@ public function isEmpty(): bool */ public function toImap(): string { - return $this->compileWheres($this->wheres); + return $this->grammar()->toImap($this->wheres); } /** @@ -368,19 +367,23 @@ public function toImap(): string */ public function toImapTokens(): array { - if ($this->usesLegacyCompiler()) { - return [$this->toImap()]; - } - - $parts = $this->compileWhereParts(); + return $this->grammar()->compile($this->wheres); + } - foreach ($parts as $part) { - if (is_array($part)) { - return [new ImapCommandArgument($parts)]; - } - } + /** + * Get the conditions recorded by the builder. + */ + public function getWheres(): array + { + return $this->wheres; + } - return [trim(implode('', $parts), ' ')]; + /** + * Get the grammar used to compile search conditions. + */ + protected function grammar(): ImapSearchGrammar + { + return new ImapSearchGrammar; } /** @@ -396,36 +399,15 @@ protected function newQuery(): static */ protected function addBasicCondition(string $boolean, mixed $column, mixed $value, bool $not = false): void { - $rawValue = $this->usesLegacyCompiler() ? null : $this->normalizeWhereValue($value); - $this->wheres[] = [ 'type' => 'basic', 'not' => $not, 'key' => Str::enum($column), - 'value' => $this->prepareWhereValue($rawValue ?? $value), - 'rawValue' => $rawValue, + 'value' => $this->normalizeWhereValue($value), 'boolean' => $boolean, ]; } - /** - * Preserve the string compiler hooks for subclasses unless they opt into literals. - */ - protected function usesLegacyCompiler(): bool - { - return static::class !== self::class; - } - - /** - * Prepare the where value for the string compiler. - */ - protected function prepareWhereValue(mixed $value): RawQueryValue|string|null - { - $value = $this->normalizeWhereValue($value); - - return is_string($value) ? Str::escape($value) : $value; - } - /** * Normalize the where value for compilation. */ @@ -481,148 +463,4 @@ protected function parseDate(mixed $date): CarbonInterface return Carbon::parse($date); } - - /** - * Build a single expression node from a basic or nested where. - * - * @param array{type: 'basic'|'nested', boolean: 'AND'|'OR', query: ImapQueryBuilder} $where - */ - protected function makeExpressionNode(array $where): array - { - return match ($where['type']) { - 'basic' => [ - 'expr' => $this->compileBasic($where), - 'boolean' => $where['boolean'], - ], - - 'nested' => [ - 'expr' => $where['query']->toImap(), - 'boolean' => $where['boolean'], - ] - }; - } - - /** - * Merge the existing expression with the next expression, respecting the boolean operator. - * - * @param 'AND'|'OR' $boolean - */ - protected function mergeExpressions(string $existing, string $next, string $boolean): string - { - return match ($boolean) { - // AND is implicit – just append. - 'AND' => $existing.' '.$next, - - // IMAP's OR is binary; nest accordingly. - 'OR' => 'OR ('.$existing.') ('.$next.')', - }; - } - - /** - * Recursively compile the wheres array into an IMAP-compatible string. - */ - protected function compileWheres(array $wheres): string - { - if (empty($wheres)) { - return ''; - } - - // Convert each "where" into a node for later merging. - $exprNodes = array_map(fn (array $where) => ( - $this->makeExpressionNode($where) - ), $wheres); - - // Start with the first expression. - $combined = array_shift($exprNodes)['expr']; - - // Merge the rest of the expressions. - foreach ($exprNodes as $node) { - $combined = $this->mergeExpressions( - $combined, $node['expr'], $node['boolean'] - ); - } - - return trim($combined); - } - - /** - * Compile a basic where condition into an IMAP-compatible string. - */ - protected function compileBasic(array $where): string - { - $part = strtoupper($where['key']); - - if ($where['value'] instanceof RawQueryValue) { - $part .= ' '.$where['value']->value; - } elseif ($where['value']) { - $part .= ' "'.Str::toImapUtf7($where['value']).'"'; - } - - if ($where['not']) { - $part = 'NOT '.$part; - } - - return $part; - } - - /** - * Compile the search expression into syntax and literal arguments. - * - * @return list - */ - protected function compileWhereParts(): array - { - $parts = []; - - foreach ($this->wheres as $where) { - $expression = $where['type'] === 'nested' - ? $where['query']->compileWhereParts() - : $this->compileBasicParts($where); - - if ($parts === []) { - $parts = $expression; - } elseif ($where['boolean'] === 'OR') { - $parts = ['OR (', ...$parts, ') (', ...$expression, ')']; - } elseif ($expression !== []) { - array_push($parts, ' ', ...$expression); - } - } - - return $parts; - } - - /** - * Compile a basic where condition into syntax and literal arguments. - * - * @param array{key: string, not: bool, rawValue: RawQueryValue|string|null} $where - * @return list - */ - protected function compileBasicParts(array $where): array - { - $key = strtoupper($where['key']); - $part = ($where['not'] ? 'NOT ' : '').$key; - $value = $where['rawValue']; - - if ($value instanceof RawQueryValue) { - return [$part.' '.$value->value]; - } - - if ($value === null) { - return [$part]; - } - - if ($key === 'KEYWORD' || $key === 'UNKEYWORD') { - Assert::isValidKeyword($value); - - return [$part.' '.$value]; - } - - if (in_array(explode(' ', $key, 2)[0], ['BCC', 'BODY', 'CC', 'FROM', 'HEADER', 'SUBJECT', 'TEXT', 'TO'], true)) { - return [$part.' ', Str::literal($value)]; - } - - Assert::hasNoControlCharacters($value); - - return [$part.' "'.Str::toImapUtf7(Str::escape($value)).'"']; - } } diff --git a/src/Connection/ImapSearchGrammar.php b/src/Connection/ImapSearchGrammar.php new file mode 100644 index 00000000..a49406d7 --- /dev/null +++ b/src/Connection/ImapSearchGrammar.php @@ -0,0 +1,105 @@ +compileWhereParts($wheres, false))); + } + + /** + * Compile criteria for transmission to the server. + * + * @return list + */ + public function compile(array $wheres): array + { + $parts = $this->compileWhereParts($wheres, true); + + foreach ($parts as $part) { + if (is_array($part)) { + return [new ImapCommandArgument($parts)]; + } + } + + return [trim(implode('', $parts), ' ')]; + } + + /** + * Compile the search expression into syntax and literal arguments. + * + * @return list + */ + protected function compileWhereParts(array $wheres, bool $forTransmission): array + { + $parts = []; + + foreach ($wheres as $where) { + $expression = $where['type'] === 'nested' + ? $this->compileWhereParts($where['query']->getWheres(), $forTransmission) + : $this->compileBasicParts($where, $forTransmission); + + if ($parts === []) { + $parts = $expression; + } elseif ($where['boolean'] === 'OR') { + $parts = ['OR (', ...$parts, ') (', ...$expression, ')']; + } elseif ($expression !== []) { + array_push($parts, ' ', ...$expression); + } + } + + return $parts; + } + + /** + * Compile a basic where condition into syntax and literal arguments. + * + * @param array{key: string, not: bool, value: RawQueryValue|string|null} $where + * @return list + */ + protected function compileBasicParts(array $where, bool $forTransmission): array + { + $key = strtoupper($where['key']); + $part = ($where['not'] ? 'NOT ' : '').$key; + $value = $where['value']; + + if ($value instanceof RawQueryValue) { + return [$part.' '.$value->value]; + } + + if ($value === null) { + return [$part]; + } + + if (! $forTransmission) { + $value = Str::escape($value); + + return [$value ? $part.' "'.Str::toImapUtf7($value).'"' : $part]; + } + + if ($key === 'KEYWORD' || $key === 'UNKEYWORD') { + Assert::isValidKeyword($value); + + return [$part.' '.$value]; + } + + if (in_array(explode(' ', $key, 2)[0], ['BCC', 'BODY', 'CC', 'FROM', 'HEADER', 'SUBJECT', 'TEXT', 'TO'], true)) { + return [$part.' ', Str::literal($value)]; + } + + Assert::hasNoControlCharacters($value); + + return [$part.' "'.Str::toImapUtf7(Str::escape($value)).'"']; + } +} diff --git a/tests/Unit/Connection/ImapQueryBuilderTest.php b/tests/Unit/Connection/ImapQueryBuilderTest.php index eadea764..b6ac0776 100644 --- a/tests/Unit/Connection/ImapQueryBuilderTest.php +++ b/tests/Unit/Connection/ImapQueryBuilderTest.php @@ -26,23 +26,12 @@ expect($builder->toImap())->toBe('SUBJECT "hello"'); }); -test('preserves protected compiler overrides when sending subclass criteria', function () { - $builder = new class extends ImapQueryBuilder - { - protected function compileWheres(array $wheres): string - { - return 'SEEN '.parent::compileWheres($wheres); - } - - protected function compileBasic(array $where): string - { - return 'NOT '.parent::compileBasic($where); - } - }; +test('subclasses inherit literal compilation', function () { + $builder = new class extends ImapQueryBuilder {}; - $builder->subject('He said "Hello"'); + $argument = $builder->subject("first\nsecond")->toImapTokens()[0]; - expect($builder->toImapTokens())->toBe(['SEEN NOT SUBJECT "He said \\"Hello\\""']); + expect($argument->parts)->toBe(['SUBJECT ', ['{12}', "first\nsecond"]]); }); test('compiles a single criteria', function () { From 0824a8b0b356ac9439aa5a74731e2f7ce6617650 Mon Sep 17 00:00:00 2001 From: Steve Bauman Date: Fri, 20 Nov 2026 14:29:37 -0500 Subject: [PATCH 4/5] Render IMAP queries from the transmitted search tokens --- src/Connection/ConnectionInterface.php | 2 +- src/Connection/ImapConnection.php | 28 +++++++++-- src/Connection/ImapQueryBuilder.php | 21 +++++++- src/Connection/ImapSearchGrammar.php | 50 ++++++++++++------- src/QueriesMessages.php | 2 +- tests/Unit/Connection/ImapConnectionTest.php | 22 ++++++++ .../Unit/Connection/ImapQueryBuilderTest.php | 14 +++--- tests/Unit/MessageQueryTest.php | 42 ++++++++++++++-- 8 files changed, 145 insertions(+), 36 deletions(-) diff --git a/src/Connection/ConnectionInterface.php b/src/Connection/ConnectionInterface.php index 3a7495fc..31303370 100644 --- a/src/Connection/ConnectionInterface.php +++ b/src/Connection/ConnectionInterface.php @@ -108,7 +108,7 @@ public function capability(): UntaggedResponse; * * Execute a search request. * - * When compiled criteria are the first argument, declare UTF-8 for non-ASCII literals. + * Declare UTF-8 for non-ASCII literals when the caller omits the charset. * * @param array $params * diff --git a/src/Connection/ImapConnection.php b/src/Connection/ImapConnection.php index 2939bee9..2f980f84 100644 --- a/src/Connection/ImapConnection.php +++ b/src/Connection/ImapConnection.php @@ -493,9 +493,7 @@ public function size(int|array $ids): ResponseCollection */ public function search(array $params): UntaggedResponse { - $criteria = reset($params); - - if ($criteria instanceof ImapCommandArgument && $criteria->hasNonAsciiLiteral()) { + if ($this->requiresSearchCharset($params)) { array_unshift($params, 'CHARSET UTF-8'); } @@ -508,6 +506,30 @@ public function search(array $params): UntaggedResponse ); } + /** + * Determine whether search literals need a charset declaration. + */ + protected function requiresSearchCharset(array $params): bool + { + $first = reset($params); + + if (is_string($first) && preg_match('/^\s*CHARSET(?:\s|$)/i', $first)) { + return false; + } + + foreach ($params as $param) { + if ($param instanceof ImapCommandArgument && $param->hasNonAsciiLiteral()) { + return true; + } + + if (is_array($param) && preg_match('/[\x80-\xFF]/', $param[1])) { + return true; + } + } + + return false; + } + /** * {@inheritDoc} */ diff --git a/src/Connection/ImapQueryBuilder.php b/src/Connection/ImapQueryBuilder.php index b568614d..0e2628c3 100644 --- a/src/Connection/ImapQueryBuilder.php +++ b/src/Connection/ImapQueryBuilder.php @@ -8,6 +8,7 @@ use DateTimeInterface; use DirectoryTree\ImapEngine\Enums\ImapSearchKey; use DirectoryTree\ImapEngine\Support\Str; +use ReflectionMethod; class ImapQueryBuilder { @@ -357,7 +358,12 @@ public function isEmpty(): bool */ public function toImap(): string { - return $this->grammar()->toImap($this->wheres); + // A subclass calling parent::toImap() must not re-enter its own override. + $tokens = $this->overridesToImap() + ? $this->grammar()->compile($this->wheres) + : $this->toImapTokens(); + + return ltrim((string) new ImapCommand('', '', $tokens), ' '); } /** @@ -367,9 +373,22 @@ public function toImap(): string */ public function toImapTokens(): array { + // Older builders may customize the outgoing criteria through toImap(). + if ($this->overridesToImap()) { + return [$this->toImap()]; + } + return $this->grammar()->compile($this->wheres); } + /** + * Determine whether the builder supplies its own IMAP query string. + */ + protected function overridesToImap(): bool + { + return static::class !== self::class && (new ReflectionMethod($this, 'toImap'))->getDeclaringClass()->getName() !== self::class; + } + /** * Get the conditions recorded by the builder. */ diff --git a/src/Connection/ImapSearchGrammar.php b/src/Connection/ImapSearchGrammar.php index a49406d7..997f66c2 100644 --- a/src/Connection/ImapSearchGrammar.php +++ b/src/Connection/ImapSearchGrammar.php @@ -10,14 +10,6 @@ */ class ImapSearchGrammar { - /** - * Render the criteria using the public single-line query format. - */ - public function toImap(array $wheres): string - { - return trim(implode('', $this->compileWhereParts($wheres, false))); - } - /** * Compile criteria for transmission to the server. * @@ -25,7 +17,7 @@ public function toImap(array $wheres): string */ public function compile(array $wheres): array { - $parts = $this->compileWhereParts($wheres, true); + $parts = $this->compileWhereParts($wheres); foreach ($parts as $part) { if (is_array($part)) { @@ -41,14 +33,14 @@ public function compile(array $wheres): array * * @return list */ - protected function compileWhereParts(array $wheres, bool $forTransmission): array + protected function compileWhereParts(array $wheres): array { $parts = []; foreach ($wheres as $where) { $expression = $where['type'] === 'nested' - ? $this->compileWhereParts($where['query']->getWheres(), $forTransmission) - : $this->compileBasicParts($where, $forTransmission); + ? $this->compileNestedParts($where['query']) + : $this->compileBasicParts($where); if ($parts === []) { $parts = $expression; @@ -62,13 +54,39 @@ protected function compileWhereParts(array $wheres, bool $forTransmission): arra return $parts; } + /** + * Compile nested criteria through the nested builder's public compiler. + */ + protected function compileNestedParts(ImapQueryBuilder $query): array + { + $parts = []; + + foreach ($query->toImapTokens() as $token) { + if ($token === '') { + continue; + } + + if ($parts !== []) { + $parts[] = ' '; + } + + if ($token instanceof ImapCommandArgument) { + array_push($parts, ...$token->parts); + } else { + $parts[] = $token; + } + } + + return $parts; + } + /** * Compile a basic where condition into syntax and literal arguments. * * @param array{key: string, not: bool, value: RawQueryValue|string|null} $where * @return list */ - protected function compileBasicParts(array $where, bool $forTransmission): array + protected function compileBasicParts(array $where): array { $key = strtoupper($where['key']); $part = ($where['not'] ? 'NOT ' : '').$key; @@ -82,12 +100,6 @@ protected function compileBasicParts(array $where, bool $forTransmission): array return [$part]; } - if (! $forTransmission) { - $value = Str::escape($value); - - return [$value ? $part.' "'.Str::toImapUtf7($value).'"' : $part]; - } - if ($key === 'KEYWORD' || $key === 'UNKEYWORD') { Assert::isValidKeyword($value); diff --git a/src/QueriesMessages.php b/src/QueriesMessages.php index 7d0b3d30..0069a000 100644 --- a/src/QueriesMessages.php +++ b/src/QueriesMessages.php @@ -66,7 +66,7 @@ trait QueriesMessages /** * The methods that should be returned from query builder. */ - protected array $passthru = ['toimap', 'toimaptokens', 'isempty']; + protected array $passthru = ['toimap', 'toimaptokens', 'getwheres', 'isempty']; /** * The sort key for server-side sorting (RFC 5256). diff --git a/tests/Unit/Connection/ImapConnectionTest.php b/tests/Unit/Connection/ImapConnectionTest.php index 03d6892a..ad856726 100644 --- a/tests/Unit/Connection/ImapConnectionTest.php +++ b/tests/Unit/Connection/ImapConnectionTest.php @@ -749,6 +749,28 @@ public function setSocketSetCrypto(bool $enabled, ?int $method): bool|int expect((string) $responses->first())->toBe('* 1 FETCH (UID 1 RFC822.SIZE 1024)'); }); +test('search detects literal charsets and honors explicit declarations', function (array $params, string $expected) { + $stream = new FakeStream; + $stream->open(); + $stream->feed([ + '* OK Welcome to IMAP', + '+ Ready for literal data', + '* SEARCH', + 'TAG1 OK SEARCH completed', + ]); + + $connection = new ImapConnection($stream); + $connection->connect('imap.example.com'); + $connection->search($params); + + $stream->assertWritten("TAG1 UID SEARCH {$expected}\r\n"); +})->with([ + [['SUBJECT', Str::literal('café')], 'CHARSET UTF-8 SUBJECT {5}'], + [['SEEN', ...(new ImapQueryBuilder)->subject('café')->toImapTokens()], 'CHARSET UTF-8 SEEN SUBJECT {5}'], + [['charset', 'ISO-8859-1', 'SUBJECT', Str::literal("caf\xe9")], 'charset ISO-8859-1 SUBJECT {4}'], + [['CHARSET UTF-8', 'SUBJECT', Str::literal('café')], 'CHARSET UTF-8 SUBJECT {5}'], +]); + test('search', function () { $stream = new FakeStream; $stream->open(); diff --git a/tests/Unit/Connection/ImapQueryBuilderTest.php b/tests/Unit/Connection/ImapQueryBuilderTest.php index b6ac0776..fdc8b79b 100644 --- a/tests/Unit/Connection/ImapQueryBuilderTest.php +++ b/tests/Unit/Connection/ImapQueryBuilderTest.php @@ -115,7 +115,7 @@ function (ImapQueryBuilder $q) { $builder->where('subject', ''); // empty string - expect($builder->toImap())->toBe('SUBJECT'); + expect($builder->toImap())->toBe('SUBJECT ""'); }); test('compiles a null value', function () { @@ -193,15 +193,15 @@ function (ImapQueryBuilder $q) { expect($builder->toImap())->toBe('SUBJECT "He said \\"Hello\\""'); }); -test('removes newlines and carriage returns in search value', function () { +test('renders newline and carriage return bytes in a literal', function () { $builder = new ImapQueryBuilder; $builder->where('body', "Line one\nLine two\rLine three"); - expect($builder->toImap())->toBe('BODY "Line oneLine twoLine three"'); + expect($builder->toImap())->toBe("BODY {28}\r\nLine one\nLine two\rLine three"); }); -test('escapes multiple special characters', function () { +test('preserves quotes and backslashes inside a rendered literal', function () { $builder = new ImapQueryBuilder; // Special characters: double quotes, newlines, backslash @@ -209,7 +209,7 @@ function (ImapQueryBuilder $q) { $builder->where('subject', $value); - expect($builder->toImap())->toBe('SUBJECT "Foo \\"Bar\\"Baz\\\\Zot"'); + expect($builder->toImap())->toBe("SUBJECT {17}\r\n".$value); }); test('compiles a SINCE condition with unquoted date', function () { @@ -328,11 +328,11 @@ function (ImapQueryBuilder $q) { }); test('compiles KEYWORD condition', function () { - expect((new ImapQueryBuilder)->keyword('important')->toImap())->toBe('KEYWORD "important"'); + expect((new ImapQueryBuilder)->keyword('important')->toImap())->toBe('KEYWORD important'); }); test('compiles UNKEYWORD condition', function () { - expect((new ImapQueryBuilder)->unkeyword('important')->toImap())->toBe('UNKEYWORD "important"'); + expect((new ImapQueryBuilder)->unkeyword('important')->toImap())->toBe('UNKEYWORD important'); }); test('sends search keywords as atoms', function () { diff --git a/tests/Unit/MessageQueryTest.php b/tests/Unit/MessageQueryTest.php index c7c3ae38..e7e258a2 100644 --- a/tests/Unit/MessageQueryTest.php +++ b/tests/Unit/MessageQueryTest.php @@ -33,6 +33,40 @@ function query(?Mailbox $mailbox = null): MessageQuery expect($query->toImap())->toBe(''); expect($query->isEmpty())->toBeTrue(); expect($query->subject('hello')->toImapTokens())->toBe(['SUBJECT "hello"']); + expect($query->getWheres()[0]['value'])->toBe('hello'); +}); + +test('search and sort execute public query string overrides', function () { + $stream = new FakeStream; + $stream->open(); + $stream->feed([ + '* OK Welcome to IMAP', + 'TAG1 OK Logged in', + '* SEARCH', + 'TAG2 OK SEARCH completed', + '* CAPABILITY IMAP4rev1 SORT', + 'TAG3 OK CAPABILITY completed', + '* SORT', + 'TAG4 OK SORT completed', + ]); + + $mailbox = Mailbox::make(); + $mailbox->connect(new ImapConnection($stream)); + + $builder = new class extends ImapQueryBuilder + { + public function toImap(): string + { + return parent::toImap().' UNSEEN'; + } + }; + + $query = new MessageQuery(new Folder($mailbox, 'test'), $builder); + $query->where(fn ($nested) => $nested->seen())->count(); + $query->sortBy('date')->get(); + + $stream->assertWritten("TAG2 UID SEARCH SEEN UNSEEN UNSEEN\r\n"); + $stream->assertWritten("TAG4 UID SORT (DATE) UTF-8 SEEN UNSEEN UNSEEN\r\n"); }); test('where', function () { @@ -383,13 +417,13 @@ function query(?Mailbox $mailbox = null): MessageQuery $mailbox = Mailbox::make(); $mailbox->connect(new ImapConnection($stream)); - $count = query($mailbox) + $query = query($mailbox) ->body("first\nsecond") ->orWhere('subject', $subject) - ->header('Message-ID', '0') - ->count(); + ->header('Message-ID', '0'); - expect($count)->toBe(1); + expect($query->toImap())->toBe("OR (BODY {12}\r\nfirst\nsecond) (SUBJECT {10}\r\n{$subject}) HEADER MESSAGE-ID \"0\""); + expect($query->count())->toBe(1); $stream->assertWritten("TAG2 UID SEARCH {$charset}OR (BODY {12}\r\n"); $stream->assertWritten("first\nsecond) (SUBJECT {10}\r\n"); From 8661f7c66a8c42e97b7b27e842a1b32b926ca480 Mon Sep 17 00:00:00 2001 From: Steve Bauman Date: Fri, 20 Nov 2026 14:40:13 -0500 Subject: [PATCH 5/5] Use query tokens as the search compiler extension point --- src/Connection/ImapQueryBuilder.php | 21 +----------- tests/Unit/MessageQueryTest.php | 51 +++++++++++++++++++++++++++-- 2 files changed, 49 insertions(+), 23 deletions(-) diff --git a/src/Connection/ImapQueryBuilder.php b/src/Connection/ImapQueryBuilder.php index 0e2628c3..3c1c3d9e 100644 --- a/src/Connection/ImapQueryBuilder.php +++ b/src/Connection/ImapQueryBuilder.php @@ -8,7 +8,6 @@ use DateTimeInterface; use DirectoryTree\ImapEngine\Enums\ImapSearchKey; use DirectoryTree\ImapEngine\Support\Str; -use ReflectionMethod; class ImapQueryBuilder { @@ -358,12 +357,7 @@ public function isEmpty(): bool */ public function toImap(): string { - // A subclass calling parent::toImap() must not re-enter its own override. - $tokens = $this->overridesToImap() - ? $this->grammar()->compile($this->wheres) - : $this->toImapTokens(); - - return ltrim((string) new ImapCommand('', '', $tokens), ' '); + return ltrim((string) new ImapCommand('', '', $this->toImapTokens()), ' '); } /** @@ -373,22 +367,9 @@ public function toImap(): string */ public function toImapTokens(): array { - // Older builders may customize the outgoing criteria through toImap(). - if ($this->overridesToImap()) { - return [$this->toImap()]; - } - return $this->grammar()->compile($this->wheres); } - /** - * Determine whether the builder supplies its own IMAP query string. - */ - protected function overridesToImap(): bool - { - return static::class !== self::class && (new ReflectionMethod($this, 'toImap'))->getDeclaringClass()->getName() !== self::class; - } - /** * Get the conditions recorded by the builder. */ diff --git a/tests/Unit/MessageQueryTest.php b/tests/Unit/MessageQueryTest.php index e7e258a2..b16dec6d 100644 --- a/tests/Unit/MessageQueryTest.php +++ b/tests/Unit/MessageQueryTest.php @@ -36,7 +36,7 @@ function query(?Mailbox $mailbox = null): MessageQuery expect($query->getWheres()[0]['value'])->toBe('hello'); }); -test('search and sort execute public query string overrides', function () { +test('search and sort execute query token overrides', function () { $stream = new FakeStream; $stream->open(); $stream->feed([ @@ -55,9 +55,9 @@ function query(?Mailbox $mailbox = null): MessageQuery $builder = new class extends ImapQueryBuilder { - public function toImap(): string + public function toImapTokens(): array { - return parent::toImap().' UNSEEN'; + return [...parent::toImapTokens(), 'UNSEEN']; } }; @@ -69,6 +69,51 @@ public function toImap(): string $stream->assertWritten("TAG4 UID SORT (DATE) UTF-8 SEEN UNSEEN UNSEEN\r\n"); }); +test('search and sort preserve literals in query token overrides', function () { + $stream = new FakeStream; + $stream->open(); + $stream->feed([ + '* OK Welcome to IMAP', + 'TAG1 OK Logged in', + '+ Ready for subject', + '+ Ready for body', + '* SEARCH', + 'TAG2 OK SEARCH completed', + '* CAPABILITY IMAP4rev1 SORT', + 'TAG3 OK CAPABILITY completed', + '+ Ready for subject', + '+ Ready for body', + '* SORT', + 'TAG4 OK SORT completed', + ]); + + $mailbox = Mailbox::make(); + $mailbox->connect(new ImapConnection($stream)); + + $builder = new class extends ImapQueryBuilder + { + public function toImapTokens(): array + { + return [...parent::toImapTokens(), 'UNSEEN']; + } + }; + + $query = new MessageQuery(new Folder($mailbox, 'test'), $builder); + $query->subject('café')->orWhere('body', "line {3}\r\nend"); + + expect($query->toImap())->toBe("OR (SUBJECT {5}\r\ncafé) (BODY {13}\r\nline {3}\r\nend) UNSEEN"); + $query->count(); + $query->sortBy('date')->get(); + + $stream->assertWritten("TAG2 UID SEARCH CHARSET UTF-8 OR (SUBJECT {5}\r\n"); + $stream->assertWritten("café) (BODY {13}\r\n"); + $stream->assertWritten("line {3}\r\nend) UNSEEN\r\n"); + + $stream->assertWritten("TAG4 UID SORT (DATE) UTF-8 OR (SUBJECT {5}\r\n"); + $stream->assertWritten("café) (BODY {13}\r\n"); + $stream->assertWritten("line {3}\r\nend) UNSEEN\r\n"); +}); + test('where', function () { $query = query() ->where('subject', 'hello')