Debian Codegraph @

lib/3rdParty/composer/spomky-labs/pki-framework/src/X501/StringPrep/TranscodeStep.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace SpomkyLabs\Pki\X501\StringPrep;
6
7 use function in_array;
8 use LogicException;
9 use SpomkyLabs\Pki\ASN1\Element;
10 use SpomkyLabs\Pki\ASN1\Type\Primitive\T61String;
11 use function sprintf;
12
13 /**
14 * Implements 'Transcode' step of the Internationalized String Preparation as specified by RFC 4518.
15 *
16 * @see https://tools.ietf.org/html/rfc4518#section-2.1
17 */
18 final class TranscodeStep implements PrepareStep
19 {
20 /**
21 * Supported ASN.1 types.
22 *
23 * @var array<int>
24 */
25 private const SUPPORTED_TYPES = [
26 Element::TYPE_UTF8_STRING,
27 Element::TYPE_PRINTABLE_STRING,
28 Element::TYPE_BMP_STRING,
29 Element::TYPE_UNIVERSAL_STRING,
30 Element::TYPE_T61_STRING,
31 ];
32
33 /**
34 * @param int $_type ASN.1 type tag of the string
35 */
36 private function __construct(
37 private readonly int $_type
38 ) {
39 }
40
41 public static function create(int $_type): self
42 {
43 return new self($_type);
44 }
45
46 /**
47 * Check whether transcoding from given ASN.1 type tag is supported.
48 *
49 * @param int $type ASN.1 type tag
50 */
51 public static function isTypeSupported(int $type): bool
52 {
53 return in_array($type, self::SUPPORTED_TYPES, true);
54 }
55
56 /**
57 * @param string $string String to prepare
58 *
59 * @return string UTF-8 encoded string
60 */
61 public function apply(string $string): string
62 {
63 switch ($this->_type) {
64 // UTF-8 string as is
65 case Element::TYPE_UTF8_STRING:
66 // PrintableString maps directly to UTF-8
67 case Element::TYPE_PRINTABLE_STRING:
68 return $string;
69 // UCS-2 to UTF-8
70 case Element::TYPE_BMP_STRING:
71 return mb_convert_encoding($string, 'UTF-8', 'UCS-2BE');
72 // UCS-4 to UTF-8
73 case Element::TYPE_UNIVERSAL_STRING:
74 return mb_convert_encoding($string, 'UTF-8', 'UCS-4BE');
75 // TeletexString mapping is a local matter.
76 // We take a shortcut here and encode it as a hexstring.
77 case Element::TYPE_T61_STRING:
78 $el = T61String::create($string);
79 return '#' . bin2hex($el->toDER());
80 }
81 throw new LogicException(sprintf('Unsupported string type %s.', Element::tagToName($this->_type)));
82 }
83 }