<?php
 declare(strict_types=1); namespace SpomkyLabs\Pki\X509\Certificate\Extension\Target; use ArrayIterator; use Countable; use IteratorAggregate; use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence; use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType; use function count; final class Targets implements Countable, IteratorAggregate { private readonly array $targets; private function __construct(Target ...$targets) { $this->targets = $targets; } public static function create(Target ...$targets): self { return new self(...$targets); } public static function fromASN1(Sequence $seq): self { $targets = array_map(static fn (UnspecifiedType $el) => Target::fromASN1($el->asTagged()), $seq->elements()); return self::create(...$targets); } public function all(): array { return $this->targets; } public function nameTargets(): array { return $this->allOfType(Target::TYPE_NAME); } public function groupTargets(): array { return $this->allOfType(Target::TYPE_GROUP); } public function hasTarget(Target $target): bool { foreach ($this->allOfType($target->type()) as $t) { if ($target->equals($t)) { return true; } } return false; } public function toASN1(): Sequence { $elements = array_map(static fn (Target $target) => $target->toASN1(), $this->targets); return Sequence::create(...$elements); } public function count(): int { return count($this->targets); } public function getIterator(): ArrayIterator { return new ArrayIterator($this->targets); } private function allOfType(int $type): array { return array_values(array_filter($this->targets, static fn (Target $target) => $target->type() === $type)); } } 