Debian Codegraph @

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

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace SpomkyLabs\Pki\X509\Certificate\Extension;
6
7 use LogicException;
8 use SpomkyLabs\Pki\ASN1\Element;
9 use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
10 use SpomkyLabs\Pki\ASN1\Type\Primitive\Boolean;
11 use SpomkyLabs\Pki\ASN1\Type\Primitive\Integer;
12 use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
13
14 /**
15 * Implements 'Basic Constraints' certificate extension.
16 *
17 * @see https://tools.ietf.org/html/rfc5280#section-4.2.1.9
18 */
19 final class BasicConstraintsExtension extends Extension
20 {
21 /**
22 * @param bool $ca Whether certificate is a CA.
23 * @param int|null $pathLen Maximum certification path length.
24 */
25 private function __construct(
26 bool $critical,
27 private readonly bool $ca,
28 private readonly ?int $pathLen
29 ) {
30 parent::__construct(self::OID_BASIC_CONSTRAINTS, $critical);
31 }
32
33 public static function create(bool $critical, bool $ca, ?int $pathLen = null): self
34 {
35 return new self($critical, $ca, $pathLen);
36 }
37
38 /**
39 * Whether certificate is a CA.
40 */
41 public function isCA(): bool
42 {
43 return $this->ca;
44 }
45
46 /**
47 * Whether path length is present.
48 */
49 public function hasPathLen(): bool
50 {
51 return isset($this->pathLen);
52 }
53
54 /**
55 * Get path length.
56 */
57 public function pathLen(): int
58 {
59 if (! $this->hasPathLen()) {
60 throw new LogicException('pathLenConstraint not set.');
61 }
62 return $this->pathLen;
63 }
64
65 protected static function fromDER(string $data, bool $critical): static
66 {
67 $seq = UnspecifiedType::fromDER($data)->asSequence();
68 $ca = false;
69 $path_len = null;
70 $idx = 0;
71 if ($seq->has($idx, Element::TYPE_BOOLEAN)) {
72 $ca = $seq->at($idx++)
73 ->asBoolean()
74 ->value();
75 }
76 if ($seq->has($idx, Element::TYPE_INTEGER)) {
77 $path_len = $seq->at($idx)
78 ->asInteger()
79 ->intNumber();
80 }
81 return self::create($critical, $ca, $path_len);
82 }
83
84 protected function valueASN1(): Element
85 {
86 $elements = [];
87 if ($this->ca) {
88 $elements[] = Boolean::create(true);
89 }
90 if (isset($this->pathLen)) {
91 $elements[] = Integer::create($this->pathLen);
92 }
93 return Sequence::create(...$elements);
94 }
95 }