<?php
 declare(strict_types=1); namespace Jose\Component\Encryption; use InvalidArgumentException; use Jose\Component\Core\JWT; use Override; use function array_key_exists; use function count; use function sprintf; class JWE implements JWT { private ?string $payload = null; public function __construct( private readonly ?string $ciphertext, private readonly string $iv, private readonly string $tag, private readonly ?string $aad = null, private readonly array $sharedHeader = [], private readonly array $sharedProtectedHeader = [], private readonly ?string $encodedSharedProtectedHeader = null, private readonly array $recipients = [] ) { } #[Override] public function getPayload(): ?string { return $this->payload; } public function withPayload(string $payload): self { $clone = clone $this; $clone->payload = $payload; return $clone; } public function countRecipients(): int { return count($this->recipients); } public function isEncrypted(): bool { return $this->getCiphertext() !== null; } public function getRecipients(): array { return $this->recipients; } public function getRecipient(int $id): Recipient { if (! isset($this->recipients[$id])) { throw new InvalidArgumentException('The recipient does not exist.'); } return $this->recipients[$id]; } public function getCiphertext(): ?string { return $this->ciphertext; } public function getAAD(): ?string { return $this->aad; } public function getIV(): ?string { return $this->iv; } public function getTag(): ?string { return $this->tag; } public function getEncodedSharedProtectedHeader(): string { return $this->encodedSharedProtectedHeader ?? ''; } public function getSharedProtectedHeader(): array { return $this->sharedProtectedHeader; } public function getSharedProtectedHeaderParameter(string $key) { if (! $this->hasSharedProtectedHeaderParameter($key)) { throw new InvalidArgumentException(sprintf('The shared protected header "%s" does not exist.', $key)); } return $this->sharedProtectedHeader[$key]; } public function hasSharedProtectedHeaderParameter(string $key): bool { return array_key_exists($key, $this->sharedProtectedHeader); } public function getSharedHeader(): array { return $this->sharedHeader; } public function getSharedHeaderParameter(string $key) { if (! $this->hasSharedHeaderParameter($key)) { throw new InvalidArgumentException(sprintf('The shared header "%s" does not exist.', $key)); } return $this->sharedHeader[$key]; } public function hasSharedHeaderParameter(string $key): bool { return array_key_exists($key, $this->sharedHeader); } public function split(): array { $result = []; foreach ($this->recipients as $recipient) { $result[] = new self( $this->ciphertext, $this->iv, $this->tag, $this->aad, $this->sharedHeader, $this->sharedProtectedHeader, $this->encodedSharedProtectedHeader, [$recipient] ); } return $result; } } 