Files
2026-09-29 19:45:00 -04:00

104 lines
3.5 KiB
PHP

<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\ProviderImap\Providers;
use KTXM\ProviderImap\Client\Mailbox;
use KTXF\Mail\Collection\CollectionMutableAbstract;
/**
* IMAP Mail Collection Resource
*
* Represents one IMAP mailbox / folder.
*/
class CollectionResource extends CollectionMutableAbstract
{
public function __construct(
string $provider = 'imap',
string|int|null $service = null,
) {
parent::__construct($provider, $service);
}
// ── IMAP hydration ───────────────────────────────────────────────────────
/**
* Populate from a standalone IMAP Mailbox value object.
*
* @param Mailbox $mailbox mailbox value object from LIST response
* @param array $options additional options, e.g., ['delimiter' => '/']
*/
public function fromImap(Mailbox $mailbox, array $options = []): static
{
// The mailbox name is its unique identifier within the account
$this->data['identifier'] = $mailbox->name();
// Derive parent collection from path + delimiter
$delimiter = $mailbox->delimiter() ?? $options['delimiter'] ?? '/';
if ($delimiter && str_contains($mailbox->name(), $delimiter)) {
$parts = explode($delimiter, $mailbox->name());
array_pop($parts);
$this->data['collection'] = implode($delimiter, $parts);
} else {
$this->data['collection'] = null; // top-level mailbox
}
$this->getProperties()->fromImap($mailbox, $options);
return $this;
}
// ── Cache (meta store) ───────────────────────────────────────────────────
/**
* Serialise to a meta store document.
*
* The store adds the key fields it owns (sid, tid).
*/
public function toCacheMeta(): array
{
return [
'name' => (string) $this->data[static::PROPERTY_IDENTIFIER],
'parent' => $this->data[static::PROPERTY_COLLECTION] ?? null,
'signature' => $this->data[static::PROPERTY_SIGNATURE] ?? null,
'properties' => $this->getProperties()->toCacheMeta(),
];
}
/**
* Restore from a meta store document.
*
* Only the resource's own fields are read; store keys and harmonization state
* on the same document are ignored.
*/
public function fromCacheMeta(array $data): static
{
$this->data[static::PROPERTY_IDENTIFIER] = (string) $data['name'];
$this->data[static::PROPERTY_COLLECTION] = $data['parent'] ?? null;
if (isset($data['signature'])) {
$this->data[static::PROPERTY_SIGNATURE] = $data['signature'];
}
if (isset($data['properties'])) {
$this->getProperties()->fromCacheMeta((array) $data['properties']);
}
return $this;
}
// ── Getters (lazy properties init) ───────────────────────────────────────
public function getProperties(): CollectionProperties
{
if (!isset($this->properties)) {
$this->properties = new CollectionProperties([]);
}
return $this->properties;
}
}