Debian Codegraph @

lib/3rdParty/composer/spomky-labs/pki-framework/src/X509/Certificate/CertificateChain.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace SpomkyLabs\Pki\X509\Certificate;
6
7 use ArrayIterator;
8 use function count;
9 use Countable;
10 use IteratorAggregate;
11 use LogicException;
12 use SpomkyLabs\Pki\CryptoEncoding\PEM;
13 use SpomkyLabs\Pki\CryptoEncoding\PEMBundle;
14 use SpomkyLabs\Pki\X509\CertificationPath\CertificationPath;
15
16 /**
17 * Ordered list of certificates from the end-entity to the trust anchor.
18 */
19 final class CertificateChain implements Countable, IteratorAggregate
20 {
21 /**
22 * List of certificates in a chain.
23 *
24 * @var Certificate[]
25 */
26 private readonly array $certs;
27
28 /**
29 * @param Certificate ...$certs List of certificates, end-entity first
30 */
31 private function __construct(Certificate ...$certs)
32 {
33 $this->certs = $certs;
34 }
35
36 public static function create(Certificate ...$certs): self
37 {
38 return new self(...$certs);
39 }
40
41 /**
42 * Initialize from a list of PEMs.
43 */
44 public static function fromPEMs(PEM ...$pems): self
45 {
46 $certs = array_map(Certificate::fromPEM(...), $pems);
47 return self::create(...$certs);
48 }
49
50 /**
51 * Initialize from a string containing multiple PEM blocks.
52 */
53 public static function fromPEMString(string $str): self
54 {
55 $pems = PEMBundle::fromString($str)->all();
56 return self::fromPEMs(...$pems);
57 }
58
59 /**
60 * Get all certificates in a chain ordered from the end-entity certificate to the trust anchor.
61 *
62 * @return Certificate[]
63 */
64 public function certificates(): array
65 {
66 return $this->certs;
67 }
68
69 /**
70 * Get the end-entity certificate.
71 */
72 public function endEntityCertificate(): Certificate
73 {
74 if (count($this->certs) === 0) {
75 throw new LogicException('No certificates.');
76 }
77 return $this->certs[0];
78 }
79
80 /**
81 * Get the trust anchor certificate.
82 */
83 public function trustAnchorCertificate(): Certificate
84 {
85 if (count($this->certs) === 0) {
86 throw new LogicException('No certificates.');
87 }
88 return $this->certs[count($this->certs) - 1];
89 }
90
91 /**
92 * Convert certificate chain to certification path.
93 */
94 public function certificationPath(): CertificationPath
95 {
96 return CertificationPath::fromCertificateChain($this);
97 }
98
99 /**
100 * Convert certificate chain to string of PEM blocks.
101 */
102 public function toPEMString(): string
103 {
104 return implode("\n", array_map(static fn (Certificate $cert) => $cert->toPEM()->string(), $this->certs));
105 }
106
107 /**
108 * @see \Countable::count()
109 */
110 public function count(): int
111 {
112 return count($this->certs);
113 }
114
115 /**
116 * Get iterator for certificates.
117 *
118 * @see \IteratorAggregate::getIterator()
119 */
120 public function getIterator(): ArrayIterator
121 {
122 return new ArrayIterator($this->certs);
123 }
124 }