| 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 |
|
| 18 |
|
| 19 |
final class CertificateChain implements Countable, IteratorAggregate |
| 20 |
{ |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
private readonly array $certs; |
| 27 |
|
| 28 |
|
| 29 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
public function certificates(): array |
| 65 |
{ |
| 66 |
return $this->certs; |
| 67 |
} |
| 68 |
|
| 69 |
|
| 70 |
|
| 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 |
|
| 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 |
|
| 93 |
|
| 94 |
public function certificationPath(): CertificationPath |
| 95 |
{ |
| 96 |
return CertificationPath::fromCertificateChain($this); |
| 97 |
} |
| 98 |
|
| 99 |
|
| 100 |
|
| 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 |
|
| 109 |
|
| 110 |
public function count(): int |
| 111 |
{ |
| 112 |
return count($this->certs); |
| 113 |
} |
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
public function getIterator(): ArrayIterator |
| 121 |
{ |
| 122 |
return new ArrayIterator($this->certs); |
| 123 |
} |
| 124 |
} |