Debian Codegraph @

lib/3rdParty/composer/spomky-labs/pki-framework/src/X509/Certificate/Extension/Target/Targets.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace SpomkyLabs\Pki\X509\Certificate\Extension\Target;
6
7 use ArrayIterator;
8 use function count;
9 use Countable;
10 use IteratorAggregate;
11 use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
12 use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
13
14 /**
15 * Implements *Targets* ASN.1 type as a *SEQUENCE OF Target*.
16 *
17 * @see https://tools.ietf.org/html/rfc5755#section-4.3.2
18 */
19 final class Targets implements Countable, IteratorAggregate
20 {
21 /**
22 * Target elements.
23 *
24 * @var Target[]
25 */
26 private readonly array $targets;
27
28 private function __construct(Target ...$targets)
29 {
30 $this->targets = $targets;
31 }
32
33 public static function create(Target ...$targets): self
34 {
35 return new self(...$targets);
36 }
37
38 /**
39 * Initialize from ASN.1.
40 */
41 public static function fromASN1(Sequence $seq): self
42 {
43 $targets = array_map(static fn (UnspecifiedType $el) => Target::fromASN1($el->asTagged()), $seq->elements());
44 return self::create(...$targets);
45 }
46
47 /**
48 * Get all targets.
49 *
50 * @return Target[]
51 */
52 public function all(): array
53 {
54 return $this->targets;
55 }
56
57 /**
58 * Get all name targets.
59 *
60 * @return Target[]
61 */
62 public function nameTargets(): array
63 {
64 return $this->allOfType(Target::TYPE_NAME);
65 }
66
67 /**
68 * Get all group targets.
69 *
70 * @return Target[]
71 */
72 public function groupTargets(): array
73 {
74 return $this->allOfType(Target::TYPE_GROUP);
75 }
76
77 /**
78 * Check whether given target is present.
79 */
80 public function hasTarget(Target $target): bool
81 {
82 foreach ($this->allOfType($target->type()) as $t) {
83 if ($target->equals($t)) {
84 return true;
85 }
86 }
87 return false;
88 }
89
90 /**
91 * Generate ASN.1 structure.
92 */
93 public function toASN1(): Sequence
94 {
95 $elements = array_map(static fn (Target $target) => $target->toASN1(), $this->targets);
96 return Sequence::create(...$elements);
97 }
98
99 /**
100 * @see \Countable::count()
101 */
102 public function count(): int
103 {
104 return count($this->targets);
105 }
106
107 /**
108 * Get iterator for targets.
109 *
110 * @see \IteratorAggregate::getIterator()
111 */
112 public function getIterator(): ArrayIterator
113 {
114 return new ArrayIterator($this->targets);
115 }
116
117 /**
118 * Get all targets of given type.
119 *
120 * @return Target[]
121 */
122 private function allOfType(int $type): array
123 {
124 return array_values(array_filter($this->targets, static fn (Target $target) => $target->type() === $type));
125 }
126 }