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