generated from Nodarx/template
104 lines
2.7 KiB
PHP
104 lines
2.7 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace KTXM\ProviderImap\Client;
|
|
|
|
use InvalidArgumentException;
|
|
|
|
final class SequenceSet
|
|
{
|
|
private function __construct(
|
|
private readonly string $value,
|
|
) {}
|
|
|
|
public static function all(): self
|
|
{
|
|
return new self('1:*');
|
|
}
|
|
|
|
public static function single(int|string $identifier): self
|
|
{
|
|
return new self(self::normalizeIdentifier($identifier));
|
|
}
|
|
|
|
public static function range(int|string $from, int|string $to): self
|
|
{
|
|
return new self(sprintf(
|
|
'%s:%s',
|
|
self::normalizeIdentifier($from),
|
|
self::normalizeIdentifier($to),
|
|
));
|
|
}
|
|
|
|
public static function from(int|string $from): self
|
|
{
|
|
return self::range($from, '*');
|
|
}
|
|
|
|
public static function items(int|string ...$identifiers): self
|
|
{
|
|
if ($identifiers === []) {
|
|
throw new InvalidArgumentException('Sequence sets require at least one identifier.');
|
|
}
|
|
|
|
return new self(implode(',', array_map(
|
|
static fn (int|string $identifier): string => self::normalizeIdentifier($identifier),
|
|
$identifiers,
|
|
)));
|
|
}
|
|
|
|
public static function parse(string $value): self
|
|
{
|
|
$value = trim($value);
|
|
|
|
if ($value === '') {
|
|
throw new InvalidArgumentException('Sequence sets cannot be empty.');
|
|
}
|
|
|
|
$parts = preg_split('/\s*,\s*/', $value) ?: [];
|
|
if ($parts === []) {
|
|
throw new InvalidArgumentException('Sequence sets require at least one identifier.');
|
|
}
|
|
|
|
foreach ($parts as $part) {
|
|
if (!preg_match('/^(?:\*|[1-9]\d*)(?::(?:\*|[1-9]\d*))?$/', $part)) {
|
|
throw new InvalidArgumentException(sprintf('Invalid IMAP sequence-set segment: %s', $part));
|
|
}
|
|
}
|
|
|
|
return new self(implode(',', $parts));
|
|
}
|
|
|
|
public function toCommand(): string
|
|
{
|
|
return $this->value;
|
|
}
|
|
|
|
public function __toString(): string
|
|
{
|
|
return $this->value;
|
|
}
|
|
|
|
private static function normalizeIdentifier(int|string $identifier): string
|
|
{
|
|
if ($identifier === '*') {
|
|
return '*';
|
|
}
|
|
|
|
if (is_int($identifier)) {
|
|
if ($identifier < 1) {
|
|
throw new InvalidArgumentException('IMAP sequence identifiers must be greater than zero.');
|
|
}
|
|
|
|
return (string) $identifier;
|
|
}
|
|
|
|
$identifier = trim($identifier);
|
|
if (preg_match('/^[1-9]\d*$/', $identifier) !== 1) {
|
|
throw new InvalidArgumentException(sprintf('Invalid IMAP sequence identifier: %s', $identifier));
|
|
}
|
|
|
|
return $identifier;
|
|
}
|
|
} |