| {"repo_name": "ImapEngine", "file_name": "/ImapEngine/src/Support/ForwardsCalls.php", "inference_info": {"prefix_code": "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Support;\n\nuse BadMethodCallException;\nuse Error;\n\ntrait ForwardsCalls\n{\n /**\n * Forward a method call to the given object.\n */\n ", "suffix_code": "\n\n /**\n * Throw a bad method call exception for the given method.\n */\n protected static function throwBadMethodCallException(string $method)\n {\n throw new BadMethodCallException(sprintf(\n 'Call to undefined method %s::%s()', static::class, $method\n ));\n }\n}\n", "middle_code": "protected function forwardCallTo(object $object, string $method, array $parameters): mixed\n {\n try {\n return $object->{$method}(...$parameters);\n } catch (Error|BadMethodCallException $e) {\n $pattern = '~^Call to undefined method (?P<class>[^:]+)::(?P<method>[^\\(]+)\\(\\)$~';\n if (! preg_match($pattern, $e->getMessage(), $matches)) {\n throw $e;\n }\n if ($matches['class'] != get_class($object) ||\n $matches['method'] != $method) {\n throw $e;\n }\n static::throwBadMethodCallException($method);\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "php", "sub_task_type": null}, "context_code": [["/ImapEngine/src/FileMessage.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\nuse BadMethodCallException;\n\nclass FileMessage implements MessageInterface\n{\n use HasFlags, HasParsedMessage;\n\n /**\n * Constructor.\n */\n public function __construct(\n protected string $contents\n ) {}\n\n /**\n * {@inheritDoc}\n */\n public function uid(): int\n {\n throw new BadMethodCallException('FileMessage does not support a UID');\n }\n\n /**\n * {@inheritDoc}\n */\n public function flag(mixed $flag, string $operation, bool $expunge = false): void\n {\n throw new BadMethodCallException('FileMessage does not support flagging');\n }\n\n /**\n * Get the string representation of the message.\n */\n public function __toString(): string\n {\n return $this->contents;\n }\n\n /**\n * Determine if this message is equal to another.\n */\n public function is(MessageInterface $message): bool\n {\n return $message instanceof self\n && $this->contents === $message->contents;\n }\n\n /**\n * Get the message flags.\n */\n public function flags(): array\n {\n return [];\n }\n\n /**\n * Determine if the message is empty.\n */\n protected function isEmpty(): bool\n {\n return empty($this->contents);\n }\n}\n"], ["/ImapEngine/src/Support/Str.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Support;\n\nuse BackedEnum;\n\nclass Str\n{\n /**\n * Make a list with literals or nested lists.\n */\n public static function list(array $list): string\n {\n $values = [];\n\n foreach ($list as $value) {\n if (is_array($value)) {\n $values[] = static::list($value);\n } else {\n $values[] = $value;\n }\n }\n\n return sprintf('(%s)', implode(' ', $values));\n }\n\n /**\n * Make one or more literals.\n */\n public static function literal(array|string $string): array|string\n {\n if (is_array($string)) {\n $result = [];\n\n foreach ($string as $value) {\n $result[] = static::literal($value);\n }\n\n return $result;\n }\n\n if (str_contains($string, \"\\n\")) {\n return ['{'.strlen($string).'}', $string];\n }\n\n return '\"'.static::escape($string).'\"';\n }\n\n /**\n * Resolve the value of the given enums.\n */\n public static function enums(BackedEnum|array|string|null $enums = null): array|string|null\n {\n if (is_null($enums)) {\n return null;\n }\n\n if (is_array($enums)) {\n return array_map([static::class, 'enums'], $enums);\n }\n\n return Str::enum($enums);\n }\n\n /**\n * Resolve the value of the given enum.\n */\n public static function enum(BackedEnum|string $enum): string\n {\n if ($enum instanceof BackedEnum) {\n return $enum->value;\n }\n\n return (string) $enum;\n }\n\n /**\n * Make a range set for use in a search command.\n */\n public static function set(array|int $from, int|float|null $to = null): string\n {\n // If $from is an array with multiple elements, return them as a comma-separated list.\n if (is_array($from) && count($from) > 1) {\n return implode(',', $from);\n }\n\n // If $from is an array with a single element, return that element.\n if (is_array($from) && count($from) === 1) {\n return (string) reset($from);\n }\n\n // At this point, $from is an integer. No upper bound provided, return $from as a string.\n if (is_null($to)) {\n return (string) $from;\n }\n\n // If the upper bound is infinite, use the '*' notation.\n if ($to == INF) {\n return $from.':*';\n }\n\n // Otherwise, return a typical range string.\n return $from.':'.$to;\n }\n\n /**\n * Make a credentials string for use in the AUTHENTICATE command.\n */\n public static function credentials(string $user, string $token): string\n {\n return base64_encode(\"user=$user\\1auth=Bearer $token\\1\\1\");\n }\n\n /**\n * Prefix a string with the given prefix if it does not already start with it.\n */\n public static function prefix(string $value, string $prefix): string\n {\n return str_starts_with($value, $prefix) ? $value : $prefix.$value;\n }\n\n /**\n * Escape a string for use in a list.\n */\n public static function escape(string $string): string\n {\n // Remove newlines and control characters (ASCII 0-31 and 127).\n $string = preg_replace('/[\\r\\n\\x00-\\x1F\\x7F]/', '', $string);\n\n // Escape backslashes first to avoid double-escaping and then escape double quotes.\n return str_replace(['\\\\', '\"'], ['\\\\\\\\', '\\\\\"'], $string);\n }\n\n /**\n * Decode a modified UTF-7 string (IMAP specific) to UTF-8.\n */\n public static function fromImapUtf7(string $string): string\n {\n // If the string doesn't contain any '&' character, it's not UTF-7 encoded.\n if (! str_contains($string, '&')) {\n return $string;\n }\n\n // Handle the special case of '&-' which represents '&' in UTF-7.\n if ($string === '&-') {\n return '&';\n }\n\n // Direct implementation of IMAP's modified UTF-7 decoding.\n return preg_replace_callback('/&([^-]*)-?/', function ($matches) {\n // If it's just an ampersand.\n if ($matches[1] === '') {\n return '&';\n }\n\n // If it's the special case for ampersand.\n if ($matches[1] === '-') {\n return '&';\n }\n\n // Convert modified base64 to standard base64.\n $base64 = strtr($matches[1], ',', '/');\n\n // Add padding if necessary.\n switch (strlen($base64) % 4) {\n case 1: $base64 .= '===';\n break;\n case 2: $base64 .= '==';\n break;\n case 3: $base64 .= '=';\n break;\n }\n\n // Decode base64 to binary.\n $binary = base64_decode($base64, true);\n\n if ($binary === false) {\n // If decoding fails, return the original string.\n return '&'.$matches[1].($matches[2] ?? '');\n }\n\n $result = '';\n\n // Convert binary UTF-16BE to UTF-8.\n for ($i = 0; $i < strlen($binary); $i += 2) {\n if (isset($binary[$i + 1])) {\n $char = (ord($binary[$i]) << 8) | ord($binary[$i + 1]);\n\n if ($char < 0x80) {\n $result .= chr($char);\n } elseif ($char < 0x800) {\n $result .= chr(0xC0 | ($char >> 6)).chr(0x80 | ($char & 0x3F));\n } else {\n $result .= chr(0xE0 | ($char >> 12)).chr(0x80 | (($char >> 6) & 0x3F)).chr(0x80 | ($char & 0x3F));\n }\n }\n }\n\n return $result;\n }, $string);\n }\n\n /**\n * Encode a UTF-8 string to modified UTF-7 (IMAP specific).\n */\n public static function toImapUtf7(string $string): string\n {\n $result = '';\n $buffer = '';\n\n // Iterate over each character in the UTF-8 string.\n for ($i = 0; $i < mb_strlen($string, 'UTF-8'); $i++) {\n $char = mb_substr($string, $i, 1, 'UTF-8');\n\n // Convert character to its UTF-16BE code unit (for deciding if ASCII).\n $ord = unpack('n', mb_convert_encoding($char, 'UTF-16BE', 'UTF-8'))[1];\n\n // Handle printable ASCII characters (0x20 - 0x7E) except '&'\n if ($ord >= 0x20 && $ord <= 0x7E && $char !== '&') {\n // If there is any buffered non-ASCII content, flush it as a base64 section.\n if ($buffer !== '') {\n // Encode the buffer to UTF-16BE, then to base64, swap '/' for ',', trim '=' padding, and wrap with '&' and '-'.\n $result .= '&'.rtrim(strtr(base64_encode(mb_convert_encoding($buffer, 'UTF-16BE', 'UTF-8')), '/', ','), '=').'-';\n $buffer = '';\n }\n\n // Append the ASCII character as-is.\n $result .= $char;\n\n continue;\n }\n\n // Special handling for literal '&' which becomes '&-'\n if ($char === '&') {\n // Flush any buffered non-ASCII content first.\n if ($buffer !== '') {\n $result .= '&'.rtrim(strtr(base64_encode(mb_convert_encoding($buffer, 'UTF-16BE', 'UTF-8')), '/', ','), '=').'-';\n $buffer = '';\n }\n\n // '&' is encoded as '&-'\n $result .= '&-';\n\n continue;\n }\n\n // Buffer non-ASCII characters for later base64 encoding.\n $buffer .= $char;\n }\n\n // After the loop, flush any remaining buffered non-ASCII content.\n if ($buffer !== '') {\n $result .= '&'.rtrim(strtr(base64_encode(mb_convert_encoding($buffer, 'UTF-16BE', 'UTF-8')), '/', ','), '=').'-';\n }\n\n return $result;\n }\n\n /**\n * Determine if a given string matches a given pattern.\n */\n public static function is(array|string $pattern, string $value, bool $ignoreCase = false)\n {\n if (! is_iterable($pattern)) {\n $pattern = [$pattern];\n }\n\n foreach ($pattern as $pattern) {\n $pattern = (string) $pattern;\n\n // If the given value is an exact match we can of course return true right\n // from the beginning. Otherwise, we will translate asterisks and do an\n // actual pattern match against the two strings to see if they match.\n if ($pattern === '*' || $pattern === $value) {\n return true;\n }\n\n if ($ignoreCase && mb_strtolower($pattern) === mb_strtolower($value)) {\n return true;\n }\n\n $pattern = preg_quote($pattern, '#');\n\n // Asterisks are translated into zero-or-more regular expression wildcards\n // to make it convenient to check if the strings starts with the given\n // pattern such as \"library/*\", making any string check convenient.\n $pattern = str_replace('\\*', '.*', $pattern);\n\n if (preg_match('#^'.$pattern.'\\z#'.($ignoreCase ? 'isu' : 'su'), $value) === 1) {\n return true;\n }\n }\n\n return false;\n }\n}\n"], ["/ImapEngine/src/Pagination/LengthAwarePaginator.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Pagination;\n\nuse DirectoryTree\\ImapEngine\\Support\\ForwardsCalls;\nuse Illuminate\\Contracts\\Support\\Arrayable;\nuse Illuminate\\Support\\Collection;\nuse JsonSerializable;\n\n/**\n * @template TKey of array-key\n *\n * @template-covariant TValue\n *\n * @template-implements Arrayable<TKey, TValue>\n */\nclass LengthAwarePaginator implements Arrayable, JsonSerializable\n{\n use ForwardsCalls;\n\n /**\n * Constructor.\n */\n public function __construct(\n protected Collection $items,\n protected int $total,\n protected int $perPage,\n protected int $currentPage = 1,\n protected string $path = '',\n protected array $query = [],\n protected string $pageName = 'page',\n ) {\n $this->currentPage = max($currentPage, 1);\n\n $this->path = rtrim($path, '/');\n }\n\n /**\n * Handle dynamic method calls on the paginator.\n */\n public function __call(string $method, array $parameters): mixed\n {\n return $this->forwardCallTo($this->items, $method, $parameters);\n }\n\n /**\n * Get the items being paginated.\n *\n * @return Collection<TKey, TValue>\n */\n public function items(): Collection\n {\n return $this->items;\n }\n\n /**\n * Get the total number of items.\n */\n public function total(): int\n {\n return $this->total;\n }\n\n /**\n * Get the number of items per page.\n */\n public function perPage(): int\n {\n return $this->perPage;\n }\n\n /**\n * Get the current page number.\n */\n public function currentPage(): int\n {\n return $this->currentPage;\n }\n\n /**\n * Get the last page (total pages).\n */\n public function lastPage(): int\n {\n return (int) ceil($this->total / $this->perPage);\n }\n\n /**\n * Determine if there are enough items to split into multiple pages.\n */\n public function hasPages(): bool\n {\n return $this->total() > $this->perPage();\n }\n\n /**\n * Determine if there is a next page.\n */\n public function hasMorePages(): bool\n {\n return $this->currentPage() < $this->lastPage();\n }\n\n /**\n * Generate the URL for a given page.\n */\n public function url(int $page): string\n {\n $params = array_merge($this->query, [$this->pageName => $page]);\n\n $queryString = http_build_query($params);\n\n return $this->path.($queryString ? '?'.$queryString : '');\n }\n\n /**\n * Get the URL for the next page, or null if none.\n */\n public function nextPageUrl(): ?string\n {\n if ($this->hasMorePages()) {\n return $this->url($this->currentPage() + 1);\n }\n\n return null;\n }\n\n /**\n * Get the URL for the previous page, or null if none.\n */\n public function previousPageUrl(): ?string\n {\n if ($this->currentPage() > 1) {\n return $this->url($this->currentPage() - 1);\n }\n\n return null;\n }\n\n /**\n * Get the array representation of the paginator.\n */\n public function toArray(): array\n {\n return [\n 'path' => $this->path,\n 'total' => $this->total(),\n 'to' => $this->calculateTo(),\n 'per_page' => $this->perPage(),\n 'last_page' => $this->lastPage(),\n 'first_page_url' => $this->url(1),\n 'data' => $this->items()->toArray(),\n 'current_page' => $this->currentPage(),\n 'next_page_url' => $this->nextPageUrl(),\n 'prev_page_url' => $this->previousPageUrl(),\n 'last_page_url' => $this->url($this->lastPage()),\n 'from' => $this->total() ? ($this->currentPage() - 1) * $this->perPage() + 1 : null,\n ];\n }\n\n /**\n * Calculate the \"to\" index for the current page.\n */\n protected function calculateTo(): ?int\n {\n if (! $this->total()) {\n return null;\n }\n\n $to = $this->currentPage() * $this->perPage();\n\n return min($to, $this->total());\n }\n\n /**\n * Get the JSON representation of the paginator.\n */\n public function jsonSerialize(): array\n {\n return $this->toArray();\n }\n}\n"], ["/ImapEngine/src/MessageQuery.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\nuse DirectoryTree\\ImapEngine\\Collections\\MessageCollection;\nuse DirectoryTree\\ImapEngine\\Collections\\ResponseCollection;\nuse DirectoryTree\\ImapEngine\\Connection\\ConnectionInterface;\nuse DirectoryTree\\ImapEngine\\Connection\\ImapQueryBuilder;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\MessageResponseParser;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\UntaggedResponse;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\Atom;\nuse DirectoryTree\\ImapEngine\\Enums\\ImapFetchIdentifier;\nuse DirectoryTree\\ImapEngine\\Enums\\ImapFlag;\nuse DirectoryTree\\ImapEngine\\Exceptions\\ImapCommandException;\nuse DirectoryTree\\ImapEngine\\Pagination\\LengthAwarePaginator;\nuse DirectoryTree\\ImapEngine\\Support\\Str;\nuse Illuminate\\Support\\Collection;\nuse Illuminate\\Support\\ItemNotFoundException;\n\n/**\n * @mixin \\DirectoryTree\\ImapEngine\\Connection\\ImapQueryBuilder\n */\nclass MessageQuery implements MessageQueryInterface\n{\n use QueriesMessages;\n\n /**\n * Constructor.\n */\n public function __construct(\n protected FolderInterface $folder,\n protected ImapQueryBuilder $query,\n ) {}\n\n /**\n * Count all available messages matching the current search criteria.\n */\n public function count(): int\n {\n return $this->search()->count();\n }\n\n /**\n * Get the first message in the resulting collection.\n *\n * @return Message|null\n */\n public function first(): ?MessageInterface\n {\n try {\n return $this->firstOrFail();\n } catch (ItemNotFoundException) {\n return null;\n }\n }\n\n /**\n * Get the first message in the resulting collection or throw an exception.\n *\n * @return Message\n */\n public function firstOrFail(): MessageInterface\n {\n return $this->limit(1)->get()->firstOrFail();\n }\n\n /**\n * Get the messages matching the current query.\n */\n public function get(): MessageCollection\n {\n return $this->process($this->search());\n }\n\n /**\n * Append a new message to the folder.\n */\n public function append(string $message, mixed $flags = null): int\n {\n $response = $this->connection()->append(\n $this->folder->path(), $message, Str::enums($flags),\n );\n\n return $response // TAG4 OK [APPENDUID <uidvalidity> <uid>] APPEND completed.\n ->tokenAt(2) // [APPENDUID <uidvalidity> <uid>]\n ->tokenAt(2) // <uid>\n ->value;\n }\n\n /**\n * Execute a callback over each message via a chunked query.\n */\n public function each(callable $callback, int $chunkSize = 10, int $startChunk = 1): void\n {\n $this->chunk(function (MessageCollection $messages) use ($callback) {\n foreach ($messages as $key => $message) {\n if ($callback($message, $key) === false) {\n return false;\n }\n }\n }, $chunkSize, $startChunk);\n }\n\n /**\n * Execute a callback over each chunk of messages.\n */\n public function chunk(callable $callback, int $chunkSize = 10, int $startChunk = 1): void\n {\n $startChunk = max($startChunk, 1);\n $chunkSize = max($chunkSize, 1);\n\n // Get all search result tokens once.\n $messages = $this->search();\n\n // Calculate how many chunks there are\n $totalChunks = (int) ceil($messages->count() / $chunkSize);\n\n // If startChunk is beyond our total chunks, return early.\n if ($startChunk > $totalChunks) {\n return;\n }\n\n // Save previous state to restore later.\n $previousLimit = $this->limit;\n $previousPage = $this->page;\n\n $this->limit = $chunkSize;\n\n // Iterate from the starting chunk to the last chunk.\n for ($page = $startChunk; $page <= $totalChunks; $page++) {\n $this->page = $page;\n\n // populate() will use $this->page to slice the results.\n $hydrated = $this->populate($messages);\n\n // If no messages are returned, break out to prevent infinite loop.\n if ($hydrated->isEmpty()) {\n break;\n }\n\n // If the callback returns false, break out.\n if ($callback($hydrated, $page) === false) {\n break;\n }\n }\n\n // Restore the original state.\n $this->limit = $previousLimit;\n $this->page = $previousPage;\n }\n\n /**\n * Paginate the current query.\n */\n public function paginate(int $perPage = 5, $page = null, string $pageName = 'page'): LengthAwarePaginator\n {\n if (is_null($page) && isset($_GET[$pageName]) && $_GET[$pageName] > 0) {\n $this->page = intval($_GET[$pageName]);\n } elseif ($page > 0) {\n $this->page = (int) $page;\n }\n\n $this->limit = $perPage;\n\n return $this->get()->paginate($perPage, $this->page, $pageName, true);\n }\n\n /**\n * Find a message by the given identifier type or throw an exception.\n *\n * @return Message\n */\n public function findOrFail(int $id, ImapFetchIdentifier $identifier = ImapFetchIdentifier::Uid): MessageInterface\n {\n /** @var UntaggedResponse $response */\n $response = $this->id($id, $identifier)->firstOrFail();\n\n $uid = $response->tokenAt(3) // ListData\n ->tokenAt(1) // Atom\n ->value; // UID\n\n return $this->process(new MessageCollection([$uid]))->firstOrFail();\n }\n\n /**\n * Find a message by the given identifier type.\n *\n * @return Message|null\n */\n public function find(int $id, ImapFetchIdentifier $identifier = ImapFetchIdentifier::Uid): ?MessageInterface\n {\n /** @var UntaggedResponse $response */\n if (! $response = $this->id($id, $identifier)->first()) {\n return null;\n }\n\n $uid = $response->tokenAt(3) // ListData\n ->tokenAt(1) // Atom\n ->value; // UID\n\n return $this->process(new MessageCollection([$uid]))->first();\n }\n\n /**\n * Destroy the given messages.\n */\n public function destroy(array|int $uids, bool $expunge = false): void\n {\n $uids = (array) $uids;\n\n $this->folder->mailbox()\n ->connection()\n ->store([ImapFlag::Deleted->value], $uids, mode: '+');\n\n if ($expunge) {\n $this->folder->expunge();\n }\n }\n\n /**\n * Process the collection of messages.\n */\n protected function process(Collection $messages): MessageCollection\n {\n if ($messages->isNotEmpty()) {\n return $this->populate($messages);\n }\n\n return MessageCollection::make();\n }\n\n /**\n * Populate a given id collection and receive a fully fetched message collection.\n */\n protected function populate(Collection $uids): MessageCollection\n {\n $messages = MessageCollection::make();\n\n $messages->total($uids->count());\n\n $rawMessages = $this->fetch($uids);\n\n foreach ($rawMessages['uids'] as $uid) {\n $flags = $rawMessages['flags'][$uid] ?? [];\n $headers = $rawMessages['headers'][$uid] ?? '';\n $contents = $rawMessages['contents'][$uid] ?? '';\n\n $messages->push(\n $this->newMessage($uid, $flags, $headers, $contents)\n );\n }\n\n return $messages;\n }\n\n /**\n * Fetch a given id collection.\n */\n protected function fetch(Collection $messages): array\n {\n if ($this->fetchOrder === 'desc') {\n $messages = $messages->reverse();\n }\n\n $uids = $messages->forPage($this->page, $this->limit)->toArray();\n\n $flags = $this->fetchFlags ? $this->connection()\n ->flags($uids)\n ->mapWithKeys(MessageResponseParser::getFlags(...))->all() : [];\n\n $headers = $this->fetchHeaders ? $this->connection()\n ->bodyHeader($uids, $this->fetchAsUnread)\n ->mapWithKeys(MessageResponseParser::getBodyHeader(...))->all() : [];\n\n $contents = $this->fetchBody ? $this->connection()\n ->bodyText($uids, $this->fetchAsUnread)\n ->mapWithKeys(MessageResponseParser::getBodyText(...))->all() : [];\n\n return [\n 'uids' => $uids,\n 'flags' => $flags,\n 'headers' => $headers,\n 'contents' => $contents,\n ];\n }\n\n /**\n * Execute an IMAP search request.\n */\n protected function search(): Collection\n {\n // If the query is empty, default to fetching all.\n if ($this->query->isEmpty()) {\n $this->query->all();\n }\n\n $response = $this->connection()->search([\n $this->query->toImap(),\n ]);\n\n return new Collection(array_map(\n fn (Atom $token) => $token->value,\n $response->tokensAfter(2)\n ));\n }\n\n /**\n * Get the UID for the given identifier.\n */\n protected function id(int $id, ImapFetchIdentifier $identifier = ImapFetchIdentifier::Uid): ResponseCollection\n {\n try {\n return $this->connection()->uid([$id], $identifier);\n } catch (ImapCommandException $e) {\n // IMAP servers may return an error if the message number is not found.\n // If the identifier being used is a message number, and the message\n // number is in the command tokens, we can assume this has occurred\n // and safely ignore the error and return an empty collection.\n if (\n $identifier === ImapFetchIdentifier::MessageNumber\n && in_array($id, $e->command()->tokens())\n ) {\n return ResponseCollection::make();\n }\n\n // Otherwise, re-throw the exception.\n throw $e;\n }\n }\n\n /**\n * Make a new message from given raw components.\n */\n protected function newMessage(int $uid, array $flags, string $headers, string $contents): Message\n {\n return new Message($this->folder, $uid, $flags, $headers, $contents);\n }\n\n /**\n * Get the connection instance.\n */\n protected function connection(): ConnectionInterface\n {\n return $this->folder->mailbox()->connection();\n }\n}\n"], ["/ImapEngine/src/Connection/ImapConnection.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection;\n\nuse DirectoryTree\\ImapEngine\\Collections\\ResponseCollection;\nuse DirectoryTree\\ImapEngine\\Connection\\Loggers\\LoggerInterface;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\ContinuationResponse;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\Data\\Data;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\Data\\ListData;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\Response;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\TaggedResponse;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\UntaggedResponse;\nuse DirectoryTree\\ImapEngine\\Connection\\Streams\\FakeStream;\nuse DirectoryTree\\ImapEngine\\Connection\\Streams\\StreamInterface;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\Token;\nuse DirectoryTree\\ImapEngine\\Enums\\ImapFetchIdentifier;\nuse DirectoryTree\\ImapEngine\\Exceptions\\ImapCommandException;\nuse DirectoryTree\\ImapEngine\\Exceptions\\ImapConnectionClosedException;\nuse DirectoryTree\\ImapEngine\\Exceptions\\ImapConnectionFailedException;\nuse DirectoryTree\\ImapEngine\\Exceptions\\ImapConnectionTimedOutException;\nuse DirectoryTree\\ImapEngine\\Exceptions\\ImapResponseException;\nuse DirectoryTree\\ImapEngine\\Exceptions\\ImapStreamException;\nuse DirectoryTree\\ImapEngine\\Support\\Str;\nuse Exception;\nuse Generator;\nuse LogicException;\n\nclass ImapConnection implements ConnectionInterface\n{\n /**\n * Sequence number used to generate unique command tags.\n */\n protected int $sequence = 0;\n\n /**\n * The result instance.\n */\n protected ?Result $result = null;\n\n /**\n * The parser instance.\n */\n protected ?ImapParser $parser = null;\n\n /**\n * Constructor.\n */\n public function __construct(\n protected StreamInterface $stream,\n protected ?LoggerInterface $logger = null,\n ) {}\n\n /**\n * Create a new connection with a fake stream.\n */\n public static function fake(array $responses = []): static\n {\n $stream = new FakeStream;\n\n $stream->open();\n\n $stream->feed($responses);\n\n return new static($stream);\n }\n\n /**\n * Tear down the connection.\n */\n public function __destruct()\n {\n if (! $this->connected()) {\n return;\n }\n\n try {\n @$this->logout();\n } catch (Exception $e) {\n // Do nothing.\n }\n }\n\n /**\n * {@inheritDoc}\n */\n public function connect(string $host, ?int $port = null, array $options = []): void\n {\n $transport = strtolower($options['encryption'] ?? '') ?: 'tcp';\n\n if (in_array($transport, ['ssl', 'tls'])) {\n $port ??= 993;\n } else {\n $port ??= 143;\n }\n\n $this->setParser(\n $this->newParser($this->stream)\n );\n\n $this->stream->open(\n $transport === 'starttls' ? 'tcp' : $transport,\n $host,\n $port,\n $options['timeout'] ?? 30,\n $this->getDefaultSocketOptions(\n $transport,\n $options['proxy'] ?? [],\n $options['validate_cert'] ?? true\n )\n );\n\n $this->assertNextResponse(\n fn (Response $response) => $response instanceof UntaggedResponse,\n fn (UntaggedResponse $response) => $response->type()->is('OK'),\n fn () => new ImapConnectionFailedException(\"Connection to $host:$port failed\")\n );\n\n if ($transport === 'starttls') {\n $this->startTls();\n }\n }\n\n /**\n * Get the default socket options for the given transport.\n */\n protected function getDefaultSocketOptions(string $transport, array $proxy = [], bool $validateCert = true): array\n {\n $options = [];\n\n $key = match ($transport) {\n 'ssl', 'tls' => 'ssl',\n 'starttls', 'tcp' => 'tcp',\n };\n\n if (in_array($transport, ['ssl', 'tls'])) {\n $options[$key] = [\n 'verify_peer' => $validateCert,\n 'verify_peer_name' => $validateCert,\n ];\n }\n\n if (! isset($proxy['socket'])) {\n return $options;\n }\n\n $options[$key]['proxy'] = $proxy['socket'];\n $options[$key]['request_fulluri'] = $proxy['request_fulluri'] ?? false;\n\n if (isset($proxy['username'])) {\n $auth = base64_encode($proxy['username'].':'.$proxy['password']);\n\n $options[$key]['header'] = [\"Proxy-Authorization: Basic $auth\"];\n }\n\n return $options;\n }\n\n /**\n * {@inheritDoc}\n */\n public function disconnect(): void\n {\n $this->stream->close();\n }\n\n /**\n * {@inheritDoc}\n */\n public function connected(): bool\n {\n return $this->stream->opened();\n }\n\n /**\n * {@inheritDoc}\n */\n public function login(string $user, string $password): TaggedResponse\n {\n $this->send('LOGIN', Str::literal([$user, $password]), $tag);\n\n return $this->assertTaggedResponse($tag, fn (TaggedResponse $response) => (\n ImapCommandException::make($this->result->command()->redacted(), $response)\n ));\n }\n\n /**\n * {@inheritDoc}\n */\n public function logout(): void\n {\n $this->send('LOGOUT', tag: $tag);\n }\n\n /**\n * {@inheritDoc}\n */\n public function authenticate(string $user, string $token): TaggedResponse\n {\n $this->send('AUTHENTICATE', ['XOAUTH2', Str::credentials($user, $token)], $tag);\n\n return $this->assertTaggedResponse($tag, fn (TaggedResponse $response) => (\n ImapCommandException::make($this->result->command()->redacted(), $response)\n ));\n }\n\n /**\n * {@inheritDoc}\n */\n public function startTls(): void\n {\n $this->send('STARTTLS', tag: $tag);\n\n $this->assertTaggedResponse($tag);\n\n $this->stream->setSocketSetCrypto(true, STREAM_CRYPTO_METHOD_TLS_CLIENT);\n }\n\n /**\n * {@inheritDoc}\n */\n public function select(string $folder = 'INBOX'): ResponseCollection\n {\n return $this->examineOrSelect('SELECT', $folder);\n }\n\n /**\n * {@inheritDoc}\n */\n public function examine(string $folder = 'INBOX'): ResponseCollection\n {\n return $this->examineOrSelect('EXAMINE', $folder);\n }\n\n /**\n * Examine and select have the same response.\n */\n protected function examineOrSelect(string $command = 'EXAMINE', string $folder = 'INBOX'): ResponseCollection\n {\n $this->send($command, [Str::literal($folder)], $tag);\n\n $this->assertTaggedResponse($tag);\n\n return $this->result->responses()->untagged();\n }\n\n /**\n * {@inheritDoc}\n */\n public function status(string $folder = 'INBOX', array $arguments = ['MESSAGES', 'UNSEEN', 'RECENT', 'UIDNEXT', 'UIDVALIDITY']): UntaggedResponse\n {\n $this->send('STATUS', [\n Str::literal($folder),\n Str::list($arguments),\n ], $tag);\n\n $this->assertTaggedResponse($tag);\n\n return $this->result->responses()->untagged()->firstWhere(\n fn (UntaggedResponse $response) => $response->type()->is('STATUS')\n );\n }\n\n /**\n * {@inheritDoc}\n */\n public function create(string $folder): ResponseCollection\n {\n $this->send('CREATE', [Str::literal($folder)], $tag);\n\n $this->assertTaggedResponse($tag);\n\n return $this->result->responses()->untagged()->filter(\n fn (UntaggedResponse $response) => $response->type()->is('LIST')\n );\n }\n\n /**\n * {@inheritDoc}\n */\n public function delete(string $folder): TaggedResponse\n {\n $this->send('DELETE', [Str::literal($folder)], tag: $tag);\n\n return $this->assertTaggedResponse($tag);\n }\n\n /**\n * {@inheritDoc}\n */\n public function rename(string $oldPath, string $newPath): TaggedResponse\n {\n $this->send('RENAME', Str::literal([$oldPath, $newPath]), tag: $tag);\n\n return $this->assertTaggedResponse($tag);\n }\n\n /**\n * {@inheritDoc}\n */\n public function subscribe(string $folder): TaggedResponse\n {\n $this->send('SUBSCRIBE', [Str::literal($folder)], tag: $tag);\n\n return $this->assertTaggedResponse($tag);\n }\n\n /**\n * {@inheritDoc}\n */\n public function unsubscribe(string $folder): TaggedResponse\n {\n $this->send('UNSUBSCRIBE', [Str::literal($folder)], tag: $tag);\n\n return $this->assertTaggedResponse($tag);\n }\n\n /**\n * {@inheritDoc}\n */\n public function list(string $reference = '', string $folder = '*'): ResponseCollection\n {\n $this->send('LIST', Str::literal([$reference, $folder]), $tag);\n\n $this->assertTaggedResponse($tag);\n\n return $this->result->responses()->untagged()->filter(\n fn (UntaggedResponse $response) => $response->type()->is('LIST')\n );\n }\n\n /**\n * {@inheritDoc}\n */\n public function append(string $folder, string $message, ?array $flags = null): TaggedResponse\n {\n $tokens = [];\n\n $tokens[] = Str::literal($folder);\n\n if ($flags) {\n $tokens[] = Str::list($flags);\n }\n\n $tokens[] = Str::literal($message);\n\n $this->send('APPEND', $tokens, tag: $tag);\n\n return $this->assertTaggedResponse($tag);\n }\n\n /**\n * {@inheritDoc}\n */\n public function copy(string $folder, array|int $from, ?int $to = null): TaggedResponse\n {\n $this->send('UID COPY', [\n Str::set($from, $to),\n Str::literal($folder),\n ], $tag);\n\n return $this->assertTaggedResponse($tag);\n }\n\n /**\n * {@inheritDoc}\n */\n public function move(string $folder, array|int $from, ?int $to = null): TaggedResponse\n {\n $this->send('UID MOVE', [\n Str::set($from, $to),\n Str::literal($folder),\n ], $tag);\n\n return $this->assertTaggedResponse($tag);\n }\n\n /**\n * {@inheritDoc}\n */\n public function store(array|string $flags, array|int $from, ?int $to = null, ?string $mode = null, bool $silent = true, ?string $item = null): ResponseCollection\n {\n $set = Str::set($from, $to);\n\n $flags = Str::list((array) $flags);\n\n $item = ($mode == '-' ? '-' : '+').(is_null($item) ? 'FLAGS' : $item).($silent ? '.SILENT' : '');\n\n $this->send('UID STORE', [$set, $item, $flags], tag: $tag);\n\n $this->assertTaggedResponse($tag);\n\n return $silent ? new ResponseCollection : $this->result->responses()->untagged()->filter(\n fn (UntaggedResponse $response) => $response->type()->is('FETCH')\n );\n }\n\n /**\n * {@inheritDoc}\n */\n public function uid(int|array $ids, ImapFetchIdentifier $identifier): ResponseCollection\n {\n return $this->fetch(['UID'], (array) $ids, null, $identifier);\n }\n\n /**\n * {@inheritDoc}\n */\n public function bodyText(int|array $ids, bool $peek = true): ResponseCollection\n {\n return $this->fetch([$peek ? 'BODY.PEEK[TEXT]' : 'BODY[TEXT]'], (array) $ids);\n }\n\n /**\n * {@inheritDoc}\n */\n public function bodyHeader(int|array $ids, bool $peek = true): ResponseCollection\n {\n return $this->fetch([$peek ? 'BODY.PEEK[HEADER]' : 'BODY[HEADER]'], (array) $ids);\n }\n\n /**\n * Fetch the BODYSTRUCTURE for the given message(s).\n */\n public function bodyStructure(int|array $ids): ResponseCollection\n {\n return $this->fetch(['BODYSTRUCTURE'], (array) $ids);\n }\n\n /**\n * Fetch a specific part of the message BODY, such as BODY[1], BODY[1.2], etc.\n */\n public function bodyPart(string $partIndex, int|array $ids, bool $peek = false): ResponseCollection\n {\n $part = $peek ? \"BODY.PEEK[$partIndex]\" : \"BODY[$partIndex]\";\n\n return $this->fetch([$part], (array) $ids);\n }\n\n /**\n * {@inheritDoc}\n */\n public function flags(int|array $ids): ResponseCollection\n {\n return $this->fetch(['FLAGS'], (array) $ids);\n }\n\n /**\n * {@inheritDoc}\n */\n public function size(int|array $ids): ResponseCollection\n {\n return $this->fetch(['RFC822.SIZE'], (array) $ids);\n }\n\n /**\n * {@inheritDoc}\n */\n public function search(array $params): UntaggedResponse\n {\n $this->send('UID SEARCH', $params, tag: $tag);\n\n $this->assertTaggedResponse($tag);\n\n return $this->result->responses()->untagged()->firstOrFail(\n fn (UntaggedResponse $response) => $response->type()->is('SEARCH')\n );\n }\n\n /**\n * {@inheritDoc}\n */\n public function capability(): UntaggedResponse\n {\n $this->send('CAPABILITY', tag: $tag);\n\n $this->assertTaggedResponse($tag);\n\n return $this->result->responses()->untagged()->firstOrFail(\n fn (UntaggedResponse $response) => $response->type()->is('CAPABILITY')\n );\n }\n\n /**\n * {@inheritDoc}\n */\n public function id(?array $ids = null): UntaggedResponse\n {\n $token = 'NIL';\n\n if (is_array($ids) && ! empty($ids)) {\n $token = '(';\n\n foreach ($ids as $id) {\n $token .= '\"'.$id.'\" ';\n }\n\n $token = rtrim($token).')';\n }\n\n $this->send('ID', [$token], tag: $tag);\n\n $this->assertTaggedResponse($tag);\n\n return $this->result->responses()->untagged()->firstOrFail(\n fn (UntaggedResponse $response) => $response->type()->is('ID')\n );\n }\n\n /**\n * {@inheritDoc}\n */\n public function expunge(): ResponseCollection\n {\n $this->send('EXPUNGE', tag: $tag);\n\n $this->assertTaggedResponse($tag);\n\n return $this->result->responses()->untagged();\n }\n\n /**\n * {@inheritDoc}\n */\n public function noop(): TaggedResponse\n {\n $this->send('NOOP', tag: $tag);\n\n return $this->assertTaggedResponse($tag);\n }\n\n /**\n * {@inheritDoc}\n */\n public function idle(int $timeout): Generator\n {\n $this->stream->setTimeout($timeout);\n\n $this->send('IDLE', tag: $tag);\n\n $this->assertNextResponse(\n fn (Response $response) => $response instanceof ContinuationResponse,\n fn (ContinuationResponse $response) => true,\n fn (ContinuationResponse $response) => ImapCommandException::make(new ImapCommand('', 'IDLE'), $response),\n );\n\n while ($response = $this->nextReply()) {\n yield $response;\n }\n }\n\n /**\n * {@inheritDoc}\n */\n public function done(): void\n {\n $this->write('DONE');\n\n // After issuing a \"DONE\" command, the server must eventually respond with a\n // tagged response to indicate that the IDLE command has been successfully\n // terminated and the server is ready to accept further commands.\n $this->assertNextResponse(\n fn (Response $response) => $response instanceof TaggedResponse,\n fn (TaggedResponse $response) => $response->successful(),\n fn (TaggedResponse $response) => ImapCommandException::make(new ImapCommand('', 'DONE'), $response),\n );\n }\n\n /**\n * Send an IMAP command.\n */\n public function send(string $name, array $tokens = [], ?string &$tag = null): void\n {\n if (! $tag) {\n $this->sequence++;\n $tag = 'TAG'.$this->sequence;\n }\n\n $command = new ImapCommand($tag, $name, $tokens);\n\n // After every command, we'll overwrite any previous result\n // with the new command and its responses, so that we can\n // easily access the commands responses for assertion.\n $this->setResult(new Result($command));\n\n foreach ($command->compile() as $line) {\n $this->write($line);\n }\n }\n\n /**\n * Write data to the connected stream.\n */\n protected function write(string $data): void\n {\n if ($this->stream->fwrite($data.\"\\r\\n\") === false) {\n throw new ImapStreamException('Failed to write data to stream');\n }\n\n $this->logger?->sent($data);\n }\n\n /**\n * Fetch one or more items for one or more messages.\n */\n public function fetch(array|string $items, array|int $from, mixed $to = null, ImapFetchIdentifier $identifier = ImapFetchIdentifier::Uid): ResponseCollection\n {\n $prefix = ($identifier === ImapFetchIdentifier::Uid) ? 'UID' : '';\n\n $this->send(trim($prefix.' FETCH'), [\n Str::set($from, $to),\n Str::list((array) $items),\n ], $tag);\n\n $this->assertTaggedResponse($tag);\n\n // Some IMAP servers can send unsolicited untagged responses along with fetch\n // requests. We'll need to filter these out so that we can return only the\n // responses that are relevant to the fetch command. For example:\n // >> TAG123 FETCH (UID 456 BODY[TEXT])\n // << * 123 FETCH (UID 456 BODY[TEXT] {14}\\nHello, World!)\n // << * 123 FETCH (FLAGS (\\Seen)) <-- Unsolicited response\n return $this->result->responses()->untagged()->filter(function (UntaggedResponse $response) use ($items, $identifier) {\n // Skip over any untagged responses that are not FETCH responses.\n // The third token should always be the list of data items.\n if (! ($data = $response->tokenAt(3)) instanceof ListData) {\n return false;\n }\n\n return match ($identifier) {\n // If we're fetching UIDs, we can check if a UID token is contained in the list.\n ImapFetchIdentifier::Uid => $data->contains('UID'),\n\n // If we're fetching message numbers, we can check if the requested items are all contained in the list.\n ImapFetchIdentifier::MessageNumber => $data->contains($items),\n };\n });\n }\n\n /**\n * Set the current result instance.\n */\n protected function setResult(Result $result): void\n {\n $this->result = $result;\n }\n\n /**\n * Set the current parser instance.\n */\n protected function setParser(ImapParser $parser): void\n {\n $this->parser = $parser;\n }\n\n /**\n * Create a new parser instance.\n */\n protected function newParser(StreamInterface $stream): ImapParser\n {\n return new ImapParser($this->newTokenizer($stream));\n }\n\n /**\n * Create a new tokenizer instance.\n */\n protected function newTokenizer(StreamInterface $stream): ImapTokenizer\n {\n return new ImapTokenizer($stream);\n }\n\n /**\n * Assert the next response is a successful tagged response.\n */\n protected function assertTaggedResponse(string $tag, ?callable $exception = null): TaggedResponse\n {\n return $this->assertNextResponse(\n fn (Response $response) => (\n $response instanceof TaggedResponse && $response->tag()->is($tag)\n ),\n fn (TaggedResponse $response) => (\n $response->successful()\n ),\n $exception ?? fn (TaggedResponse $response) => (\n ImapCommandException::make($this->result->command(), $response)\n ),\n );\n }\n\n /**\n * Assert the next response matches the given filter and assertion.\n *\n * @template T of Response\n *\n * @param callable(Response): bool $filter\n * @return T\n */\n protected function assertNextResponse(callable $filter, callable $assertion, callable $exception): Response\n {\n while ($response = $this->nextResponse($filter)) {\n if ($assertion($response)) {\n return $response;\n }\n\n throw $exception($response);\n }\n\n throw new ImapResponseException('No matching response found');\n }\n\n /**\n * Returns the next response matching the given filter.\n *\n * @template T of Response\n *\n * @param callable(Response): bool $filter\n * @return T\n */\n protected function nextResponse(callable $filter): Response\n {\n if (! $this->parser) {\n throw new LogicException('No parser instance set');\n }\n\n while ($response = $this->nextReply()) {\n if (! $response instanceof Response) {\n continue;\n }\n\n $this->result?->addResponse($response);\n\n if ($filter($response)) {\n return $response;\n }\n }\n\n throw new ImapResponseException('No matching response found');\n }\n\n /**\n * Read the next reply from the stream.\n */\n protected function nextReply(): Data|Token|Response|null\n {\n if (! $reply = $this->parser->next()) {\n $meta = $this->stream->meta();\n\n throw match (true) {\n $meta['timed_out'] ?? false => new ImapConnectionTimedOutException('Stream timed out, no response'),\n $meta['eof'] ?? false => new ImapConnectionClosedException('Server closed the connection (EOF)'),\n default => new ImapConnectionFailedException('Unknown stream error. Metadata: '.json_encode($meta)),\n };\n }\n\n $this->logger?->received($reply);\n\n return $reply;\n }\n}\n"], ["/ImapEngine/src/QueriesMessages.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\nuse DirectoryTree\\ImapEngine\\Connection\\ImapQueryBuilder;\nuse DirectoryTree\\ImapEngine\\Support\\ForwardsCalls;\nuse Illuminate\\Support\\Traits\\Conditionable;\n\ntrait QueriesMessages\n{\n use Conditionable, ForwardsCalls;\n\n /**\n * The query builder instance.\n */\n protected ImapQueryBuilder $query;\n\n /**\n * The current page.\n */\n protected int $page = 1;\n\n /**\n * The fetch limit.\n */\n protected ?int $limit = null;\n\n /**\n * Whether to fetch the message body.\n */\n protected bool $fetchBody = false;\n\n /**\n * Whether to fetch the message flags.\n */\n protected bool $fetchFlags = false;\n\n /**\n * Whether to fetch the message headers.\n */\n protected bool $fetchHeaders = false;\n\n /**\n * The fetch order.\n */\n protected string $fetchOrder = 'desc';\n\n /**\n * Whether to leave messages fetched as unread by default.\n */\n protected bool $fetchAsUnread = true;\n\n /**\n * The methods that should be returned from query builder.\n */\n protected array $passthru = ['toimap', 'isempty'];\n\n /**\n * Handle dynamic method calls into the query builder.\n */\n public function __call(string $method, array $parameters): mixed\n {\n if (in_array(strtolower($method), $this->passthru)) {\n return $this->query->{$method}(...$parameters);\n }\n\n $this->forwardCallTo($this->query, $method, $parameters);\n\n return $this;\n }\n\n /**\n * {@inheritDoc}\n */\n public function leaveUnread(): MessageQueryInterface\n {\n $this->fetchAsUnread = true;\n\n return $this;\n }\n\n /**\n * {@inheritDoc}\n */\n public function markAsRead(): MessageQueryInterface\n {\n $this->fetchAsUnread = false;\n\n return $this;\n }\n\n /**\n * {@inheritDoc}\n */\n public function limit(int $limit, int $page = 1): MessageQueryInterface\n {\n if ($page >= 1) {\n $this->page = $page;\n }\n\n $this->limit = $limit;\n\n return $this;\n }\n\n /**\n * {@inheritDoc}\n */\n public function getLimit(): ?int\n {\n return $this->limit;\n }\n\n /**\n * {@inheritDoc}\n */\n public function setLimit(int $limit): MessageQueryInterface\n {\n $this->limit = max($limit, 1);\n\n return $this;\n }\n\n /**\n * {@inheritDoc}\n */\n public function getPage(): int\n {\n return $this->page;\n }\n\n /**\n * {@inheritDoc}\n */\n public function setPage(int $page): MessageQueryInterface\n {\n $this->page = $page;\n\n return $this;\n }\n\n /**\n * {@inheritDoc}\n */\n public function isFetchingBody(): bool\n {\n return $this->fetchBody;\n }\n\n /**\n * {@inheritDoc}\n */\n public function isFetchingFlags(): bool\n {\n return $this->fetchFlags;\n }\n\n /**\n * {@inheritDoc}\n */\n public function isFetchingHeaders(): bool\n {\n return $this->fetchHeaders;\n }\n\n /**\n * {@inheritDoc}\n */\n public function withFlags(): MessageQueryInterface\n {\n return $this->setFetchFlags(true);\n }\n\n /**\n * {@inheritDoc}\n */\n public function withBody(): MessageQueryInterface\n {\n return $this->setFetchBody(true);\n }\n\n /**\n * {@inheritDoc}\n */\n public function withHeaders(): MessageQueryInterface\n {\n return $this->setFetchHeaders(true);\n }\n\n /**\n * {@inheritDoc}\n */\n public function withoutBody(): MessageQueryInterface\n {\n return $this->setFetchBody(false);\n }\n\n /**\n * {@inheritDoc}\n */\n public function withoutHeaders(): MessageQueryInterface\n {\n return $this->setFetchHeaders(false);\n }\n\n /**\n * {@inheritDoc}\n */\n public function withoutFlags(): MessageQueryInterface\n {\n return $this->setFetchFlags(false);\n }\n\n /**\n * Set whether to fetch the flags.\n */\n protected function setFetchFlags(bool $fetchFlags): MessageQueryInterface\n {\n $this->fetchFlags = $fetchFlags;\n\n return $this;\n }\n\n /**\n * Set the fetch body flag.\n */\n protected function setFetchBody(bool $fetchBody): MessageQueryInterface\n {\n $this->fetchBody = $fetchBody;\n\n return $this;\n }\n\n /**\n * Set whether to fetch the headers.\n */\n protected function setFetchHeaders(bool $fetchHeaders): MessageQueryInterface\n {\n $this->fetchHeaders = $fetchHeaders;\n\n return $this;\n }\n\n /** {@inheritDoc} */\n public function setFetchOrder(string $fetchOrder): MessageQueryInterface\n {\n $fetchOrder = strtolower($fetchOrder);\n\n if (in_array($fetchOrder, ['asc', 'desc'])) {\n $this->fetchOrder = $fetchOrder;\n }\n\n return $this;\n }\n\n /**\n * {@inheritDoc}\n */\n public function getFetchOrder(): string\n {\n return $this->fetchOrder;\n }\n\n /**\n * {@inheritDoc}\n */\n public function setFetchOrderAsc(): MessageQueryInterface\n {\n return $this->setFetchOrder('asc');\n }\n\n /**\n * {@inheritDoc}\n */\n public function setFetchOrderDesc(): MessageQueryInterface\n {\n return $this->setFetchOrder('desc');\n }\n\n /**\n * {@inheritDoc}\n */\n public function oldest(): MessageQueryInterface\n {\n return $this->setFetchOrder('asc');\n }\n\n /**\n * {@inheritDoc}\n */\n public function newest(): MessageQueryInterface\n {\n return $this->setFetchOrder('desc');\n }\n}\n"], ["/ImapEngine/src/Connection/Streams/FakeStream.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Streams;\n\nuse PHPUnit\\Framework\\Assert;\nuse RuntimeException;\n\nclass FakeStream implements StreamInterface\n{\n /**\n * Lines queued for testing; each call to fgets() pops the next line.\n *\n * @var string[]\n */\n protected array $buffer = [];\n\n /**\n * Data that has been \"written\" to this fake stream (for assertion).\n *\n * @var string[]\n */\n protected array $written = [];\n\n /**\n * The connection info.\n */\n protected ?array $connection = null;\n\n /**\n * The mock meta info.\n */\n protected array $meta = [\n 'crypto' => [\n 'protocol' => '',\n 'cipher_name' => '',\n 'cipher_bits' => 0,\n 'cipher_version' => '',\n ],\n 'mode' => 'c',\n 'eof' => false,\n 'blocked' => false,\n 'timed_out' => false,\n 'seekable' => false,\n 'unread_bytes' => 0,\n 'stream_type' => 'tcp_socket/unknown',\n ];\n\n /**\n * Feed a line to the stream buffer with a newline character.\n */\n public function feed(array|string $lines): self\n {\n // We'll ensure that each line ends with a CRLF,\n // as this is the expected behavior of every\n // reply that comes from an IMAP server.\n $lines = array_map(fn (string $line) => (\n rtrim($line, \"\\r\\n\").\"\\r\\n\"\n ), (array) $lines);\n\n array_push($this->buffer, ...$lines);\n\n return $this;\n }\n\n /**\n * Feed a raw line to the stream buffer.\n */\n public function feedRaw(array|string $lines): self\n {\n array_push($this->buffer, ...(array) $lines);\n\n return $this;\n }\n\n /**\n * Set the timed out status.\n */\n public function setMeta(string $attribute, mixed $value): self\n {\n if (! isset($this->meta[$attribute])) {\n throw new RuntimeException(\n \"Unknown metadata attribute: {$attribute}\"\n );\n }\n\n if (gettype($this->meta[$attribute]) !== gettype($value)) {\n throw new RuntimeException(\n \"Metadata attribute {$attribute} must be of type \".gettype($this->meta[$attribute])\n );\n }\n\n $this->meta[$attribute] = $value;\n\n return $this;\n }\n\n /**\n * {@inheritDoc}\n */\n public function open(?string $transport = null, ?string $host = null, ?int $port = null, ?int $timeout = null, array $options = []): bool\n {\n $this->connection = compact('transport', 'host', 'port', 'timeout', 'options');\n\n return true;\n }\n\n /**\n * {@inheritDoc}\n */\n public function close(): void\n {\n $this->buffer = [];\n $this->connection = null;\n }\n\n /**\n * {@inheritDoc}\n */\n public function read(int $length): string|false\n {\n if (! $this->opened()) {\n return false;\n }\n\n if ($this->meta['eof'] && empty($this->buffer)) {\n return false; // EOF and no data left. Indicate end of stream.\n }\n\n $data = implode('', $this->buffer);\n\n $availableLength = strlen($data);\n\n if ($availableLength === 0) {\n // No data available right now (but not EOF).\n // Simulate non-blocking behavior.\n return '';\n }\n\n $bytesToRead = min($length, $availableLength);\n\n $result = substr($data, 0, $bytesToRead);\n\n $remainingData = substr($data, $bytesToRead);\n\n $this->buffer = $remainingData !== '' ? [$remainingData] : [];\n\n return $result;\n }\n\n /**\n * {@inheritDoc}\n */\n public function fgets(): string|false\n {\n if (! $this->opened()) {\n return false;\n }\n\n // Simulate timeout/eof checks.\n if ($this->meta['timed_out'] || $this->meta['eof']) {\n return false;\n }\n\n return array_shift($this->buffer) ?? false;\n }\n\n /**\n * {@inheritDoc}\n */\n public function fwrite(string $data): int|false\n {\n if (! $this->opened()) {\n return false;\n }\n\n $this->written[] = $data;\n\n return strlen($data);\n }\n\n /**\n * {@inheritDoc}\n */\n public function meta(): array\n {\n return $this->meta;\n }\n\n /**\n * {@inheritDoc}\n */\n public function opened(): bool\n {\n return (bool) $this->connection;\n }\n\n /**\n * {@inheritDoc}\n */\n public function setTimeout(int $seconds): bool\n {\n return true;\n }\n\n /**\n * {@inheritDoc}\n */\n public function setSocketSetCrypto(bool $enabled, ?int $method): bool|int\n {\n return true;\n }\n\n /**\n * Assert that the given data was written to the stream.\n */\n public function assertWritten(string $string): void\n {\n $found = false;\n\n foreach ($this->written as $index => $written) {\n if (str_contains($written, $string)) {\n unset($this->written[$index]);\n\n $found = true;\n\n break;\n }\n }\n\n Assert::assertTrue($found, \"Failed asserting that the string '{$string}' was written to the stream.\");\n }\n}\n"], ["/ImapEngine/src/Connection/ImapQueryBuilder.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection;\n\nuse BackedEnum;\nuse Carbon\\Carbon;\nuse Carbon\\CarbonInterface;\nuse DateTimeInterface;\nuse DirectoryTree\\ImapEngine\\Enums\\ImapSearchKey;\nuse DirectoryTree\\ImapEngine\\Support\\Str;\n\nclass ImapQueryBuilder\n{\n /**\n * The where conditions for the query.\n */\n protected array $wheres = [];\n\n /**\n * The date format to use for date based queries.\n */\n protected string $dateFormat = 'd-M-Y';\n\n /**\n * Add a where \"ALL\" clause to the query.\n */\n public function all(): static\n {\n return $this->where(ImapSearchKey::All);\n }\n\n /**\n * Add a where \"NEW\" clause to the query.\n */\n public function new(): static\n {\n return $this->where(ImapSearchKey::New);\n }\n\n /**\n * Add a where \"OLD\" clause to the query.\n */\n public function old(): static\n {\n return $this->where(ImapSearchKey::Old);\n }\n\n /**\n * Add a where \"SEEN\" clause to the query.\n */\n public function seen(): static\n {\n return $this->where(ImapSearchKey::Seen);\n }\n\n /**\n * Add a where \"DRAFT\" clause to the query.\n */\n public function draft(): static\n {\n return $this->where(ImapSearchKey::Draft);\n }\n\n /**\n * Add a where \"RECENT\" clause to the query.\n */\n public function recent(): static\n {\n return $this->where(ImapSearchKey::Recent);\n }\n\n /**\n * Add a where \"UNSEEN\" clause to the query.\n */\n public function unseen(): static\n {\n return $this->where(ImapSearchKey::Unseen);\n }\n\n /**\n * Add a where \"FLAGGED\" clause to the query.\n */\n public function flagged(): static\n {\n return $this->where(ImapSearchKey::Flagged);\n }\n\n /**\n * Add a where \"DELETED\" clause to the query.\n */\n public function deleted(): static\n {\n return $this->where(ImapSearchKey::Deleted);\n }\n\n /**\n * Add a where \"ANSWERED\" clause to the query.\n */\n public function answered(): static\n {\n return $this->where(ImapSearchKey::Answered);\n }\n\n /**\n * Add a where \"UNDELETED\" clause to the query.\n */\n public function undeleted(): static\n {\n return $this->where(ImapSearchKey::Undeleted);\n }\n\n /**\n * Add a where \"UNFLAGGED\" clause to the query.\n */\n public function unflagged(): static\n {\n return $this->where(ImapSearchKey::Unflagged);\n }\n\n /**\n * Add a where \"UNANSWERED\" clause to the query.\n */\n public function unanswered(): static\n {\n return $this->where(ImapSearchKey::Unanswered);\n }\n\n /**\n * Add a where \"FROM\" clause to the query.\n */\n public function from(string $email): static\n {\n return $this->where(ImapSearchKey::From, $email);\n }\n\n /**\n * Add a where \"TO\" clause to the query.\n */\n public function to(string $value): static\n {\n return $this->where(ImapSearchKey::To, $value);\n }\n\n /**\n * Add a where \"CC\" clause to the query.\n */\n public function cc(string $value): static\n {\n return $this->where(ImapSearchKey::Cc, $value);\n }\n\n /**\n * Add a where \"BCC\" clause to the query.\n */\n public function bcc(string $value): static\n {\n return $this->where(ImapSearchKey::Bcc, $value);\n }\n\n /**\n * Add a where \"BODY\" clause to the query.\n */\n public function body(string $value): static\n {\n return $this->where(ImapSearchKey::Body, $value);\n }\n\n /**\n * Add a where \"KEYWORD\" clause to the query.\n */\n public function keyword(string $value): static\n {\n return $this->where(ImapSearchKey::Keyword, $value);\n }\n\n /**\n * Add a where \"ON\" clause to the query.\n */\n public function on(mixed $date): static\n {\n return $this->where(ImapSearchKey::On, new RawQueryValue(\n $this->parseDate($date)->format($this->dateFormat)\n ));\n }\n\n /**\n * Add a where \"SINCE\" clause to the query.\n */\n public function since(mixed $date): static\n {\n return $this->where(ImapSearchKey::Since, new RawQueryValue(\n $this->parseDate($date)->format($this->dateFormat)\n ));\n }\n\n /**\n * Add a where \"BEFORE\" clause to the query.\n */\n public function before(mixed $value): static\n {\n return $this->where(ImapSearchKey::Before, new RawQueryValue(\n $this->parseDate($value)->format($this->dateFormat)\n ));\n }\n\n /**\n * Add a where \"SUBJECT\" clause to the query.\n */\n public function subject(string $value): static\n {\n return $this->where(ImapSearchKey::Subject, $value);\n }\n\n /**\n * Add a where \"TEXT\" clause to the query.\n */\n public function text(string $value): static\n {\n return $this->where(ImapSearchKey::Text, $value);\n }\n\n /**\n * Add a where \"HEADER\" clause to the query.\n */\n public function header(string $header, string $value): static\n {\n return $this->where(ImapSearchKey::Header->value.\" $header\", $value);\n }\n\n /**\n * Add a where \"UID\" clause to the query.\n */\n public function uid(int|string|array $uid): static\n {\n return $this->where(ImapSearchKey::Uid, new RawQueryValue(\n Str::set(array_map('intval', (array) $uid))\n ));\n }\n\n /**\n * Add a \"where\" condition.\n */\n public function where(mixed $column, mixed $value = null): static\n {\n if (is_callable($column)) {\n $this->addNestedCondition('AND', $column);\n } else {\n $this->addBasicCondition('AND', $column, $value);\n }\n\n return $this;\n }\n\n /**\n * Add an \"or where\" condition.\n */\n public function orWhere(mixed $column, mixed $value = null): static\n {\n if (is_callable($column)) {\n $this->addNestedCondition('OR', $column);\n } else {\n $this->addBasicCondition('OR', $column, $value);\n }\n\n return $this;\n }\n\n /**\n * Add a \"where not\" condition.\n */\n public function whereNot(mixed $column, mixed $value = null): static\n {\n $this->addBasicCondition('AND', $column, $value, true);\n\n return $this;\n }\n\n /**\n * Determine if the query has any where conditions.\n */\n public function isEmpty(): bool\n {\n return empty($this->wheres);\n }\n\n /**\n * Transform the instance into an IMAP-compatible query string.\n */\n public function toImap(): string\n {\n return $this->compileWheres($this->wheres);\n }\n\n /**\n * Create a new query instance (like Eloquent's newQuery).\n */\n protected function newQuery(): static\n {\n return new static;\n }\n\n /**\n * Add a basic condition to the query.\n */\n protected function addBasicCondition(string $boolean, mixed $column, mixed $value, bool $not = false): void\n {\n $value = $this->prepareWhereValue($value);\n\n $column = Str::enum($column);\n\n $this->wheres[] = [\n 'type' => 'basic',\n 'not' => $not,\n 'key' => $column,\n 'value' => $value,\n 'boolean' => $boolean,\n ];\n }\n\n /**\n * Prepare the where value, escaping it as needed.\n */\n protected function prepareWhereValue(mixed $value): RawQueryValue|string|null\n {\n if (is_null($value)) {\n return null;\n }\n\n if ($value instanceof RawQueryValue) {\n return $value;\n }\n\n if ($value instanceof BackedEnum) {\n $value = $value->value;\n }\n\n if ($value instanceof DateTimeInterface) {\n $value = Carbon::instance($value);\n }\n\n if ($value instanceof CarbonInterface) {\n $value = $value->format($this->dateFormat);\n }\n\n return Str::escape($value);\n }\n\n /**\n * Add a nested condition group to the query.\n */\n protected function addNestedCondition(string $boolean, callable $callback): void\n {\n $nested = $this->newQuery();\n\n $callback($nested);\n\n $this->wheres[] = [\n 'type' => 'nested',\n 'query' => $nested,\n 'boolean' => $boolean,\n ];\n }\n\n /**\n * Attempt to parse a date string into a Carbon instance.\n */\n protected function parseDate(mixed $date): CarbonInterface\n {\n if ($date instanceof CarbonInterface) {\n return $date;\n }\n\n return Carbon::parse($date);\n }\n\n /**\n * Build a single expression node from a basic or nested where.\n */\n protected function makeExpressionNode(array $where): array\n {\n return match ($where['type']) {\n 'basic' => [\n 'expr' => $this->compileBasic($where),\n 'boolean' => $where['boolean'],\n ],\n\n 'nested' => [\n 'expr' => $where['query']->toImap(),\n 'boolean' => $where['boolean'],\n ]\n };\n }\n\n /**\n * Merge the existing expression with the next expression, respecting the boolean operator.\n */\n protected function mergeExpressions(string $existing, string $next, string $boolean): string\n {\n return match ($boolean) {\n // AND is implicit – just append.\n 'AND' => $existing.' '.$next,\n\n // IMAP's OR is binary; nest accordingly.\n 'OR' => 'OR ('.$existing.') ('.$next.')',\n };\n }\n\n /**\n * Recursively compile the wheres array into an IMAP-compatible string.\n */\n protected function compileWheres(array $wheres): string\n {\n if (empty($wheres)) {\n return '';\n }\n\n // Convert each \"where\" into a node for later merging.\n $exprNodes = array_map(fn (array $where) => (\n $this->makeExpressionNode($where)\n ), $wheres);\n\n // Start with the first expression.\n $combined = array_shift($exprNodes)['expr'];\n\n // Merge the rest of the expressions.\n foreach ($exprNodes as $node) {\n $combined = $this->mergeExpressions(\n $combined, $node['expr'], $node['boolean']\n );\n }\n\n return trim($combined);\n }\n\n /**\n * Compile a basic where condition into an IMAP-compatible string.\n */\n protected function compileBasic(array $where): string\n {\n $part = strtoupper($where['key']);\n\n if ($where['value'] instanceof RawQueryValue) {\n $part .= ' '.$where['value']->value;\n } elseif ($where['value']) {\n $part .= ' \"'.Str::toImapUtf7($where['value']).'\"';\n }\n\n if ($where['not']) {\n $part = 'NOT '.$part;\n }\n\n return $part;\n }\n}\n"], ["/ImapEngine/src/Connection/ImapTokenizer.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection;\n\nuse DirectoryTree\\ImapEngine\\Connection\\Streams\\StreamInterface;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\Atom;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\Crlf;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\EmailAddress;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\ListClose;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\ListOpen;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\Literal;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\QuotedString;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\ResponseCodeClose;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\ResponseCodeOpen;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\Token;\nuse DirectoryTree\\ImapEngine\\Exceptions\\ImapParserException;\nuse DirectoryTree\\ImapEngine\\Exceptions\\ImapStreamException;\n\nclass ImapTokenizer\n{\n /**\n * The current position in the buffer.\n */\n protected int $position = 0;\n\n /**\n * The buffer of characters read from the stream.\n */\n protected string $buffer = '';\n\n /**\n * Constructor.\n */\n public function __construct(\n protected StreamInterface $stream\n ) {}\n\n /**\n * Returns the next token from the stream.\n */\n public function nextToken(): ?Token\n {\n $this->skipWhitespace();\n\n $this->ensureBuffer(1);\n\n $char = $this->currentChar();\n\n if ($char === null || $char === '') {\n return null;\n }\n\n // Check for line feed.\n if ($char === \"\\n\") {\n // With a valid IMAP response, we should never reach this point,\n // but in case we receive a malformed response, we will flush\n // the buffer and return null to prevent an infinite loop.\n $this->flushBuffer();\n\n return null;\n }\n\n // Check for carriage return. (\\r\\n)\n if ($char === \"\\r\") {\n $this->advance(); // Consume CR\n\n $this->ensureBuffer(1);\n\n if ($this->currentChar() !== \"\\n\") {\n throw new ImapParserException('Expected LF after CR');\n }\n\n $this->advance(); // Consume LF (\\n)\n\n return new Crlf(\"\\r\\n\");\n }\n\n // Check for parameter list opening.\n if ($char === '(') {\n $this->advance();\n\n return new ListOpen('(');\n }\n\n // Check for a parameter list closing.\n if ($char === ')') {\n $this->advance();\n\n return new ListClose(')');\n }\n\n // Check for a response group open.\n if ($char === '[') {\n $this->advance();\n\n return new ResponseCodeOpen('[');\n }\n\n // Check for response group close.\n if ($char === ']') {\n $this->advance();\n\n return new ResponseCodeClose(']');\n }\n\n // Check for angle bracket open (email addresses).\n if ($char === '<') {\n $this->advance();\n\n return $this->readEmailAddress();\n }\n\n // Check for quoted string.\n if ($char === '\"') {\n return $this->readQuotedString();\n }\n\n // Check for literal block open.\n if ($char === '{') {\n return $this->readLiteral();\n }\n\n // Otherwise, parse an atom.\n return $this->readAtom();\n }\n\n /**\n * Skips whitespace characters (spaces and tabs only, preserving CRLF).\n */\n protected function skipWhitespace(): void\n {\n while (true) {\n $this->ensureBuffer(1);\n\n $char = $this->currentChar();\n\n // Break on EOF.\n if ($char === null || $char === '') {\n break;\n }\n\n // Break on CRLF.\n if ($char === \"\\r\" || $char === \"\\n\") {\n break;\n }\n\n // Break on non-whitespace.\n if ($char !== ' ' && $char !== \"\\t\") {\n break;\n }\n\n $this->advance();\n }\n }\n\n /**\n * Reads a quoted string token.\n *\n * Quoted strings are enclosed in double quotes and may contain escaped characters.\n */\n protected function readQuotedString(): QuotedString\n {\n // Skip the opening quote.\n $this->advance();\n\n $value = '';\n\n while (true) {\n $this->ensureBuffer(1);\n\n $char = $this->currentChar();\n\n if ($char === null) {\n throw new ImapParserException(sprintf(\n 'Unterminated quoted string at buffer offset %d. Buffer: \"%s\"',\n $this->position,\n substr($this->buffer, max(0, $this->position - 10), 20)\n ));\n }\n\n if ($char === '\\\\') {\n $this->advance(); // Skip the backslash.\n\n $this->ensureBuffer(1);\n\n $escapedChar = $this->currentChar();\n\n if ($escapedChar === null) {\n throw new ImapParserException('Unterminated escape sequence in quoted string');\n }\n\n $value .= $escapedChar;\n\n $this->advance();\n\n continue;\n }\n\n if ($char === '\"') {\n $this->advance(); // Skip the closing quote.\n\n break;\n }\n\n $value .= $char;\n\n $this->advance();\n }\n\n return new QuotedString($value);\n }\n\n /**\n * Reads a literal token.\n *\n * Literal blocks in IMAP have the form {<length>}\\r\\n<data>.\n */\n protected function readLiteral(): Literal\n {\n // Skip the opening '{'.\n $this->advance();\n\n // This will contain the size of the literal block in a sequence of digits.\n // {<size>}\\r\\n<data>\n $numStr = '';\n\n while (true) {\n $this->ensureBuffer(1);\n\n $char = $this->currentChar();\n\n if ($char === null) {\n throw new ImapParserException('Unterminated literal specifier');\n }\n\n if ($char === '}') {\n $this->advance(); // Skip the '}'.\n\n break;\n }\n\n $numStr .= $char;\n\n $this->advance();\n }\n\n // Expect carriage return after the literal specifier.\n $this->ensureBuffer(2);\n\n // Get the carriage return.\n $crlf = substr($this->buffer, $this->position, 2);\n\n if ($crlf !== \"\\r\\n\") {\n throw new ImapParserException('Expected CRLF after literal specifier');\n }\n\n // Skip the CRLF.\n $this->advance(2);\n\n $length = (int) $numStr;\n\n // Use any data that is already in our buffer.\n $available = strlen($this->buffer) - $this->position;\n\n if ($available >= $length) {\n $literal = substr($this->buffer, $this->position, $length);\n\n $this->advance($length);\n } else {\n // Consume whatever is available without flushing the whole buffer.\n $literal = substr($this->buffer, $this->position);\n\n $consumed = strlen($literal);\n\n // Advance the pointer by the number of bytes we took.\n $this->advance($consumed);\n\n // Calculate how many bytes are still needed.\n $remaining = $length - $consumed;\n\n // Read the missing bytes from the stream.\n $data = $this->stream->read($remaining);\n\n if ($data === false || strlen($data) !== $remaining) {\n throw new ImapStreamException('Unexpected end of stream while trying to fill the buffer');\n }\n\n $literal .= $data;\n }\n\n // Verify that the literal length matches the expected length.\n if (strlen($literal) !== $length) {\n throw new ImapParserException(sprintf(\n 'Literal length mismatch: expected %d, got %d',\n $length,\n strlen($literal)\n ));\n }\n\n return new Literal($literal);\n }\n\n /**\n * Reads an atom token.\n *\n * ATOMs are sequences of printable ASCII characters that do not contain delimiters.\n */\n protected function readAtom(): Atom\n {\n $value = '';\n\n while (true) {\n $this->ensureBuffer(1);\n $char = $this->currentChar();\n\n if ($char === null) {\n break;\n }\n\n if (! $this->isValidAtomCharacter($char)) {\n break;\n }\n\n // Append the character to the value.\n $value .= $char;\n\n $this->advance();\n }\n\n return new Atom($value);\n }\n\n /**\n * Reads an email address token enclosed in angle brackets.\n *\n * Email addresses are enclosed in angle brackets (\"<\" and \">\").\n *\n * For example \"<johndoe@email.com>\"\n */\n protected function readEmailAddress(): ?EmailAddress\n {\n $value = '';\n\n while (true) {\n $this->ensureBuffer(1);\n\n $char = $this->currentChar();\n\n if ($char === null) {\n throw new ImapParserException('Unterminated email address, expected \">\"');\n }\n\n if ($char === '>') {\n $this->advance(); // Skip the closing '>'.\n\n break;\n }\n\n $value .= $char;\n\n $this->advance();\n }\n\n return new EmailAddress($value);\n }\n\n /**\n * Ensures that at least the given length in characters are available in the buffer.\n */\n protected function ensureBuffer(int $length): void\n {\n // If we have enough data in the buffer, return early.\n while ((strlen($this->buffer) - $this->position) < $length) {\n $data = $this->stream->fgets();\n\n if ($data === false) {\n return;\n }\n\n $this->buffer .= $data;\n }\n }\n\n /**\n * Returns the current character in the buffer.\n */\n protected function currentChar(): ?string\n {\n return $this->buffer[$this->position] ?? null;\n }\n\n /**\n * Advances the internal pointer by $n characters.\n */\n protected function advance(int $n = 1): void\n {\n $this->position += $n;\n\n // If we have consumed the entire buffer, reset it.\n if ($this->position >= strlen($this->buffer)) {\n $this->flushBuffer();\n }\n }\n\n /**\n * Flush the buffer and reset the position.\n */\n protected function flushBuffer(): void\n {\n $this->buffer = '';\n $this->position = 0;\n }\n\n /**\n * Determine if the given character is a valid atom character.\n */\n protected function isValidAtomCharacter(string $char): bool\n {\n // Get the ASCII code.\n $code = ord($char);\n\n // Allow only printable ASCII (32-126).\n if ($code < 32 || $code > 126) {\n return false;\n }\n\n // Delimiters are not allowed inside ATOMs.\n if ($this->isDelimiter($char)) {\n return false;\n }\n\n return true;\n }\n\n /**\n * Determine if the given character is a delimiter for tokenizing responses.\n */\n protected function isDelimiter(string $char): bool\n {\n // This delimiter list includes additional characters (such as square\n // brackets, curly braces, and angle brackets) to ensure that tokens\n // like the response code group brackets are split out. This is fine\n // for tokenizing responses, even though it’s more restrictive\n // than the IMAP atom definition in RFC 3501 (section 9).\n return in_array($char, [' ', '(', ')', '[', ']', '{', '}', '<', '>'], true);\n }\n}\n"], ["/ImapEngine/src/Connection/Streams/ImapStream.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Streams;\n\nuse DirectoryTree\\ImapEngine\\Exceptions\\ImapConnectionFailedException;\n\nclass ImapStream implements StreamInterface\n{\n /**\n * The underlying PHP stream resource.\n *\n * @var resource|null\n */\n protected mixed $stream = null;\n\n /**\n * {@inheritDoc}\n */\n public function open(string $transport, string $host, int $port, int $timeout, array $options = []): bool\n {\n $this->stream = stream_socket_client(\n \"{$transport}://{$host}:{$port}\",\n $errno,\n $errstr,\n $timeout,\n STREAM_CLIENT_CONNECT,\n stream_context_create($options)\n );\n\n if (! $this->stream) {\n throw new ImapConnectionFailedException('Stream failed to open: '.$errstr, $errno);\n }\n\n return true;\n }\n\n /**\n * {@inheritDoc}\n */\n public function close(): void\n {\n if ($this->opened()) {\n fclose($this->stream);\n }\n\n $this->stream = null;\n }\n\n /**\n * {@inheritDoc}\n */\n public function read(int $length): string|false\n {\n if (! $this->opened()) {\n return false;\n }\n\n $data = '';\n\n while (strlen($data) < $length && ! feof($this->stream)) {\n $chunk = fread($this->stream, $length - strlen($data));\n\n if ($chunk === false) {\n return false;\n }\n\n $data .= $chunk;\n }\n\n return $data;\n }\n\n /**\n * {@inheritDoc}\n */\n public function fgets(): string|false\n {\n return $this->opened() ? fgets($this->stream) : false;\n }\n\n /**\n * {@inheritDoc}\n */\n public function fwrite(string $data): int|false\n {\n return $this->opened() ? fwrite($this->stream, $data) : false;\n }\n\n /**\n * {@inheritDoc}\n */\n public function meta(): array\n {\n return $this->opened() ? stream_get_meta_data($this->stream) : [];\n }\n\n /**\n * {@inheritDoc}\n */\n public function opened(): bool\n {\n return is_resource($this->stream);\n }\n\n /**\n * {@inheritDoc}\n */\n public function setTimeout(int $seconds): bool\n {\n return stream_set_timeout($this->stream, $seconds);\n }\n\n /**\n * {@inheritDoc}\n */\n public function setSocketSetCrypto(bool $enabled, ?int $method): bool|int\n {\n return stream_socket_enable_crypto($this->stream, $enabled, $method);\n }\n}\n"], ["/ImapEngine/src/Mbox.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\nuse DirectoryTree\\ImapEngine\\Exceptions\\RuntimeException;\nuse Generator;\n\nclass Mbox\n{\n /**\n * Constructor.\n */\n public function __construct(\n protected string $filepath\n ) {}\n\n /**\n * Get the messages from the mbox file.\n */\n public function messages(\n string $delimiter = '/^From\\s+\\S+\\s+' // From\n .'(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\\s+' // Day\n .'(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s+' // Month\n .'\\d{1,2}\\s+\\d{2}:\\d{2}:\\d{2}' // Time (HH:MM:SS)\n .'(?:\\s+[+-]\\d{4})?' // Optional Timezone (\"+0000\")\n .'\\s+\\d{4}/' // Year\n ): Generator {\n if (! $handle = fopen($this->filepath, 'r')) {\n throw new RuntimeException('Failed to open mbox file: '.$this->filepath);\n }\n\n $buffer = '';\n\n while (($line = fgets($handle)) !== false) {\n if (preg_match($delimiter, $line) && $buffer !== '') {\n yield new FileMessage($buffer);\n\n $buffer = '';\n }\n\n $buffer .= $line;\n }\n\n if ($buffer !== '') {\n yield new FileMessage($buffer);\n }\n\n fclose($handle);\n }\n}\n"], ["/ImapEngine/src/Idle.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\nuse Carbon\\Carbon;\nuse Carbon\\CarbonInterface;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\UntaggedResponse;\nuse DirectoryTree\\ImapEngine\\Exceptions\\Exception;\nuse DirectoryTree\\ImapEngine\\Exceptions\\ImapConnectionClosedException;\nuse DirectoryTree\\ImapEngine\\Exceptions\\ImapConnectionTimedOutException;\nuse Generator;\n\nclass Idle\n{\n /**\n * Constructor.\n */\n public function __construct(\n protected Mailbox $mailbox,\n protected string $folder,\n protected int $timeout,\n ) {}\n\n /**\n * Destructor.\n */\n public function __destruct()\n {\n $this->disconnect();\n }\n\n /**\n * Await new messages on the connection.\n */\n public function await(callable $callback): void\n {\n $this->connect();\n\n // Loop indefinitely, restarting IDLE sessions as needed.\n while (true) {\n $ttl = $this->getNextTimeout();\n\n try {\n $this->listen($callback, $ttl);\n } catch (ImapConnectionTimedOutException) {\n $this->restart();\n } catch (ImapConnectionClosedException) {\n $this->reconnect();\n }\n }\n }\n\n /**\n * Start listening for new messages using the idle() generator.\n */\n protected function listen(callable $callback, CarbonInterface $ttl): void\n {\n // Iterate over responses yielded by the idle generator.\n foreach ($this->idle() as $response) {\n if (! $response instanceof UntaggedResponse) {\n continue;\n }\n\n if ($response->tokenAt(2)?->is('EXISTS')) {\n $msgn = (int) $response->tokenAt(1)->value;\n\n $callback($msgn);\n\n $ttl = $this->getNextTimeout();\n }\n\n // If we've been idle too long, break out to restart the session.\n if (Carbon::now()->greaterThanOrEqualTo($ttl)) {\n $this->restart();\n\n break;\n }\n }\n }\n\n /**\n * Get the folder to idle.\n */\n protected function folder(): FolderInterface\n {\n return $this->mailbox->folders()->findOrFail($this->folder);\n }\n\n /**\n * Issue a done command and restart the idle session.\n */\n protected function restart(): void\n {\n try {\n // Send DONE to terminate the current IDLE session gracefully.\n $this->done();\n } catch (Exception) {\n $this->reconnect();\n }\n }\n\n /**\n * Reconnect the client and restart the idle session.\n */\n protected function reconnect(): void\n {\n $this->mailbox->disconnect();\n\n $this->connect();\n }\n\n /**\n * Connect the client and select the folder to idle.\n */\n protected function connect(): void\n {\n $this->mailbox->connect();\n\n $this->mailbox->select($this->folder(), true);\n }\n\n /**\n * Disconnect the client.\n */\n protected function disconnect(): void\n {\n try {\n // Attempt to terminate IDLE gracefully.\n $this->done();\n } catch (Exception) {\n // Do nothing.\n }\n\n $this->mailbox->disconnect();\n }\n\n /**\n * End the current IDLE session.\n */\n protected function done(): void\n {\n $this->mailbox->connection()->done();\n }\n\n /**\n * Begin a new IDLE session as a generator.\n */\n protected function idle(): Generator\n {\n yield from $this->mailbox->connection()->idle($this->timeout);\n }\n\n /**\n * Get the next timeout as a Carbon instance.\n */\n protected function getNextTimeout(): CarbonInterface\n {\n return Carbon::now()->addSeconds($this->timeout);\n }\n}\n"], ["/ImapEngine/src/Message.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\MessageResponseParser;\nuse DirectoryTree\\ImapEngine\\Exceptions\\ImapCapabilityException;\nuse DirectoryTree\\ImapEngine\\Support\\Str;\nuse Illuminate\\Contracts\\Support\\Arrayable;\nuse JsonSerializable;\n\nclass Message implements Arrayable, JsonSerializable, MessageInterface\n{\n use HasFlags, HasParsedMessage;\n\n /**\n * Constructor.\n */\n public function __construct(\n protected FolderInterface $folder,\n protected int $uid,\n protected array $flags,\n protected string $head,\n protected string $body,\n ) {}\n\n /**\n * Get the names of properties that should be serialized.\n */\n public function __sleep(): array\n {\n // We don't want to serialize the parsed message.\n return ['folder', 'uid', 'flags', 'headers', 'contents'];\n }\n\n /**\n * Get the message's folder.\n */\n public function folder(): FolderInterface\n {\n return $this->folder;\n }\n\n /**\n * Get the message's identifier.\n */\n public function uid(): int\n {\n return $this->uid;\n }\n\n /**\n * Get the message's flags.\n */\n public function flags(): array\n {\n return $this->flags;\n }\n\n /**\n * Get the message's raw headers.\n */\n public function head(): string\n {\n return $this->head;\n }\n\n /**\n * Determine if the message has headers.\n */\n public function hasHead(): bool\n {\n return ! empty($this->head);\n }\n\n /**\n * Get the message's raw body.\n */\n public function body(): string\n {\n return $this->body;\n }\n\n /**\n * Determine if the message has contents.\n */\n public function hasBody(): bool\n {\n return ! empty($this->body);\n }\n\n /**\n * {@inheritDoc}\n */\n public function is(MessageInterface $message): bool\n {\n return $message instanceof self\n && $this->uid === $message->uid\n && $this->head === $message->head\n && $this->body === $message->body\n && $this->folder->is($message->folder);\n }\n\n /**\n * Add or remove a flag from the message.\n */\n public function flag(mixed $flag, string $operation, bool $expunge = false): void\n {\n $flag = Str::enum($flag);\n\n $this->folder->mailbox()\n ->connection()\n ->store($flag, $this->uid, mode: $operation);\n\n if ($expunge) {\n $this->folder->expunge();\n }\n\n $this->flags = match ($operation) {\n '+' => array_unique(array_merge($this->flags, [$flag])),\n '-' => array_diff($this->flags, [$flag]),\n };\n }\n\n /**\n * Copy the message to the given folder.\n */\n public function copy(string $folder): ?int\n {\n $mailbox = $this->folder->mailbox();\n\n $capabilities = $mailbox->capabilities();\n\n if (! in_array('UIDPLUS', $capabilities)) {\n throw new ImapCapabilityException(\n 'Unable to copy message. IMAP server does not support UIDPLUS capability'\n );\n }\n\n $response = $mailbox->connection()->copy($folder, $this->uid);\n\n return MessageResponseParser::getUidFromCopy($response);\n }\n\n /**\n * Move the message to the given folder.\n *\n * @throws ImapCapabilityException\n */\n public function move(string $folder, bool $expunge = false): ?int\n {\n $mailbox = $this->folder->mailbox();\n\n $capabilities = $mailbox->capabilities();\n\n switch (true) {\n case in_array('MOVE', $capabilities):\n $response = $mailbox->connection()->move($folder, $this->uid);\n\n if ($expunge) {\n $this->folder->expunge();\n }\n\n return MessageResponseParser::getUidFromCopy($response);\n\n case in_array('UIDPLUS', $capabilities):\n $uid = $this->copy($folder);\n\n $this->delete($expunge);\n\n return $uid;\n\n default:\n throw new ImapCapabilityException(\n 'Unable to move message. IMAP server does not support MOVE or UIDPLUS capabilities'\n );\n }\n }\n\n /**\n * Delete the message.\n */\n public function delete(bool $expunge = false): void\n {\n $this->markDeleted($expunge);\n }\n\n /**\n * Restore the message.\n */\n public function restore(): void\n {\n $this->unmarkDeleted();\n }\n\n /**\n * Get the array representation of the message.\n */\n public function toArray(): array\n {\n return [\n 'uid' => $this->uid,\n 'flags' => $this->flags,\n 'head' => $this->head,\n 'body' => $this->body,\n ];\n }\n\n /**\n * Get the string representation of the message.\n */\n public function __toString(): string\n {\n return implode(\"\\r\\n\\r\\n\", array_filter([\n rtrim($this->head),\n ltrim($this->body),\n ]));\n }\n\n /**\n * Get the JSON representation of the message.\n */\n public function jsonSerialize(): array\n {\n return $this->toArray();\n }\n\n /**\n * Determine if the message is empty.\n */\n protected function isEmpty(): bool\n {\n return ! $this->hasHead() && ! $this->hasBody();\n }\n}\n"], ["/ImapEngine/src/Folder.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\nuse DirectoryTree\\ImapEngine\\Connection\\ImapQueryBuilder;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\UntaggedResponse;\nuse DirectoryTree\\ImapEngine\\Enums\\ImapFetchIdentifier;\nuse DirectoryTree\\ImapEngine\\Exceptions\\Exception;\nuse DirectoryTree\\ImapEngine\\Exceptions\\ImapCapabilityException;\nuse DirectoryTree\\ImapEngine\\Support\\Str;\nuse Illuminate\\Contracts\\Support\\Arrayable;\nuse Illuminate\\Support\\ItemNotFoundException;\nuse JsonSerializable;\n\nclass Folder implements Arrayable, FolderInterface, JsonSerializable\n{\n use ComparesFolders;\n\n /**\n * Constructor.\n */\n public function __construct(\n protected Mailbox $mailbox,\n protected string $path,\n protected array $flags = [],\n protected string $delimiter = '/',\n ) {}\n\n /**\n * Get the folder's mailbox.\n */\n public function mailbox(): Mailbox\n {\n return $this->mailbox;\n }\n\n /**\n * Get the folder path.\n */\n public function path(): string\n {\n return $this->path;\n }\n\n /**\n * Get the folder flags.\n *\n * @return string[]\n */\n public function flags(): array\n {\n return $this->flags;\n }\n\n /**\n * {@inheritDoc}\n */\n public function delimiter(): string\n {\n return $this->delimiter;\n }\n\n /**\n * {@inheritDoc}\n */\n public function name(): string\n {\n return Str::fromImapUtf7(\n last(explode($this->delimiter, $this->path))\n );\n }\n\n /**\n * {@inheritDoc}\n */\n public function is(FolderInterface $folder): bool\n {\n return $this->isSameFolder($this, $folder);\n }\n\n /**\n * {@inheritDoc}\n */\n public function messages(): MessageQuery\n {\n // Ensure the folder is selected.\n $this->select(true);\n\n return new MessageQuery($this, new ImapQueryBuilder);\n }\n\n /**\n * {@inheritDoc}\n */\n public function idle(callable $callback, ?callable $query = null, int $timeout = 300): void\n {\n if (! in_array('IDLE', $this->mailbox->capabilities())) {\n throw new ImapCapabilityException('Unable to IDLE. IMAP server does not support IDLE capability.');\n }\n\n // The message query to use when fetching messages.\n $query ??= fn (MessageQuery $query) => $query;\n\n // Fetch the message by message number.\n $fetch = fn (int $msgn) => (\n $query($this->messages())->findOrFail($msgn, ImapFetchIdentifier::MessageNumber)\n );\n\n (new Idle(clone $this->mailbox, $this->path, $timeout))->await(\n function (int $msgn) use ($callback, $fetch) {\n if (! $this->mailbox->connected()) {\n $this->mailbox->connect();\n }\n\n try {\n $message = $fetch($msgn);\n } catch (ItemNotFoundException) {\n // The message wasn't found. We will skip\n // it and continue awaiting new messages.\n return;\n } catch (Exception) {\n // Something else happened. We will attempt\n // reconnecting and re-fetching the message.\n $this->mailbox->reconnect();\n\n $message = $fetch($msgn);\n }\n\n $callback($message);\n }\n );\n }\n\n /**\n * {@inheritDoc}\n */\n public function move(string $newPath): void\n {\n $this->mailbox->connection()->rename($this->path, $newPath);\n\n $this->path = $newPath;\n }\n\n /**\n * {@inheritDoc}\n */\n public function select(bool $force = false): void\n {\n $this->mailbox->select($this, $force);\n }\n\n /**\n * {@inheritDoc}\n */\n public function status(): array\n {\n $response = $this->mailbox->connection()->status($this->path);\n\n $tokens = $response->tokenAt(3)->tokens();\n\n $values = [];\n\n // Tokens are expected to alternate between keys and values.\n for ($i = 0; $i < count($tokens); $i += 2) {\n $values[$tokens[$i]->value] = $tokens[$i + 1]->value;\n }\n\n return $values;\n }\n\n /**\n * {@inheritDoc}\n */\n public function examine(): array\n {\n return $this->mailbox->connection()->examine($this->path)->map(\n fn (UntaggedResponse $response) => $response->toArray()\n )->all();\n }\n\n /**\n * {@inheritDoc}\n */\n public function expunge(): array\n {\n return $this->mailbox->connection()->expunge()->map(\n fn (UntaggedResponse $response) => $response->tokenAt(1)->value\n )->all();\n }\n\n /**\n * {@inheritDoc}\n */\n public function delete(): void\n {\n $this->mailbox->connection()->delete($this->path);\n }\n\n /**\n * Get the array representation of the folder.\n */\n public function toArray(): array\n {\n return [\n 'path' => $this->path,\n 'flags' => $this->flags,\n 'delimiter' => $this->delimiter,\n ];\n }\n\n /**\n * Get the JSON representation of the folder.\n */\n public function jsonSerialize(): array\n {\n return $this->toArray();\n }\n}\n"], ["/ImapEngine/src/HasParsedMessage.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\nuse Carbon\\Carbon;\nuse Carbon\\CarbonInterface;\nuse DirectoryTree\\ImapEngine\\Exceptions\\RuntimeException;\nuse GuzzleHttp\\Psr7\\Utils;\nuse ZBateson\\MailMimeParser\\Header\\HeaderConsts;\nuse ZBateson\\MailMimeParser\\Header\\IHeader;\nuse ZBateson\\MailMimeParser\\Header\\IHeaderPart;\nuse ZBateson\\MailMimeParser\\Header\\Part\\AddressPart;\nuse ZBateson\\MailMimeParser\\Header\\Part\\ContainerPart;\nuse ZBateson\\MailMimeParser\\Header\\Part\\NameValuePart;\nuse ZBateson\\MailMimeParser\\Message as MailMimeMessage;\n\ntrait HasParsedMessage\n{\n /**\n * The parsed message.\n */\n protected ?MailMimeMessage $parsed = null;\n\n /**\n * Get the message date and time.\n */\n public function date(): ?CarbonInterface\n {\n if ($date = $this->header(HeaderConsts::DATE)?->getDateTime()) {\n return Carbon::instance($date);\n }\n\n return null;\n }\n\n /**\n * Get the message's message-id.\n */\n public function messageId(): ?string\n {\n return $this->header(HeaderConsts::MESSAGE_ID)?->getValue();\n }\n\n /**\n * Get the message's subject.\n */\n public function subject(): ?string\n {\n return $this->header(HeaderConsts::SUBJECT)?->getValue();\n }\n\n /**\n * Get the FROM address.\n */\n public function from(): ?Address\n {\n return head($this->addresses(HeaderConsts::FROM)) ?: null;\n }\n\n /**\n * Get the SENDER address.\n */\n public function sender(): ?Address\n {\n return head($this->addresses(HeaderConsts::SENDER)) ?: null;\n }\n\n /**\n * Get the REPLY-TO address.\n */\n public function replyTo(): ?Address\n {\n return head($this->addresses(HeaderConsts::REPLY_TO)) ?: null;\n }\n\n /**\n * Get the IN-REPLY-TO address.\n */\n public function inReplyTo(): ?Address\n {\n return head($this->addresses(HeaderConsts::IN_REPLY_TO)) ?: null;\n }\n\n /**\n * Get the TO addresses.\n *\n * @return Address[]\n */\n public function to(): array\n {\n return $this->addresses(HeaderConsts::TO);\n }\n\n /**\n * Get the CC addresses.\n *\n * @return Address[]\n */\n public function cc(): array\n {\n return $this->addresses(HeaderConsts::CC);\n }\n\n /**\n * Get the BCC addresses.\n *\n * @return Address[]\n */\n public function bcc(): array\n {\n return $this->addresses(HeaderConsts::BCC);\n }\n\n /**\n * Get the message's attachments.\n *\n * @return Attachment[]\n */\n public function attachments(): array\n {\n $attachments = [];\n\n foreach ($this->parse()->getAllAttachmentParts() as $part) {\n // If the attachment's content type is message/rfc822, we're\n // working with a forwarded message. We will parse the\n // forwarded message and merge in its attachments.\n if (strtolower($part->getContentType()) === 'message/rfc822') {\n $message = new FileMessage($part->getContent());\n\n $attachments = array_merge($attachments, $message->attachments());\n } else {\n $attachments[] = new Attachment(\n $part->getFilename(),\n $part->getContentId(),\n $part->getContentType(),\n $part->getBinaryContentStream() ?? Utils::streamFor(''),\n );\n }\n }\n\n return $attachments;\n }\n\n /**\n * Determine if the message has attachments.\n */\n public function hasAttachments(): bool\n {\n return $this->attachmentCount() > 0;\n }\n\n /**\n * Get the count of attachments.\n */\n public function attachmentCount(): int\n {\n return $this->parse()->getAttachmentCount();\n }\n\n /**\n * Get addresses from the given header.\n *\n * @return Address[]\n */\n public function addresses(string $header): array\n {\n $parts = $this->header($header)?->getParts() ?? [];\n\n $addresses = array_map(fn (IHeaderPart $part) => match (true) {\n $part instanceof AddressPart => new Address($part->getEmail(), $part->getName()),\n $part instanceof NameValuePart => new Address($part->getName(), $part->getValue()),\n $part instanceof ContainerPart => new Address($part->getValue(), ''),\n default => null,\n }, $parts);\n\n return array_filter($addresses);\n }\n\n /**\n * Get the message's HTML content.\n */\n public function html(): ?string\n {\n return $this->parse()->getHtmlContent();\n }\n\n /**\n * Get the message's text content.\n */\n public function text(): ?string\n {\n return $this->parse()->getTextContent();\n }\n\n /**\n * Get all headers from the message.\n */\n public function headers(): array\n {\n return $this->parse()->getAllHeaders();\n }\n\n /**\n * Get a header from the message.\n */\n public function header(string $name, int $offset = 0): ?IHeader\n {\n return $this->parse()->getHeader($name, $offset);\n }\n\n /**\n * Parse the message into a MailMimeMessage instance.\n */\n public function parse(): MailMimeMessage\n {\n if ($this->isEmpty()) {\n throw new RuntimeException('Cannot parse an empty message');\n }\n\n return $this->parsed ??= MessageParser::parse((string) $this);\n }\n\n /**\n * Determine if the message is empty.\n */\n abstract protected function isEmpty(): bool;\n\n /**\n * Get the string representation of the message.\n */\n abstract public function __toString(): string;\n}\n"], ["/ImapEngine/src/Connection/ImapParser.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection;\n\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\ContinuationResponse;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\Data\\Data;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\Data\\ListData;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\Data\\ResponseCodeData;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\Response;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\TaggedResponse;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\UntaggedResponse;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\Atom;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\Crlf;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\ListClose;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\ListOpen;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\ResponseCodeClose;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\ResponseCodeOpen;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\Token;\nuse DirectoryTree\\ImapEngine\\Exceptions\\ImapParserException;\n\nclass ImapParser\n{\n /**\n * The current token being parsed.\n *\n * Expected to be an associative array with keys like \"type\" and \"value\".\n */\n protected ?Token $currentToken = null;\n\n /**\n * Constructor.\n */\n public function __construct(\n protected ImapTokenizer $tokenizer\n ) {}\n\n /**\n * Get the next response from the tokenizer.\n */\n public function next(): Data|Token|Response|null\n {\n // Attempt to load the first token.\n if (! $this->currentToken) {\n $this->advance();\n }\n\n // No token was found, return null.\n if (! $this->currentToken) {\n return null;\n }\n\n // If the token indicates the beginning of a list, parse it.\n if ($this->currentToken instanceof ListOpen) {\n return $this->parseList();\n }\n\n // If the token is an ATOM, check its value for special markers.\n if ($this->currentToken instanceof Atom) {\n // '*' marks an untagged response.\n if ($this->currentToken->value === '*') {\n return $this->parseUntaggedResponse();\n }\n\n // '+' marks a continuation response.\n if ($this->currentToken->value === '+') {\n return $this->parseContinuationResponse();\n }\n\n // If it's an ATOM and not '*' or '+', it's likely a tagged response.\n return $this->parseTaggedResponse();\n }\n\n return $this->parseElement();\n }\n\n /**\n * Parse an untagged response.\n *\n * An untagged response begins with the '*' token. It may contain\n * multiple elements, including lists and response codes.\n */\n protected function parseUntaggedResponse(): UntaggedResponse\n {\n // Capture the initial '*' token.\n $elements[] = clone $this->currentToken;\n\n $this->advance();\n\n // Collect all tokens until the end-of-response marker.\n while ($this->currentToken && ! $this->isEndOfResponseToken($this->currentToken)) {\n $elements[] = $this->parseElement();\n }\n\n // If the end-of-response marker (CRLF) is present, consume it.\n if ($this->currentToken && $this->isEndOfResponseToken($this->currentToken)) {\n $this->currentToken = null;\n } else {\n throw new ImapParserException('Unterminated untagged response');\n }\n\n return new UntaggedResponse($elements);\n }\n\n /**\n * Parse a continuation response.\n *\n * A continuation response starts with a '+' token, indicating\n * that the server expects additional data from the client.\n */\n protected function parseContinuationResponse(): ContinuationResponse\n {\n // Capture the initial '+' token.\n $elements[] = clone $this->currentToken;\n\n $this->advance();\n\n // Collect all tokens until the CRLF marker.\n while ($this->currentToken && ! $this->isEndOfResponseToken($this->currentToken)) {\n $elements[] = $this->parseElement();\n }\n\n // Consume the CRLF marker if present.\n if ($this->currentToken && $this->isEndOfResponseToken($this->currentToken)) {\n $this->currentToken = null;\n } else {\n throw new ImapParserException('Unterminated continuation response');\n }\n\n return new ContinuationResponse($elements);\n }\n\n /**\n * Parse a tagged response.\n *\n * A tagged response begins with a tag (which is not '*' or '+')\n * and is followed by a status and optional data.\n */\n protected function parseTaggedResponse(): TaggedResponse\n {\n // Capture the initial TAG token.\n $tokens[] = clone $this->currentToken;\n\n $this->advance();\n\n // Collect tokens until the end-of-response marker is reached.\n while ($this->currentToken && ! $this->isEndOfResponseToken($this->currentToken)) {\n $tokens[] = $this->parseElement();\n }\n\n // Consume the CRLF marker if present.\n if ($this->currentToken && $this->isEndOfResponseToken($this->currentToken)) {\n $this->currentToken = null;\n } else {\n throw new ImapParserException('Unterminated tagged response');\n }\n\n return new TaggedResponse($tokens);\n }\n\n /**\n * Parses a bracket group of elements delimited by '[' and ']'.\n *\n * Bracket groups are used to represent response codes.\n */\n protected function parseBracketGroup(): ResponseCodeData\n {\n // Consume the opening '[' token.\n $this->advance();\n\n $elements = [];\n\n while (\n $this->currentToken\n && ! $this->currentToken instanceof ResponseCodeClose\n && ! $this->isEndOfResponseToken($this->currentToken)\n ) {\n $elements[] = $this->parseElement();\n }\n\n if ($this->currentToken === null) {\n throw new ImapParserException('Unterminated bracket group in response');\n }\n\n // Consume the closing ']' token.\n $this->advance();\n\n return new ResponseCodeData($elements);\n }\n\n /**\n * Parses a list of elements delimited by '(' and ')'.\n *\n * Lists are handled recursively, as a list may contain nested lists.\n */\n protected function parseList(): ListData\n {\n // Consume the opening '(' token.\n $this->advance();\n\n $elements = [];\n\n // Continue to parse elements until we find the corresponding ')'.\n while (\n $this->currentToken\n && ! $this->currentToken instanceof ListClose\n && ! $this->isEndOfResponseToken($this->currentToken)\n ) {\n $elements[] = $this->parseElement();\n }\n\n // If we reached the end without finding a closing ')', throw an exception.\n if ($this->currentToken === null) {\n throw new ImapParserException('Unterminated list in response');\n }\n\n // Consume the closing ')' token.\n $this->advance();\n\n return new ListData($elements);\n }\n\n /**\n * Parses a single element, which might be a list or a simple token.\n */\n protected function parseElement(): Data|Token|null\n {\n // If there is no current token, return null.\n if ($this->currentToken === null) {\n return null;\n }\n\n // If the token indicates the start of a list, parse it as a list.\n if ($this->currentToken instanceof ListOpen) {\n return $this->parseList();\n }\n\n // If the token indicates the start of a group, parse it as a group.\n if ($this->currentToken instanceof ResponseCodeOpen) {\n return $this->parseBracketGroup();\n }\n\n // Otherwise, capture the current token.\n $token = clone $this->currentToken;\n\n $this->advance();\n\n return $token;\n }\n\n /**\n * Advance to the next token from the tokenizer.\n */\n protected function advance(): void\n {\n $this->currentToken = $this->tokenizer->nextToken();\n }\n\n /**\n * Determine if the given token marks the end of a response.\n */\n protected function isEndOfResponseToken(Token $token): bool\n {\n return $token instanceof Crlf;\n }\n}\n"], ["/ImapEngine/src/Mailbox.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\nuse DirectoryTree\\ImapEngine\\Connection\\ConnectionInterface;\nuse DirectoryTree\\ImapEngine\\Connection\\ImapConnection;\nuse DirectoryTree\\ImapEngine\\Connection\\Loggers\\EchoLogger;\nuse DirectoryTree\\ImapEngine\\Connection\\Loggers\\FileLogger;\nuse DirectoryTree\\ImapEngine\\Connection\\Streams\\ImapStream;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\Atom;\nuse Exception;\n\nclass Mailbox implements MailboxInterface\n{\n /**\n * The mailbox configuration.\n */\n protected array $config = [\n 'port' => 993,\n 'host' => '',\n 'timeout' => 30,\n 'debug' => false,\n 'username' => '',\n 'password' => '',\n 'encryption' => 'ssl',\n 'validate_cert' => true,\n 'authentication' => 'plain',\n 'proxy' => [\n 'socket' => null,\n 'username' => null,\n 'password' => null,\n 'request_fulluri' => false,\n ],\n ];\n\n /**\n * The cached mailbox capabilities.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#section-6.1.1\n */\n protected ?array $capabilities = null;\n\n /**\n * The currently selected folder.\n */\n protected ?FolderInterface $selected = null;\n\n /**\n * The mailbox connection.\n */\n protected ?ConnectionInterface $connection = null;\n\n /**\n * Constructor.\n */\n public function __construct(array $config = [])\n {\n $this->config = array_merge($this->config, $config);\n }\n\n /**\n * Prepare the cloned instance.\n */\n public function __clone(): void\n {\n $this->connection = null;\n }\n\n /**\n * Make a new mailbox instance.\n */\n public static function make(array $config = []): static\n {\n return new static($config);\n }\n\n /**\n * {@inheritDoc}\n */\n public function config(?string $key = null, mixed $default = null): mixed\n {\n if (is_null($key)) {\n return $this->config;\n }\n\n return data_get($this->config, $key, $default);\n }\n\n /**\n * {@inheritDoc}\n */\n public function connection(): ConnectionInterface\n {\n if (! $this->connection) {\n $this->connect();\n }\n\n return $this->connection;\n }\n\n /**\n * {@inheritDoc}\n */\n public function connected(): bool\n {\n return (bool) $this->connection?->connected();\n }\n\n /**\n * {@inheritDoc}\n */\n public function reconnect(): void\n {\n $this->disconnect();\n\n $this->connect();\n }\n\n /**\n * {@inheritDoc}\n */\n public function connect(?ConnectionInterface $connection = null): void\n {\n if ($this->connected()) {\n return;\n }\n\n $debug = $this->config('debug');\n\n $this->connection = $connection ?? new ImapConnection(new ImapStream, match (true) {\n class_exists($debug) => new $debug,\n is_string($debug) => new FileLogger($debug),\n is_bool($debug) && $debug => new EchoLogger,\n default => null,\n });\n\n $this->connection->connect($this->config('host'), $this->config('port'), [\n 'proxy' => $this->config('proxy'),\n 'debug' => $this->config('debug'),\n 'timeout' => $this->config('timeout'),\n 'encryption' => $this->config('encryption'),\n 'validate_cert' => $this->config('validate_cert'),\n ]);\n\n $this->authenticate();\n }\n\n /**\n * Authenticate the current session.\n */\n protected function authenticate(): void\n {\n if ($this->config('authentication') === 'oauth') {\n $this->connection->authenticate(\n $this->config('username'),\n $this->config('password')\n );\n } else {\n $this->connection->login(\n $this->config('username'),\n $this->config('password'),\n );\n }\n }\n\n /**\n * {@inheritDoc}\n */\n public function disconnect(): void\n {\n try {\n $this->connection?->logout();\n $this->connection?->disconnect();\n } catch (Exception) {\n // Do nothing.\n } finally {\n $this->connection = null;\n }\n }\n\n /**\n * {@inheritDoc}\n */\n public function inbox(): FolderInterface\n {\n // \"INBOX\" is a special name reserved for the user's primary mailbox.\n // See: https://datatracker.ietf.org/doc/html/rfc9051#section-5.1\n return $this->folders()->find('INBOX');\n }\n\n /**\n * {@inheritDoc}\n */\n public function folders(): FolderRepositoryInterface\n {\n // Ensure the connection is established.\n $this->connection();\n\n return new FolderRepository($this);\n }\n\n /**\n * {@inheritDoc}\n */\n public function capabilities(): array\n {\n return $this->capabilities ??= array_map(\n fn (Atom $token) => $token->value,\n $this->connection()->capability()->tokensAfter(2)\n );\n }\n\n /**\n * {@inheritDoc}\n */\n public function select(FolderInterface $folder, bool $force = false): void\n {\n if (! $this->selected($folder) || $force) {\n $this->connection()->select($folder->path());\n }\n\n $this->selected = $folder;\n }\n\n /**\n * {@inheritDoc}\n */\n public function selected(FolderInterface $folder): bool\n {\n return $this->selected?->is($folder) ?? false;\n }\n}\n"], ["/ImapEngine/src/Testing/FakeFolderRepository.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Testing;\n\nuse DirectoryTree\\ImapEngine\\Collections\\FolderCollection;\nuse DirectoryTree\\ImapEngine\\FolderInterface;\nuse DirectoryTree\\ImapEngine\\FolderRepositoryInterface;\nuse DirectoryTree\\ImapEngine\\MailboxInterface;\nuse DirectoryTree\\ImapEngine\\Support\\Str;\nuse Illuminate\\Support\\ItemNotFoundException;\n\nclass FakeFolderRepository implements FolderRepositoryInterface\n{\n /**\n * Constructor.\n */\n public function __construct(\n protected MailboxInterface $mailbox,\n /** @var FolderInterface[] */\n protected array $folders = []\n ) {}\n\n /**\n * {@inheritDoc}\n */\n public function find(string $path): ?FolderInterface\n {\n try {\n return $this->findOrFail($path);\n } catch (ItemNotFoundException) {\n return null;\n }\n }\n\n /**\n * {@inheritDoc}\n */\n public function findOrFail(string $path): FolderInterface\n {\n return $this->get()->firstOrFail(\n fn (FolderInterface $folder) => strtolower($folder->path()) === strtolower($path)\n );\n }\n\n /**\n * {@inheritDoc}\n */\n public function create(string $path): FolderInterface\n {\n return $this->folders[] = new FakeFolder($path, mailbox: $this->mailbox);\n }\n\n /**\n * {@inheritDoc}\n */\n public function firstOrCreate(string $path): FolderInterface\n {\n return $this->find($path) ?? $this->create($path);\n }\n\n /**\n * {@inheritDoc}\n */\n public function get(?string $match = '*', ?string $reference = ''): FolderCollection\n {\n $folders = FolderCollection::make($this->folders);\n\n // If we're not matching all, filter the folders by the match pattern.\n if (! in_array($match, ['*', null])) {\n return $folders->filter(\n fn (FolderInterface $folder) => Str::is($match, $folder->path())\n );\n }\n\n return $folders;\n }\n}\n"], ["/ImapEngine/src/Connection/ImapCommand.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection;\n\nuse Stringable;\n\nclass ImapCommand implements Stringable\n{\n /**\n * The compiled command lines.\n *\n * @var string[]\n */\n protected ?array $compiled = null;\n\n /**\n * Constructor.\n */\n public function __construct(\n protected string $tag,\n protected string $command,\n protected array $tokens = [],\n ) {}\n\n /**\n * Get the IMAP tag.\n */\n public function tag(): string\n {\n return $this->tag;\n }\n\n /**\n * Get the IMAP command.\n */\n public function command(): string\n {\n return $this->command;\n }\n\n /**\n * Get the IMAP tokens.\n */\n public function tokens(): array\n {\n return $this->tokens;\n }\n\n /**\n * Compile the command into lines for transmission.\n *\n * @return string[]\n */\n public function compile(): array\n {\n if (is_array($this->compiled)) {\n return $this->compiled;\n }\n\n $lines = [];\n\n $line = trim(\"{$this->tag} {$this->command}\");\n\n foreach ($this->tokens as $token) {\n if (is_array($token)) {\n // For tokens provided as arrays, the first element is a placeholder\n // (for example, \"{20}\") that signals a literal value will follow.\n // The second element holds the actual literal content.\n [$placeholder, $literal] = $token;\n\n $lines[] = \"{$line} {$placeholder}\";\n\n $line = $literal;\n } else {\n $line .= \" {$token}\";\n }\n }\n\n $lines[] = $line;\n\n return $this->compiled = $lines;\n }\n\n /**\n * Get a redacted version of the command for safe exposure.\n */\n public function redacted(): ImapCommand\n {\n return new static($this->tag, $this->command, array_map(\n function (mixed $token) {\n return is_array($token)\n ? array_map(fn () => '[redacted]', $token)\n : '[redacted]';\n }, $this->tokens)\n );\n }\n\n /**\n * Get the command as a string.\n */\n public function __toString(): string\n {\n return implode(\"\\r\\n\", $this->compile());\n }\n}\n"], ["/ImapEngine/src/DraftMessage.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\nuse DateTimeInterface;\nuse Stringable;\nuse Symfony\\Component\\Mime\\Email;\n\nclass DraftMessage implements Stringable\n{\n /**\n * The underlying Symfony Email instance.\n */\n protected Email $message;\n\n /**\n * Constructor.\n */\n public function __construct(\n protected ?string $from = null,\n protected array|string $to = [],\n protected array|string $cc = [],\n protected array|string $bcc = [],\n protected ?string $subject = null,\n protected ?string $text = null,\n protected ?string $html = null,\n protected array $headers = [],\n protected array $attachments = [],\n protected ?DateTimeInterface $date = null,\n ) {\n $this->message = new Email;\n\n if ($this->from) {\n $this->message->from($this->from);\n }\n\n if ($this->subject) {\n $this->message->subject($this->subject);\n }\n\n if ($this->text) {\n $this->message->text($this->text);\n }\n\n if ($this->html) {\n $this->message->html($this->html);\n }\n\n if ($this->date) {\n $this->message->date($this->date);\n }\n\n if (! empty($this->to)) {\n $this->message->to(...(array) $this->to);\n }\n\n if (! empty($this->cc)) {\n $this->message->cc(...(array) $this->cc);\n }\n\n if (! empty($this->bcc)) {\n $this->message->bcc(...(array) $this->bcc);\n }\n\n foreach ($this->attachments as $attachment) {\n match (true) {\n $attachment instanceof Attachment => $this->message->attach(\n $attachment->contents(),\n $attachment->filename(),\n $attachment->contentType()\n ),\n\n is_resource($attachment) => $this->message->attach($attachment),\n\n default => $this->message->attachFromPath($attachment),\n };\n }\n\n foreach ($this->headers as $name => $value) {\n $this->message->getHeaders()->addTextHeader($name, $value);\n }\n }\n\n /**\n * Get the underlying Symfony Email instance.\n */\n public function email(): Email\n {\n return $this->message;\n }\n\n /**\n * Get the email as a string.\n */\n public function __toString(): string\n {\n return $this->message->toString();\n }\n}\n"], ["/ImapEngine/src/Testing/FakeMessageQuery.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Testing;\n\nuse DirectoryTree\\ImapEngine\\Collections\\MessageCollection;\nuse DirectoryTree\\ImapEngine\\Connection\\ImapQueryBuilder;\nuse DirectoryTree\\ImapEngine\\Enums\\ImapFetchIdentifier;\nuse DirectoryTree\\ImapEngine\\MessageInterface;\nuse DirectoryTree\\ImapEngine\\MessageQueryInterface;\nuse DirectoryTree\\ImapEngine\\Pagination\\LengthAwarePaginator;\nuse DirectoryTree\\ImapEngine\\QueriesMessages;\n\nclass FakeMessageQuery implements MessageQueryInterface\n{\n use QueriesMessages;\n\n /**\n * Constructor.\n */\n public function __construct(\n protected FakeFolder $folder,\n protected ImapQueryBuilder $query = new ImapQueryBuilder\n ) {}\n\n /**\n * {@inheritDoc}\n */\n public function get(): MessageCollection\n {\n return new MessageCollection(\n $this->folder->getMessages()\n );\n }\n\n /**\n * {@inheritDoc}\n */\n public function count(): int\n {\n return count(\n $this->folder->getMessages()\n );\n }\n\n /**\n * {@inheritDoc}\n */\n public function first(): ?MessageInterface\n {\n return $this->get()->first();\n }\n\n /**\n * {@inheritDoc}\n */\n public function firstOrFail(): MessageInterface\n {\n return $this->get()->firstOrFail();\n }\n\n /**\n * {@inheritDoc}\n */\n public function append(string $message, mixed $flags = null): int\n {\n $uid = 1;\n\n if ($lastMessage = $this->get()->last()) {\n $uid = $lastMessage->uid() + 1;\n }\n\n $this->folder->addMessage(\n new FakeMessage($uid, $flags === null ? [] : $flags, $message)\n );\n\n return $uid;\n }\n\n /**\n * {@inheritDoc}\n */\n public function each(callable $callback, int $chunkSize = 10, int $startChunk = 1): void\n {\n $this->chunk(function (MessageCollection $messages) use ($callback) {\n foreach ($messages as $key => $message) {\n if ($callback($message, $key) === false) {\n return false;\n }\n }\n }, $chunkSize, $startChunk);\n }\n\n /**\n * {@inheritDoc}\n */\n public function chunk(callable $callback, int $chunkSize = 10, int $startChunk = 1): void\n {\n $page = $startChunk;\n\n foreach ($this->get()->chunk($chunkSize) as $chunk) {\n if ($page < $startChunk) {\n $page++;\n\n continue;\n }\n\n // If the callback returns false, break out.\n if ($callback($chunk, $page) === false) {\n break;\n }\n\n $page++;\n }\n }\n\n /**\n * {@inheritDoc}\n */\n public function paginate(int $perPage = 5, $page = null, string $pageName = 'page'): LengthAwarePaginator\n {\n return $this->get()->paginate($perPage, $page, $pageName);\n }\n\n /**\n * {@inheritDoc}\n */\n public function findOrFail(int $id, ImapFetchIdentifier $identifier = ImapFetchIdentifier::Uid): MessageInterface\n {\n return $this->get()->findOrFail($id);\n }\n\n /**\n * {@inheritDoc}\n */\n public function find(int $id, ImapFetchIdentifier $identifier = ImapFetchIdentifier::Uid): ?MessageInterface\n {\n return $this->get()->find($id);\n }\n\n /**\n * {@inheritDoc}\n */\n public function destroy(array|int $uids, bool $expunge = false): void\n {\n $messages = $this->get()->keyBy(\n fn (MessageInterface $message) => $message->uid()\n );\n\n foreach ((array) $uids as $uid) {\n $messages->pull($uid);\n }\n\n $this->folder->setMessages(\n $messages->values()->all()\n );\n }\n}\n"], ["/ImapEngine/src/Connection/Responses/Data/ListData.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Responses\\Data;\n\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\Token;\n\nclass ListData extends Data\n{\n /**\n * Lookup the value of the given field in the list.\n */\n public function lookup(string $field): Data|Token|null\n {\n foreach ($this->tokens as $index => $token) {\n if ((string) $token === $field) {\n return $this->tokenAt(++$index);\n }\n }\n\n return null;\n }\n\n /**\n * Get the list as a string.\n */\n public function __toString(): string\n {\n return sprintf('(%s)', implode(\n ' ', array_map('strval', $this->tokens)\n ));\n }\n}\n"], ["/ImapEngine/src/FolderRepository.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\nuse DirectoryTree\\ImapEngine\\Collections\\FolderCollection;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\UntaggedResponse;\nuse DirectoryTree\\ImapEngine\\Support\\Str;\n\nclass FolderRepository implements FolderRepositoryInterface\n{\n /**\n * Constructor.\n */\n public function __construct(\n protected Mailbox $mailbox\n ) {}\n\n /**\n * {@inheritDoc}\n */\n public function find(string $path): ?FolderInterface\n {\n return $this->get($path)->first();\n }\n\n /**\n * {@inheritDoc}\n */\n public function findOrFail(string $path): FolderInterface\n {\n return $this->get($path)->firstOrFail();\n }\n\n /**\n * {@inheritDoc}\n */\n public function create(string $path): FolderInterface\n {\n $this->mailbox->connection()->create(\n Str::toImapUtf7($path)\n );\n\n return $this->find($path);\n }\n\n /**\n * {@inheritDoc}\n */\n public function firstOrCreate(string $path): FolderInterface\n {\n return $this->find($path) ?? $this->create($path);\n }\n\n /**\n * {@inheritDoc}\n */\n public function get(?string $match = '*', ?string $reference = ''): FolderCollection\n {\n return $this->mailbox->connection()->list($reference, Str::toImapUtf7($match))->map(\n fn (UntaggedResponse $response) => new Folder(\n mailbox: $this->mailbox,\n path: $response->tokenAt(4)->value,\n flags: $response->tokenAt(2)->values(),\n delimiter: $response->tokenAt(3)->value,\n )\n )->pipeInto(FolderCollection::class);\n }\n}\n"], ["/ImapEngine/src/Connection/Responses/MessageResponseParser.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Responses;\n\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\Data\\ResponseCodeData;\n\nclass MessageResponseParser\n{\n /**\n * Get the flags from an untagged response.\n *\n * @return array<string, string[]>\n */\n public static function getFlags(UntaggedResponse $response): array\n {\n $data = $response->tokenAt(3);\n\n $uid = $data->lookup('UID')->value;\n $flags = $data->lookup('FLAGS')->values();\n\n return [$uid => $flags];\n }\n\n /**\n * Get the body header from an untagged response.\n *\n * @return array<string, string>\n */\n public static function getBodyHeader(UntaggedResponse $response): array\n {\n $data = $response->tokenAt(3);\n\n $uid = $data->lookup('UID')->value;\n $headers = $data->lookup('[HEADER]')->value;\n\n return [$uid => $headers];\n }\n\n /**\n * Get the body text from an untagged response.\n *\n * @return array<string, string>\n */\n public static function getBodyText(UntaggedResponse $response): array\n {\n $data = $response->tokenAt(3);\n\n $uid = $data->lookup('UID')->value;\n $contents = $data->lookup('[TEXT]')->value;\n\n return [$uid => $contents];\n }\n\n /**\n * Get the UID from a tagged move or copy response.\n */\n public static function getUidFromCopy(TaggedResponse $response): ?int\n {\n if (! $data = $response->tokenAt(2)) {\n return null;\n }\n\n if (! $data instanceof ResponseCodeData) {\n return null;\n }\n\n if (! $value = $data->tokenAt(3)?->value) {\n return null;\n }\n\n return (int) $value;\n }\n}\n"], ["/ImapEngine/src/Connection/Responses/Data/Data.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Responses\\Data;\n\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\HasTokens;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\Token;\nuse Stringable;\n\nabstract class Data implements Stringable\n{\n use HasTokens;\n\n /**\n * Constructor.\n */\n public function __construct(\n protected array $tokens\n ) {}\n\n /**\n * Get the tokens.\n *\n * @return Token[]|Data[]\n */\n public function tokens(): array\n {\n return $this->tokens;\n }\n\n /**\n * Get the first token.\n */\n public function first(): Token|Data|null\n {\n return $this->tokens[0] ?? null;\n }\n\n /**\n * Get the last token.\n */\n public function last(): Token|Data|null\n {\n return $this->tokens[count($this->tokens) - 1] ?? null;\n }\n\n /**\n * Determine if the data contains a specific value.\n */\n public function contains(array|string $needles): bool\n {\n $haystack = $this->values();\n\n foreach ((array) $needles as $needle) {\n if (! in_array($needle, $haystack)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Get all the token's values.\n */\n public function values(): array\n {\n return array_map(function (Token|Data $token) {\n return $token instanceof Data\n ? $token->values()\n : $token->value;\n }, $this->tokens);\n }\n}\n"], ["/ImapEngine/src/Testing/FakeMessage.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Testing;\n\nuse DirectoryTree\\ImapEngine\\HasFlags;\nuse DirectoryTree\\ImapEngine\\HasParsedMessage;\nuse DirectoryTree\\ImapEngine\\MessageInterface;\nuse DirectoryTree\\ImapEngine\\Support\\Str;\n\nclass FakeMessage implements MessageInterface\n{\n use HasFlags, HasParsedMessage;\n\n /**\n * Constructor.\n */\n public function __construct(\n protected int $uid,\n protected array $flags = [],\n protected string $contents = '',\n ) {}\n\n /**\n * {@inheritDoc}\n */\n public function uid(): int\n {\n return $this->uid;\n }\n\n /**\n * {@inheritDoc}\n */\n public function is(MessageInterface $message): bool\n {\n return $message instanceof self\n && $this->uid === $message->uid\n && $this->flags === $message->flags\n && $this->contents === $message->contents;\n }\n\n /**\n * {@inheritDoc}\n */\n public function flag(mixed $flag, string $operation, bool $expunge = false): void\n {\n $flag = Str::enum($flag);\n\n if ($operation === '+') {\n $this->flags = array_unique([...$this->flags, $flag]);\n } else {\n $this->flags = array_filter($this->flags, fn (string $value) => $value !== $flag);\n }\n }\n\n /**\n * {@inheritDoc}\n */\n public function flags(): array\n {\n return $this->flags;\n }\n\n /**\n * {@inheritDoc}\n */\n protected function isEmpty(): bool\n {\n return empty($this->contents);\n }\n\n /**\n * {@inheritDoc}\n */\n public function __toString(): string\n {\n return $this->contents;\n }\n}\n"], ["/ImapEngine/src/Attachment.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\nuse Illuminate\\Contracts\\Support\\Arrayable;\nuse JsonSerializable;\nuse Psr\\Http\\Message\\StreamInterface;\nuse Symfony\\Component\\Mime\\MimeTypes;\n\nclass Attachment implements Arrayable, JsonSerializable\n{\n /**\n * Constructor.\n */\n public function __construct(\n protected ?string $filename,\n protected ?string $contentId,\n protected string $contentType,\n protected StreamInterface $contentStream,\n ) {}\n\n /**\n * Get the attachment's filename.\n */\n public function filename(): ?string\n {\n return $this->filename;\n }\n\n /**\n * Get the attachment's content ID.\n */\n public function contentId(): ?string\n {\n return $this->contentId;\n }\n\n /**\n * Get the attachment's content type.\n */\n public function contentType(): string\n {\n return $this->contentType;\n }\n\n /**\n * Get the attachment's contents.\n */\n public function contents(): string\n {\n return $this->contentStream->getContents();\n }\n\n /**\n * Get the attachment's content stream.\n */\n public function contentStream(): StreamInterface\n {\n return $this->contentStream;\n }\n\n /**\n * Save the attachment to a file.\n */\n public function save(string $path): false|int\n {\n return file_put_contents($path, $this->contents());\n }\n\n /**\n * Get the attachment's extension.\n */\n public function extension(): ?string\n {\n if ($ext = pathinfo($this->filename, PATHINFO_EXTENSION)) {\n return $ext;\n }\n\n if ($ext = (MimeTypes::getDefault()->getExtensions($this->contentType)[0] ?? null)) {\n return $ext;\n }\n\n return null;\n }\n\n /**\n * Get the array representation of the attachment.\n */\n public function toArray(): array\n {\n return [\n 'filename' => $this->filename,\n 'content_type' => $this->contentType,\n 'contents' => $this->contents(),\n ];\n }\n\n /**\n * Get the JSON representation of the attachment.\n */\n public function jsonSerialize(): array\n {\n return $this->toArray();\n }\n}\n"], ["/ImapEngine/src/Exceptions/ImapCommandException.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Exceptions;\n\nuse DirectoryTree\\ImapEngine\\Connection\\ImapCommand;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\Response;\n\nclass ImapCommandException extends Exception\n{\n /**\n * The IMAP response.\n */\n protected Response $response;\n\n /**\n * The failed IMAP command.\n */\n protected ImapCommand $command;\n\n /**\n * Make a new instance from a failed command and response.\n */\n public static function make(ImapCommand $command, Response $response): static\n {\n $exception = new static(sprintf('IMAP command \"%s\" failed. Response: \"%s\"', $command, $response));\n\n $exception->command = $command;\n $exception->response = $response;\n\n return $exception;\n }\n\n /**\n * Get the failed IMAP command.\n */\n public function command(): ImapCommand\n {\n return $this->command;\n }\n\n /**\n * Get the IMAP response.\n */\n public function response(): Response\n {\n return $this->response;\n }\n}\n"], ["/ImapEngine/src/Testing/FakeMailbox.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Testing;\n\nuse DirectoryTree\\ImapEngine\\Connection\\ConnectionInterface;\nuse DirectoryTree\\ImapEngine\\Exceptions\\Exception;\nuse DirectoryTree\\ImapEngine\\FolderInterface;\nuse DirectoryTree\\ImapEngine\\FolderRepositoryInterface;\nuse DirectoryTree\\ImapEngine\\MailboxInterface;\n\nclass FakeMailbox implements MailboxInterface\n{\n /**\n * The currently selected folder.\n */\n protected ?FolderInterface $selected = null;\n\n /**\n * Constructor.\n */\n public function __construct(\n protected array $config = [],\n /** @var FakeFolder[] */\n protected array $folders = [],\n protected array $capabilities = [],\n ) {\n foreach ($folders as $folder) {\n $folder->setMailbox($this);\n }\n }\n\n /**\n * {@inheritDoc}\n */\n public function config(?string $key = null, mixed $default = null): mixed\n {\n if (is_null($key)) {\n return $this->config;\n }\n\n return data_get($this->config, $key, $default);\n }\n\n /**\n * {@inheritDoc}\n */\n public function connection(): ConnectionInterface\n {\n throw new Exception('Unsupported.');\n }\n\n /**\n * {@inheritDoc}\n */\n public function connected(): bool\n {\n return true;\n }\n\n /**\n * {@inheritDoc}\n */\n public function reconnect(): void\n {\n // Do nothing.\n }\n\n /**\n * {@inheritDoc}\n */\n public function connect(?ConnectionInterface $connection = null): void\n {\n // Do nothing.\n }\n\n /**\n * {@inheritDoc}\n */\n public function disconnect(): void\n {\n // Do nothing.\n }\n\n /**\n * {@inheritDoc}\n */\n public function inbox(): FolderInterface\n {\n return $this->folders()->findOrFail('inbox');\n }\n\n /**\n * {@inheritDoc}\n */\n public function folders(): FolderRepositoryInterface\n {\n return new FakeFolderRepository($this, $this->folders);\n }\n\n /**\n * {@inheritDoc}\n */\n public function capabilities(): array\n {\n return $this->capabilities;\n }\n\n /**\n * {@inheritDoc}\n */\n public function select(FolderInterface $folder, bool $force = false): void\n {\n $this->selected = $folder;\n }\n\n /**\n * {@inheritDoc}\n */\n public function selected(FolderInterface $folder): bool\n {\n return $this->selected?->is($folder) ?? false;\n }\n}\n"], ["/ImapEngine/src/Testing/FakeFolder.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Testing;\n\nuse DirectoryTree\\ImapEngine\\ComparesFolders;\nuse DirectoryTree\\ImapEngine\\Exceptions\\Exception;\nuse DirectoryTree\\ImapEngine\\FolderInterface;\nuse DirectoryTree\\ImapEngine\\MailboxInterface;\nuse DirectoryTree\\ImapEngine\\MessageQueryInterface;\nuse DirectoryTree\\ImapEngine\\Support\\Str;\n\nclass FakeFolder implements FolderInterface\n{\n use ComparesFolders;\n\n /**\n * Constructor.\n */\n public function __construct(\n protected string $path = '',\n protected array $flags = [],\n /** @var FakeMessage[] */\n protected array $messages = [],\n protected string $delimiter = '/',\n protected ?MailboxInterface $mailbox = null,\n ) {}\n\n /**\n * {@inheritDoc}\n */\n public function mailbox(): MailboxInterface\n {\n return $this->mailbox ?? throw new Exception('Folder has no mailbox.');\n }\n\n /**\n * {@inheritDoc}\n */\n public function path(): string\n {\n return $this->path;\n }\n\n /**\n * {@inheritDoc}\n */\n public function flags(): array\n {\n return $this->flags;\n }\n\n /**\n * {@inheritDoc}\n */\n public function delimiter(): string\n {\n return $this->delimiter;\n }\n\n /**\n * {@inheritDoc}\n */\n public function name(): string\n {\n return Str::fromImapUtf7(\n last(explode($this->delimiter, $this->path))\n );\n }\n\n /**\n * {@inheritDoc}\n */\n public function is(FolderInterface $folder): bool\n {\n return $this->isSameFolder($this, $folder);\n }\n\n /**\n * {@inheritDoc}\n */\n public function messages(): MessageQueryInterface\n {\n // Ensure the folder is selected.\n $this->select(true);\n\n return new FakeMessageQuery($this);\n }\n\n /**\n * {@inheritDoc}\n */\n public function idle(callable $callback, ?callable $query = null, int $timeout = 300): void\n {\n foreach ($this->messages as $message) {\n $callback($message);\n }\n }\n\n /**\n * {@inheritDoc}\n */\n public function move(string $newPath): void\n {\n // Do nothing.\n }\n\n /**\n * {@inheritDoc}\n */\n public function select(bool $force = false): void\n {\n $this->mailbox?->select($this, $force);\n }\n\n /**\n * {@inheritDoc}\n */\n public function status(): array\n {\n return [];\n }\n\n /**\n * {@inheritDoc}\n */\n public function examine(): array\n {\n return [];\n }\n\n /**\n * {@inheritDoc}\n */\n public function expunge(): array\n {\n return [];\n }\n\n /**\n * {@inheritDoc}\n */\n public function delete(): void\n {\n // Do nothing.\n }\n\n /**\n * Set the folder's path.\n */\n public function setPath(string $path): FakeFolder\n {\n $this->path = $path;\n\n return $this;\n }\n\n /**\n * Set the folder's flags.\n */\n public function setFlags(array $flags): FakeFolder\n {\n $this->flags = $flags;\n\n return $this;\n }\n\n /**\n * Set the folder's mailbox.\n */\n public function setMailbox(MailboxInterface $mailbox): FakeFolder\n {\n $this->mailbox = $mailbox;\n\n return $this;\n }\n\n /**\n * Set the folder's messages.\n *\n * @param FakeMessage[] $messages\n */\n public function setMessages(array $messages): FakeFolder\n {\n $this->messages = $messages;\n\n return $this;\n }\n\n /**\n * Get the folder's messages.\n *\n * @return FakeMessage[]\n */\n public function getMessages(): array\n {\n return $this->messages;\n }\n\n /**\n * Add a message to the folder.\n */\n public function addMessage(FakeMessage $message): void\n {\n $this->messages[] = $message;\n }\n\n /**\n * Set the folder's delimiter.\n */\n public function setDelimiter(string $delimiter = '/'): FakeFolder\n {\n $this->delimiter = $delimiter;\n\n return $this;\n }\n}\n"], ["/ImapEngine/src/Collections/PaginatedCollection.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Collections;\n\nuse DirectoryTree\\ImapEngine\\Pagination\\LengthAwarePaginator;\nuse Illuminate\\Support\\Collection;\n\n/**\n * @template TKey of array-key\n *\n * @template-covariant TValue\n *\n * @template-extends Collection<TKey, TValue>\n */\nclass PaginatedCollection extends Collection\n{\n /**\n * The total number of items.\n */\n protected int $total = 0;\n\n /**\n * Paginate the current collection.\n *\n * @return LengthAwarePaginator<TKey, TValue>\n */\n public function paginate(int $perPage = 15, ?int $page = null, string $pageName = 'page', bool $prepaginated = false): LengthAwarePaginator\n {\n $total = $this->total ?: $this->count();\n\n $results = ! $prepaginated && $total ? $this->forPage($page, $perPage) : $this;\n\n return $this->paginator($results, $total, $perPage, $page, $pageName);\n }\n\n /**\n * Create a new length-aware paginator instance.\n *\n * @return LengthAwarePaginator<TKey, TValue>\n */\n protected function paginator(Collection $items, int $total, int $perPage, ?int $currentPage, string $pageName): LengthAwarePaginator\n {\n return new LengthAwarePaginator($items, $total, $perPage, $currentPage, $pageName);\n }\n\n /**\n * Get or set the total amount.\n */\n public function total(?int $total = null): ?int\n {\n if (is_null($total)) {\n return $this->total;\n }\n\n return $this->total = $total;\n }\n}\n"], ["/ImapEngine/src/Connection/Responses/Response.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Responses;\n\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\Data\\Data;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\Token;\nuse Illuminate\\Contracts\\Support\\Arrayable;\nuse Stringable;\n\nclass Response implements Arrayable, Stringable\n{\n use HasTokens;\n\n /**\n * Constructor.\n */\n public function __construct(\n protected array $tokens\n ) {}\n\n /**\n * Get the response tokens.\n *\n * @return Token[]|Data[]\n */\n public function tokens(): array\n {\n return $this->tokens;\n }\n\n /**\n * Get the instance as an array.\n */\n public function toArray(): array\n {\n return array_map(function (Token|Data $token) {\n return $token instanceof Data\n ? $token->values()\n : $token->value;\n }, $this->tokens);\n }\n\n /**\n * Get a JSON representation of the response tokens.\n */\n public function __toString(): string\n {\n return implode(' ', $this->tokens);\n }\n}\n"], ["/ImapEngine/src/Connection/Loggers/Logger.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Loggers;\n\nabstract class Logger implements LoggerInterface\n{\n /**\n * Write a message to the log.\n */\n abstract protected function write(string $message): void;\n\n /**\n * {@inheritDoc}\n */\n public function sent(string $message): void\n {\n $this->write(sprintf('%s: >> %s', $this->date(), $message).PHP_EOL);\n }\n\n /**\n * {@inheritDoc}\n */\n public function received(string $message): void\n {\n $this->write(sprintf('%s: << %s', $this->date(), $message).PHP_EOL);\n }\n\n /**\n * Get the current date and time.\n */\n protected function date(): string\n {\n return date('Y-m-d H:i:s');\n }\n}\n"], ["/ImapEngine/src/Collections/MessageCollection.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Collections;\n\nuse DirectoryTree\\ImapEngine\\MessageInterface;\n\n/**\n * @template-extends PaginatedCollection<array-key, \\DirectoryTree\\ImapEngine\\MessageInterface|\\DirectoryTree\\ImapEngine\\Message>\n */\nclass MessageCollection extends PaginatedCollection\n{\n /**\n * Find a message by its UID.\n *\n * @return \\DirectoryTree\\ImapEngine\\Message|null\n */\n public function find(int $uid): ?MessageInterface\n {\n return $this->first(\n fn (MessageInterface $message) => $message->uid() === $uid\n );\n }\n\n /**\n * Find a message by its UID or throw an exception.\n *\n * @return \\DirectoryTree\\ImapEngine\\Message\n */\n public function findOrFail(int $uid): MessageInterface\n {\n return $this->firstOrFail(\n fn (MessageInterface $message) => $message->uid() === $uid\n );\n }\n}\n"], ["/ImapEngine/src/MessageParser.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\nuse ZBateson\\MailMimeParser\\MailMimeParser;\nuse ZBateson\\MailMimeParser\\Message as MailMimeMessage;\n\nclass MessageParser\n{\n /**\n * The mail mime parser instance.\n */\n protected static ?MailMimeParser $parser = null;\n\n /**\n * Parse the given message contents.\n */\n public static function parse(string $contents): MailMimeMessage\n {\n return static::parser()->parse($contents, true);\n }\n\n /**\n * Get the mail mime parser instance.\n */\n protected static function parser(): MailMimeParser\n {\n return static::$parser ??= new MailMimeParser;\n }\n}\n"], ["/ImapEngine/src/Connection/Streams/StreamInterface.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Streams;\n\ninterface StreamInterface\n{\n /**\n * Open the underlying stream.\n */\n public function open(string $transport, string $host, int $port, int $timeout, array $options = []): bool;\n\n /**\n * Close the underlying stream.\n */\n public function close(): void;\n\n /**\n * Read data from the stream.\n */\n public function read(int $length): string|false;\n\n /**\n * Read a single line from the stream.\n */\n public function fgets(): string|false;\n\n /**\n * Write data to the stream.\n */\n public function fwrite(string $data): int|false;\n\n /**\n * Return meta info (like stream_get_meta_data).\n */\n public function meta(): array;\n\n /**\n * Determine if the stream is open.\n */\n public function opened(): bool;\n\n /**\n * Set the timeout on the stream.\n */\n public function setTimeout(int $seconds): bool;\n\n /**\n * Set encryption state on an already connected socked.\n */\n public function setSocketSetCrypto(bool $enabled, ?int $method): bool|int;\n}\n"], ["/ImapEngine/src/Collections/ResponseCollection.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Collections;\n\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\ContinuationResponse;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\Response;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\TaggedResponse;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\UntaggedResponse;\nuse Illuminate\\Support\\Collection;\n\n/**\n * @template-extends Collection<array-key, Response>\n */\nclass ResponseCollection extends Collection\n{\n /**\n * Filter the collection to only tagged responses.\n *\n * @return self<array-key, TaggedResponse>\n */\n public function tagged(): self\n {\n return $this->whereInstanceOf(TaggedResponse::class);\n }\n\n /**\n * Filter the collection to only untagged responses.\n *\n * @return self<array-key, UntaggedResponse>\n */\n public function untagged(): self\n {\n return $this->whereInstanceOf(UntaggedResponse::class);\n }\n\n /**\n * Filter the collection to only continuation responses.\n *\n * @return self<array-key, ContinuationResponse>\n */\n public function continuation(): self\n {\n return $this->whereInstanceOf(ContinuationResponse::class);\n }\n}\n"], ["/ImapEngine/src/MessageQueryInterface.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\nuse DirectoryTree\\ImapEngine\\Collections\\MessageCollection;\nuse DirectoryTree\\ImapEngine\\Enums\\ImapFetchIdentifier;\nuse DirectoryTree\\ImapEngine\\Pagination\\LengthAwarePaginator;\n\n/**\n * @mixin \\DirectoryTree\\ImapEngine\\Connection\\ImapQueryBuilder\n */\ninterface MessageQueryInterface\n{\n /**\n * Don't mark messages as read when fetching.\n */\n public function leaveUnread(): MessageQueryInterface;\n\n /**\n * Mark all messages as read when fetching.\n */\n public function markAsRead(): MessageQueryInterface;\n\n /**\n * Set the limit and page for the current query.\n */\n public function limit(int $limit, int $page = 1): MessageQueryInterface;\n\n /**\n * Get the set fetch limit.\n */\n public function getLimit(): ?int;\n\n /**\n * Set the fetch limit.\n */\n public function setLimit(int $limit): MessageQueryInterface;\n\n /**\n * Get the set page.\n */\n public function getPage(): int;\n\n /**\n * Set the page.\n */\n public function setPage(int $page): MessageQueryInterface;\n\n /**\n * Determine if the body of messages is being fetched.\n */\n public function isFetchingBody(): bool;\n\n /**\n * Determine if the flags of messages is being fetched.\n */\n public function isFetchingFlags(): bool;\n\n /**\n * Determine if the headers of messages is being fetched.\n */\n public function isFetchingHeaders(): bool;\n\n /**\n * Fetch the flags of messages.\n */\n public function withFlags(): MessageQueryInterface;\n\n /**\n * Fetch the body of messages.\n */\n public function withBody(): MessageQueryInterface;\n\n /**\n * Fetch the headers of messages.\n */\n public function withHeaders(): MessageQueryInterface;\n\n /**\n * Don't fetch the body of messages.\n */\n public function withoutBody(): MessageQueryInterface;\n\n /**\n * Don't fetch the headers of messages.\n */\n public function withoutHeaders(): MessageQueryInterface;\n\n /**\n * Don't fetch the flags of messages.\n */\n public function withoutFlags(): MessageQueryInterface;\n\n /**\n * Set the fetch order.\n */\n public function setFetchOrder(string $fetchOrder): MessageQueryInterface;\n\n /**\n * Get the fetch order.\n */\n public function getFetchOrder(): string;\n\n /**\n * Set the fetch order to 'ascending'.\n */\n public function setFetchOrderAsc(): MessageQueryInterface;\n\n /**\n * Set the fetch order to 'descending'.\n */\n public function setFetchOrderDesc(): MessageQueryInterface;\n\n /**\n * Set the fetch order to show oldest messages first (ascending).\n */\n public function oldest(): MessageQueryInterface;\n\n /**\n * Set the fetch order to show newest messages first (descending).\n */\n public function newest(): MessageQueryInterface;\n\n /**\n * Count all available messages matching the current search criteria.\n */\n public function count(): int;\n\n /**\n * Get the first message in the resulting collection.\n *\n * @return \\DirectoryTree\\ImapEngine\\Message|null\n */\n public function first(): ?MessageInterface;\n\n /**\n * Get the first message in the resulting collection or throw an exception.\n *\n * @return \\DirectoryTree\\ImapEngine\\Message\n */\n public function firstOrFail(): MessageInterface;\n\n /**\n * Get the messages matching the current query.\n */\n public function get(): MessageCollection;\n\n /**\n * Append a new message to the folder.\n */\n public function append(string $message, mixed $flags = null): int;\n\n /**\n * Execute a callback over each message via a chunked query.\n */\n public function each(callable $callback, int $chunkSize = 10, int $startChunk = 1): void;\n\n /**\n * Execute a callback over each chunk of messages.\n */\n public function chunk(callable $callback, int $chunkSize = 10, int $startChunk = 1): void;\n\n /**\n * Paginate the current query.\n */\n public function paginate(int $perPage = 5, $page = null, string $pageName = 'page'): LengthAwarePaginator;\n\n /**\n * Find a message by the given identifier type or throw an exception.\n *\n * @return \\DirectoryTree\\ImapEngine\\Message\n */\n public function findOrFail(int $id, ImapFetchIdentifier $identifier = ImapFetchIdentifier::Uid): MessageInterface;\n\n /**\n * Find a message by the given identifier type.\n *\n * @return \\DirectoryTree\\ImapEngine\\Message|null\n */\n public function find(int $id, ImapFetchIdentifier $identifier = ImapFetchIdentifier::Uid): ?MessageInterface;\n\n /**\n * Destroy the given messages.\n */\n public function destroy(array|int $uids, bool $expunge = false): void;\n}\n"], ["/ImapEngine/src/Connection/Responses/Data/ResponseCodeData.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Responses\\Data;\n\nclass ResponseCodeData extends Data\n{\n /**\n * Get the group as a string.\n */\n public function __toString(): string\n {\n return sprintf('[%s]', implode(\n ' ', array_map('strval', $this->tokens)\n ));\n }\n}\n"], ["/ImapEngine/src/Address.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\nuse Illuminate\\Contracts\\Support\\Arrayable;\nuse JsonSerializable;\n\nclass Address implements Arrayable, JsonSerializable\n{\n /**\n * Constructor.\n */\n public function __construct(\n protected string $email,\n protected string $name,\n ) {}\n\n /**\n * Get the address's email.\n */\n public function email(): string\n {\n return $this->email;\n }\n\n /**\n * Get the address's name.\n */\n public function name(): string\n {\n return $this->name;\n }\n\n /**\n * Get the array representation of the address.\n */\n public function toArray(): array\n {\n return [\n 'email' => $this->email,\n 'name' => $this->name,\n ];\n }\n\n /**\n * Get the JSON representation of the address.\n */\n public function jsonSerialize(): array\n {\n return $this->toArray();\n }\n}\n"], ["/ImapEngine/src/HasFlags.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\nuse BackedEnum;\nuse DirectoryTree\\ImapEngine\\Enums\\ImapFlag;\nuse DirectoryTree\\ImapEngine\\Support\\Str;\n\ntrait HasFlags\n{\n /**\n * {@inheritDoc}\n */\n public function markRead(): void\n {\n $this->markSeen();\n }\n\n /**\n * {@inheritDoc}\n */\n public function markUnread(): void\n {\n $this->unmarkSeen();\n }\n\n /**\n * {@inheritDoc}\n */\n public function markSeen(): void\n {\n $this->flag(ImapFlag::Seen, '+');\n }\n\n /**\n * {@inheritDoc}\n */\n public function unmarkSeen(): void\n {\n $this->flag(ImapFlag::Seen, '-');\n }\n\n /**\n * {@inheritDoc}\n */\n public function markAnswered(): void\n {\n $this->flag(ImapFlag::Answered, '+');\n }\n\n /**\n * {@inheritDoc}\n */\n public function unmarkAnswered(): void\n {\n $this->flag(ImapFlag::Answered, '-');\n }\n\n /**\n * {@inheritDoc}\n */\n public function markFlagged(): void\n {\n $this->flag(ImapFlag::Flagged, '+');\n }\n\n /**\n * {@inheritDoc}\n */\n public function unmarkFlagged(): void\n {\n $this->flag(ImapFlag::Flagged, '-');\n }\n\n /**\n * {@inheritDoc}\n */\n public function markDeleted(bool $expunge = false): void\n {\n $this->flag(ImapFlag::Deleted, '+', $expunge);\n }\n\n /**\n * {@inheritDoc}\n */\n public function unmarkDeleted(): void\n {\n $this->flag(ImapFlag::Deleted, '-');\n }\n\n /**\n * {@inheritDoc}\n */\n public function markDraft(): void\n {\n $this->flag(ImapFlag::Draft, '+');\n }\n\n /**\n * {@inheritDoc}\n */\n public function unmarkDraft(): void\n {\n $this->flag(ImapFlag::Draft, '-');\n }\n\n /**\n * {@inheritDoc}\n */\n public function markRecent(): void\n {\n $this->flag(ImapFlag::Recent, '+');\n }\n\n /**\n * {@inheritDoc}\n */\n public function unmarkRecent(): void\n {\n $this->flag(ImapFlag::Recent, '-');\n }\n\n /**\n * {@inheritDoc}\n */\n public function isSeen(): bool\n {\n return $this->hasFlag(ImapFlag::Seen);\n }\n\n /**\n * {@inheritDoc}\n */\n public function isAnswered(): bool\n {\n return $this->hasFlag(ImapFlag::Answered);\n }\n\n /**\n * {@inheritDoc}\n */\n public function isFlagged(): bool\n {\n return $this->hasFlag(ImapFlag::Flagged);\n }\n\n /**\n * {@inheritDoc}\n */\n public function isDeleted(): bool\n {\n return $this->hasFlag(ImapFlag::Deleted);\n }\n\n /**\n * {@inheritDoc}\n */\n public function isDraft(): bool\n {\n return $this->hasFlag(ImapFlag::Draft);\n }\n\n /**\n * {@inheritDoc}\n */\n public function isRecent(): bool\n {\n return $this->hasFlag(ImapFlag::Recent);\n }\n\n /**\n * {@inheritDoc}\n */\n public function hasFlag(BackedEnum|string $flag): bool\n {\n return in_array(Str::enum($flag), $this->flags());\n }\n\n /**\n * {@inheritDoc}\n */\n abstract public function flags(): array;\n\n /**\n * {@inheritDoc}\n */\n abstract public function flag(mixed $flag, string $operation, bool $expunge = false): void;\n}\n"], ["/ImapEngine/src/Connection/Result.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection;\n\nuse DirectoryTree\\ImapEngine\\Collections\\ResponseCollection;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\Response;\n\nclass Result\n{\n /**\n * Constructor.\n */\n public function __construct(\n protected ImapCommand $command,\n protected array $responses = [],\n ) {}\n\n /**\n * Get the executed command.\n */\n public function command(): ImapCommand\n {\n return $this->command;\n }\n\n /**\n * Add a response to the result.\n */\n public function addResponse(Response $response): void\n {\n $this->responses[] = $response;\n }\n\n /**\n * Get the recently received responses.\n */\n public function responses(): ResponseCollection\n {\n return new ResponseCollection($this->responses);\n }\n}\n"], ["/ImapEngine/src/Connection/Responses/HasTokens.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Responses;\n\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\Data\\Data;\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\Token;\n\ntrait HasTokens\n{\n /**\n * Get the response tokens.\n *\n * @return Token[]|Data[]\n */\n abstract public function tokens(): array;\n\n /**\n * Get the response token at the given index.\n */\n public function tokenAt(int $index): Token|Data|null\n {\n return $this->tokens()[$index] ?? null;\n }\n\n /**\n * Get the response tokens after the given index.\n */\n public function tokensAfter(int $index): array\n {\n return array_slice($this->tokens(), $index);\n }\n}\n"], ["/ImapEngine/src/Connection/Responses/TaggedResponse.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Responses;\n\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\Atom;\n\nclass TaggedResponse extends Response\n{\n /**\n * Get the response tag.\n */\n public function tag(): Atom\n {\n return $this->tokens[0];\n }\n\n /**\n * Get the response status token.\n */\n public function status(): Atom\n {\n return $this->tokens[1];\n }\n\n /**\n * Get the response data tokens.\n *\n * @return Atom[]\n */\n public function data(): array\n {\n return array_slice($this->tokens, 2);\n }\n\n /**\n * Determine if the response was successful.\n */\n public function successful(): bool\n {\n return $this->status()->value === 'OK';\n }\n\n /**\n * Determine if the response failed.\n */\n public function failed(): bool\n {\n return in_array($this->status()->value, ['NO', 'BAD']);\n }\n}\n"], ["/ImapEngine/src/ComparesFolders.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\ntrait ComparesFolders\n{\n /**\n * Determine if two folders are the same.\n */\n protected function isSameFolder(FolderInterface $a, FolderInterface $b): bool\n {\n return $a->path() === $b->path()\n && $a->mailbox()->config('host') === $b->mailbox()->config('host')\n && $a->mailbox()->config('username') === $b->mailbox()->config('username');\n }\n}\n"], ["/ImapEngine/src/Connection/Tokens/Atom.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Tokens;\n\n/**\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-atom\n */\nclass Atom extends Token\n{\n /**\n * Determine if the token is the given value.\n */\n public function is(string $value): bool\n {\n return $this->value === $value;\n }\n\n /**\n * Determine if the token is not the given value.\n */\n public function isNot(string $value): bool\n {\n return ! $this->is($value);\n }\n}\n"], ["/ImapEngine/src/FolderRepositoryInterface.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\nuse DirectoryTree\\ImapEngine\\Collections\\FolderCollection;\n\ninterface FolderRepositoryInterface\n{\n /**\n * Find a folder.\n */\n public function find(string $path): ?FolderInterface;\n\n /**\n * Find a folder or throw an exception.\n */\n public function findOrFail(string $path): FolderInterface;\n\n /**\n * Create a new folder.\n */\n public function create(string $path): FolderInterface;\n\n /**\n * Find or create a folder.\n */\n public function firstOrCreate(string $path): FolderInterface;\n\n /**\n * Get the mailboxes folders.\n */\n public function get(?string $match = '*', ?string $reference = ''): FolderCollection;\n}\n"], ["/ImapEngine/src/MailboxInterface.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\nuse DirectoryTree\\ImapEngine\\Connection\\ConnectionInterface;\n\ninterface MailboxInterface\n{\n /**\n * Get mailbox configuration values.\n */\n public function config(?string $key = null, mixed $default = null): mixed;\n\n /**\n * Get the mailbox connection.\n */\n public function connection(): ConnectionInterface;\n\n /**\n * Determine if connection was established.\n */\n public function connected(): bool;\n\n /**\n * Force a reconnection to the server.\n */\n public function reconnect(): void;\n\n /**\n * Connect to the server.\n */\n public function connect(?ConnectionInterface $connection = null): void;\n\n /**\n * Disconnect from server.\n */\n public function disconnect(): void;\n\n /**\n * Get the mailbox's inbox folder.\n */\n public function inbox(): FolderInterface;\n\n /**\n * Begin querying for mailbox folders.\n */\n public function folders(): FolderRepositoryInterface;\n\n /**\n * Get the mailbox's capabilities.\n */\n public function capabilities(): array;\n\n /**\n * Select the given folder.\n */\n public function select(FolderInterface $folder, bool $force = false): void;\n\n /**\n * Determine if the given folder is selected.\n */\n public function selected(FolderInterface $folder): bool;\n}\n"], ["/ImapEngine/src/Connection/ConnectionInterface.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection;\n\nuse DirectoryTree\\ImapEngine\\Collections\\ResponseCollection;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\TaggedResponse;\nuse DirectoryTree\\ImapEngine\\Connection\\Responses\\UntaggedResponse;\nuse DirectoryTree\\ImapEngine\\Enums\\ImapFetchIdentifier;\nuse Generator;\n\ninterface ConnectionInterface\n{\n /**\n * Open a new connection.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-state-and-flow-diagram\n */\n public function connect(string $host, ?int $port = null, array $options = []): void;\n\n /**\n * Close the current connection.\n */\n public function disconnect(): void;\n\n /**\n * Determine if the current session is connected.\n */\n public function connected(): bool;\n\n /**\n * Send a \"LOGIN\" command.\n *\n * Login to a new session.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-login-command\n */\n public function login(string $user, string $password): TaggedResponse;\n\n /**\n * Send a \"LOGOUT\" command.\n *\n * Logout of the current server session.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-logout-command\n */\n public function logout(): void;\n\n /**\n * Send an \"AUTHENTICATE\" command.\n *\n * Authenticate the current session.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-authenticate-command\n */\n public function authenticate(string $user, string $token): TaggedResponse;\n\n /**\n * Send a \"STARTTLS\" command.\n *\n * Upgrade the current plaintext connection to a secure TLS-encrypted connection.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-starttls-command\n */\n public function startTls(): void;\n\n /**\n * Send an \"IDLE\" command.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-idle-command\n */\n public function idle(int $timeout): Generator;\n\n /**\n * Send a \"DONE\" command.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#section-6.3.13\n */\n public function done(): void;\n\n /**\n * Send a \"NOOP\" command.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-noop-command\n */\n public function noop(): TaggedResponse;\n\n /**\n * Send a \"EXPUNGE\" command.\n *\n * Apply session saved changes to the server.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-expunge-command\n */\n public function expunge(): ResponseCollection;\n\n /**\n * Send a \"CAPABILITY\" command.\n *\n * Get the mailbox's available capabilities.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-capability-command\n */\n public function capability(): UntaggedResponse;\n\n /**\n * Send a \"SEARCH\" command.\n *\n * Execute a search request.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-search-command\n */\n public function search(array $params): UntaggedResponse;\n\n /**\n * Send a \"FETCH\" command.\n *\n * Exchange identification information.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc2971.\n */\n public function id(?array $ids = null): UntaggedResponse;\n\n /**\n * Send a \"FETCH UID\" command.\n *\n * Fetch message UIDs using the given message numbers.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-uid-command\n */\n public function uid(int|array $ids, ImapFetchIdentifier $identifier): ResponseCollection;\n\n /**\n * Send a \"FETCH BODY[TEXT]\" command.\n *\n * Fetch message text contents.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#section-6.4.5-9.9\n */\n public function bodyText(int|array $ids, bool $peek = true): ResponseCollection;\n\n /**\n * Send a \"FETCH BODY[HEADER]\" command.\n *\n * Fetch message headers.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#section-6.4.5-9.9\n */\n public function bodyHeader(int|array $ids, bool $peek = true): ResponseCollection;\n\n /**\n * Send a \"FETCH BODYSTRUCTURE\" command.\n *\n * Fetch message body structure.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#section-6.4.5-9.9\n */\n public function bodyStructure(int|array $ids): ResponseCollection;\n\n /**\n * Send a \"FETCH BODY[i]\" command.\n *\n * Fetch a specific part of the message BODY, such as BODY[1], BODY[1.2], etc.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#section-6.4.5-9.9\n */\n public function bodyPart(string $partIndex, int|array $ids, bool $peek = false): ResponseCollection;\n\n /**\n * Send a \"FETCH FLAGS\" command.\n *\n * Fetch a message flags.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#section-6.4.5-9.17\n */\n public function flags(int|array $ids): ResponseCollection;\n\n /**\n * Send a \"RFC822.SIZE\" command.\n *\n * Fetch message sizes.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#section-6.4.5-9.21\n */\n public function size(int|array $ids): ResponseCollection;\n\n /**\n * Send a \"SELECT\" command.\n *\n * Select the specified folder.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-select-command\n */\n public function select(string $folder): ResponseCollection;\n\n /**\n * Send a \"EXAMINE\" command.\n *\n * Examine a given folder.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-examine-command\n */\n public function examine(string $folder): ResponseCollection;\n\n /**\n * Send a \"LIST\" command.\n *\n * Get a list of available folders.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-list-command\n */\n public function list(string $reference = '', string $folder = '*'): ResponseCollection;\n\n /**\n * Send a \"STATUS\" command.\n *\n * Get the status of a given folder.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-status-command\n */\n public function status(string $folder, array $arguments = ['MESSAGES', 'UNSEEN', 'RECENT', 'UIDNEXT', 'UIDVALIDITY']): UntaggedResponse;\n\n /**\n * Send a \"STORE\" command.\n *\n * Set message flags.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-store-command\n */\n public function store(array|string $flags, array|int $from, ?int $to = null, ?string $mode = null, bool $silent = true, ?string $item = null): ResponseCollection;\n\n /**\n * Send a \"APPEND\" command.\n *\n * Append a new message to given folder.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-append-command\n */\n public function append(string $folder, string $message, ?array $flags = null): TaggedResponse;\n\n /**\n * Send a \"UID COPY\" command.\n *\n * Copy message set from current folder to other folder.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-copy-command\n */\n public function copy(string $folder, array|int $from, ?int $to = null): TaggedResponse;\n\n /**\n * Send a \"UID MOVE\" command.\n *\n * Move a message set from current folder to another folder.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-move-command\n */\n public function move(string $folder, array|int $from, ?int $to = null): TaggedResponse;\n\n /**\n * Send a \"CREATE\" command.\n *\n * Create a new folder.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-create-command\n */\n public function create(string $folder): ResponseCollection;\n\n /**\n * Send a \"DELETE\" command.\n *\n * Delete a folder.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-delete-command\n */\n public function delete(string $folder): TaggedResponse;\n\n /**\n * Send a \"RENAME\" command.\n *\n * Rename an existing folder.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-rename-command\n */\n public function rename(string $oldPath, string $newPath): TaggedResponse;\n\n /**\n * Send a \"SUBSCRIBE\" command.\n *\n * Subscribe to a folder.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-subscribe-command\n */\n public function subscribe(string $folder): TaggedResponse;\n\n /**\n * Send a \"UNSUBSCRIBE\" command.\n *\n * Unsubscribe from a folder.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc9051#name-unsubscribe-command\n */\n public function unsubscribe(string $folder): TaggedResponse;\n}\n"], ["/ImapEngine/src/Connection/Loggers/FileLogger.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Loggers;\n\nclass FileLogger extends Logger\n{\n /**\n * Constructor.\n */\n public function __construct(\n protected string $path\n ) {}\n\n /**\n * {@inheritDoc}\n */\n public function write(string $message): void\n {\n file_put_contents($this->path, $message, FILE_APPEND);\n }\n}\n"], ["/ImapEngine/src/MessageInterface.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\nuse Carbon\\CarbonInterface;\nuse Stringable;\nuse ZBateson\\MailMimeParser\\Header\\IHeader;\nuse ZBateson\\MailMimeParser\\Message as MailMimeMessage;\n\ninterface MessageInterface extends FlaggableInterface, Stringable\n{\n /**\n * Get the message's identifier.\n */\n public function uid(): int;\n\n /**\n * Get the message date and time.\n */\n public function date(): ?CarbonInterface;\n\n /**\n * Get the message's subject.\n */\n public function subject(): ?string;\n\n /**\n * Get the 'From' address.\n */\n public function from(): ?Address;\n\n /**\n * Get the 'Sender' address.\n */\n public function sender(): ?Address;\n\n /**\n * Get the message's 'Message-ID'.\n */\n public function messageId(): ?string;\n\n /**\n * Get the 'Reply-To' address.\n */\n public function replyTo(): ?Address;\n\n /**\n * Get the 'In-Reply-To' address.\n */\n public function inReplyTo(): ?Address;\n\n /**\n * Get the 'To' addresses.\n *\n * @return Address[]\n */\n public function to(): array;\n\n /**\n * Get the 'CC' addresses.\n *\n * @return Address[]\n */\n public function cc(): array;\n\n /**\n * Get the 'BCC' addresses.\n *\n * @return Address[]\n */\n public function bcc(): array;\n\n /**\n * Get the message's attachments.\n *\n * @return Attachment[]\n */\n public function attachments(): array;\n\n /**\n * Determine if the message has attachments.\n */\n public function hasAttachments(): bool;\n\n /**\n * Get the count of attachments.\n */\n public function attachmentCount(): int;\n\n /**\n * Get addresses from the given header.\n *\n * @return Address[]\n */\n public function addresses(string $header): array;\n\n /**\n * Get the message's HTML content.\n */\n public function html(): ?string;\n\n /**\n * Get the message's text content.\n */\n public function text(): ?string;\n\n /**\n * Get all headers from the message.\n */\n public function headers(): array;\n\n /**\n * Get a header from the message.\n */\n public function header(string $name, int $offset = 0): ?IHeader;\n\n /**\n * Parse the message into a MailMimeMessage instance.\n */\n public function parse(): MailMimeMessage;\n\n /**\n * Determine if the message is the same as another message.\n */\n public function is(MessageInterface $message): bool;\n\n /**\n * Get the string representation of the message.\n */\n public function __toString(): string;\n}\n"], ["/ImapEngine/src/Connection/Responses/UntaggedResponse.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Responses;\n\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\Atom;\n\nclass UntaggedResponse extends Response\n{\n /**\n * Get the response type token.\n */\n public function type(): Atom\n {\n return $this->tokens[1];\n }\n\n /**\n * Get the data tokens.\n *\n * @return Atom[]\n */\n public function data(): array\n {\n return array_slice($this->tokens, 2);\n }\n}\n"], ["/ImapEngine/src/Connection/Tokens/Literal.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Tokens;\n\nclass Literal extends Token\n{\n /**\n * Get the token's value.\n */\n public function __toString(): string\n {\n return sprintf(\"{%d}\\r\\n%s\", strlen($this->value), $this->value);\n }\n}\n"], ["/ImapEngine/src/FolderInterface.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\ninterface FolderInterface\n{\n /**\n * Get the folder's mailbox.\n */\n public function mailbox(): MailboxInterface;\n\n /**\n * Get the folder path.\n */\n public function path(): string;\n\n /**\n * Get the folder flags.\n *\n * @return string[]\n */\n public function flags(): array;\n\n /**\n * Get the folder delimiter.\n */\n public function delimiter(): string;\n\n /**\n * Get the folder name.\n */\n public function name(): string;\n\n /**\n * Determine if the current folder is the same as the given.\n */\n public function is(FolderInterface $folder): bool;\n\n /**\n * Begin querying for messages.\n */\n public function messages(): MessageQueryInterface;\n\n /**\n * Begin idling on the current folder.\n */\n public function idle(callable $callback, ?callable $query = null, int $timeout = 300): void;\n\n /**\n * Move or rename the current folder.\n */\n public function move(string $newPath): void;\n\n /**\n * Select the current folder.\n */\n public function select(bool $force = false): void;\n\n /**\n * Get the folder's status.\n */\n public function status(): array;\n\n /**\n * Examine the current folder and get detailed status information.\n */\n public function examine(): array;\n\n /**\n * Expunge the mailbox and return the expunged message sequence numbers.\n */\n public function expunge(): array;\n\n /**\n * Delete the current folder.\n */\n public function delete(): void;\n}\n"], ["/ImapEngine/src/FlaggableInterface.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine;\n\nuse BackedEnum;\n\ninterface FlaggableInterface\n{\n /**\n * Mark the message as read. Alias for markSeen.\n */\n public function markRead(): void;\n\n /**\n * Mark the message as unread. Alias for unmarkSeen.\n */\n public function markUnread(): void;\n\n /**\n * Mark the message as seen.\n */\n public function markSeen(): void;\n\n /**\n * Unmark the seen flag.\n */\n public function unmarkSeen(): void;\n\n /**\n * Mark the message as answered.\n */\n public function markAnswered(): void;\n\n /**\n * Unmark the answered flag.\n */\n public function unmarkAnswered(): void;\n\n /**\n * Mark the message as flagged.\n */\n public function markFlagged(): void;\n\n /**\n * Unmark the flagged flag.\n */\n public function unmarkFlagged(): void;\n\n /**\n * Mark the message as deleted.\n */\n public function markDeleted(bool $expunge = false): void;\n\n /**\n * Unmark the deleted flag.\n */\n public function unmarkDeleted(): void;\n\n /**\n * Mark the message as a draft.\n */\n public function markDraft(): void;\n\n /**\n * Unmark the draft flag.\n */\n public function unmarkDraft(): void;\n\n /**\n * Mark the message as recent.\n */\n public function markRecent(): void;\n\n /**\n * Unmark the recent flag.\n */\n public function unmarkRecent(): void;\n\n /**\n * Determine if the message is marked as seen.\n */\n public function isSeen(): bool;\n\n /**\n * Determine if the message is marked as answered.\n */\n public function isAnswered(): bool;\n\n /**\n * Determine if the message is flagged.\n */\n public function isFlagged(): bool;\n\n /**\n * Determine if the message is marked as deleted.\n */\n public function isDeleted(): bool;\n\n /**\n * Determine if the message is marked as a draft.\n */\n public function isDraft(): bool;\n\n /**\n * Determine if the message is marked as recent.\n */\n public function isRecent(): bool;\n\n /**\n * Get the message's flags.\n *\n * @return string[]\n */\n public function flags(): array;\n\n /**\n * Determine if the message has the given flag.\n */\n public function hasFlag(BackedEnum|string $flag): bool;\n\n /**\n * Add or remove a flag from the message.\n */\n public function flag(mixed $flag, string $operation, bool $expunge = false): void;\n}\n"], ["/ImapEngine/src/Connection/Tokens/Token.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Tokens;\n\nuse Stringable;\n\nabstract class Token implements Stringable\n{\n /**\n * Constructor.\n */\n public function __construct(\n public string $value,\n ) {}\n\n /**\n * Get the token's value.\n */\n public function __toString(): string\n {\n return $this->value;\n }\n}\n"], ["/ImapEngine/src/Connection/Loggers/RayLogger.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Loggers;\n\nclass RayLogger extends Logger\n{\n /**\n * {@inheritDoc}\n */\n protected function write(string $message): void\n {\n ray($message);\n }\n}\n"], ["/ImapEngine/src/Connection/Responses/ContinuationResponse.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Responses;\n\nuse DirectoryTree\\ImapEngine\\Connection\\Tokens\\Atom;\n\nclass ContinuationResponse extends Response\n{\n /**\n * Get the data tokens.\n *\n * @return Atom[]\n */\n public function data(): array\n {\n return array_slice($this->tokens, 1);\n }\n}\n"], ["/ImapEngine/src/Connection/Loggers/EchoLogger.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Loggers;\n\nclass EchoLogger extends Logger\n{\n /**\n * {@inheritDoc}\n */\n public function write(string $message): void\n {\n echo $message;\n }\n}\n"], ["/ImapEngine/src/Enums/ImapSearchKey.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Enums;\n\nenum ImapSearchKey: string\n{\n case Cc = 'CC';\n case On = 'ON';\n case To = 'TO';\n case All = 'ALL';\n case New = 'NEW';\n case Old = 'OLD';\n case Bcc = 'BCC';\n case Uid = 'UID';\n case Seen = 'SEEN';\n case Body = 'BODY';\n case From = 'FROM';\n case Text = 'TEXT';\n case Draft = 'DRAFT';\n case Since = 'SINCE';\n case Recent = 'RECENT';\n case Unseen = 'UNSEEN';\n case Before = 'BEFORE';\n case Header = 'HEADER';\n case Deleted = 'DELETED';\n case Flagged = 'FLAGGED';\n case Keyword = 'KEYWORD';\n case Subject = 'SUBJECT';\n case Answered = 'ANSWERED';\n case Undeleted = 'UNDELETED';\n case Unflagged = 'UNFLAGGED';\n case Unanswered = 'UNANSWERED';\n}\n"], ["/ImapEngine/src/Connection/Tokens/QuotedString.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Tokens;\n\nclass QuotedString extends Token\n{\n /**\n * Get the token's value.\n */\n public function __toString(): string\n {\n return '\"'.$this->value.'\"';\n }\n}\n"], ["/ImapEngine/src/Connection/Loggers/LoggerInterface.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Loggers;\n\ninterface LoggerInterface\n{\n /**\n * Log when a message is sent.\n */\n public function sent(string $message): void;\n\n /**\n * Log when a message is received.\n */\n public function received(string $message): void;\n}\n"], ["/ImapEngine/src/Connection/Tokens/EmailAddress.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Tokens;\n\nclass EmailAddress extends Token\n{\n /**\n * Get the token's value.\n */\n public function __toString(): string\n {\n return '<'.$this->value.'>';\n }\n}\n"], ["/ImapEngine/src/Connection/RawQueryValue.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection;\n\nuse Stringable;\n\nclass RawQueryValue\n{\n /**\n * Constructor.\n */\n public function __construct(\n public readonly Stringable|string $value\n ) {}\n}\n"], ["/ImapEngine/src/Collections/FolderCollection.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Collections;\n\nuse DirectoryTree\\ImapEngine\\FolderInterface;\nuse Illuminate\\Support\\Collection;\n\n/**\n * @template-extends Collection<array-key, FolderInterface>\n */\nclass FolderCollection extends Collection {}\n"], ["/ImapEngine/src/Enums/ImapFlag.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Enums;\n\nenum ImapFlag: string\n{\n case Seen = '\\Seen';\n case Draft = '\\Draft';\n case Recent = '\\Recent';\n case Flagged = '\\Flagged';\n case Deleted = '\\Deleted';\n case Answered = '\\Answered';\n}\n"], ["/ImapEngine/src/Exceptions/ImapConnectionClosedException.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Exceptions;\n\nclass ImapConnectionClosedException extends ImapConnectionException {}\n"], ["/ImapEngine/src/Exceptions/ImapConnectionFailedException.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Exceptions;\n\nclass ImapConnectionFailedException extends ImapConnectionException {}\n"], ["/ImapEngine/src/Exceptions/ImapConnectionTimedOutException.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Exceptions;\n\nclass ImapConnectionTimedOutException extends ImapConnectionException {}\n"], ["/ImapEngine/src/Exceptions/Exception.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Exceptions;\n\nclass Exception extends \\Exception {}\n"], ["/ImapEngine/src/Exceptions/ImapStreamException.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Exceptions;\n\nclass ImapStreamException extends Exception {}\n"], ["/ImapEngine/src/Exceptions/ImapCapabilityException.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Exceptions;\n\nclass ImapCapabilityException extends Exception {}\n"], ["/ImapEngine/src/Exceptions/ImapResponseException.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Exceptions;\n\nclass ImapResponseException extends Exception {}\n"], ["/ImapEngine/src/Exceptions/ImapParserException.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Exceptions;\n\nclass ImapParserException extends Exception {}\n"], ["/ImapEngine/src/Exceptions/ImapConnectionException.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Exceptions;\n\nabstract class ImapConnectionException extends Exception {}\n"], ["/ImapEngine/src/Enums/ImapFetchIdentifier.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Enums;\n\nenum ImapFetchIdentifier\n{\n case Uid;\n case MessageNumber;\n}\n"], ["/ImapEngine/src/Exceptions/RuntimeException.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Exceptions;\n\nclass RuntimeException extends \\RuntimeException {}\n"], ["/ImapEngine/src/Connection/Tokens/ListOpen.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Tokens;\n\nclass ListOpen extends Token {}\n"], ["/ImapEngine/src/Connection/Tokens/ListClose.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Tokens;\n\nclass ListClose extends Token {}\n"], ["/ImapEngine/src/Connection/Tokens/ResponseCodeOpen.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Tokens;\n\nclass ResponseCodeOpen extends Token {}\n"], ["/ImapEngine/src/Connection/Tokens/ResponseCodeClose.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Tokens;\n\nclass ResponseCodeClose extends Token {}\n"], ["/ImapEngine/src/Connection/Tokens/Crlf.php", "<?php\n\nnamespace DirectoryTree\\ImapEngine\\Connection\\Tokens;\n\nclass Crlf extends Token {}\n"]], "task_instance_info": {"created_time": "2025-08-20 21:24:43", "created_task_model": "DeepSeek-R1", "function_skeleton": "protected function forwardCallTo (object $object, string $method, array $parameters) : mixed {}", "code_description": "This code segment functions to: Delegate method invocations to a specified object while handling exceptions related to undefined methods and rethrowing them with contextualized error information."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```php\n[TASK_BEGIN]\n protected function forwardCallTo(object $object, string $method, array $parameters): mixed\n {\n if (method_exists($object, $method)) {\n return call_user_func_array([$object, $method], $parameters);\n }\n\n static::throwBadMethodCallException($method);\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 21-24-55"}, "editdistance_info": {"edit_distance": 31.1258, "calculate_time": "2025-08-20 21:24:55", "true_code_clean": "protected function forwardCallTo(object $object, string $method, array $parameters): mixed\n {\n try {\n return $object->{$method}(...$parameters);\n } catch (Error|BadMethodCallException $e) {\n $pattern = '~^Call to undefined method (?P<class>[^:]+)::(?P<method>[^\\(]+)\\(\\)$~';\n if (! preg_match($pattern, $e->getMessage(), $matches)) {\n throw $e;\n }\n if ($matches['class'] != get_class($object) ||\n $matches['method'] != $method) {\n throw $e;\n }\n static::throwBadMethodCallException($method);\n }\n }", "predict_code_clean": "protected function forwardCallTo(object $object, string $method, array $parameters): mixed\n {\n if (method_exists($object, $method)) {\n return call_user_func_array([$object, $method], $parameters);\n }\n static::throwBadMethodCallException($method);\n }"}} | |