|
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
|
|
|
* ASN.1 type of the string. |
|
20
|
|
|
* |
|
21
|
|
|
* @var int |
|
22
|
|
|
*/ |
|
23
|
|
|
protected $_type; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Constructor. |
|
27
|
|
|
* |
|
28
|
|
|
* @param int $type ASN.1 type tag of the string |
|
29
|
|
|
*/ |
|
30
|
58 |
|
public function __construct(int $type) |
|
31
|
|
|
{ |
|
32
|
58 |
|
$this->_type = $type; |
|
33
|
58 |
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* @param string $string String to prepare |
|
37
|
|
|
* |
|
38
|
|
|
* @throws \LogicException If string type is not supported |
|
39
|
|
|
* |
|
40
|
|
|
* @return string UTF-8 encoded string |
|
41
|
|
|
*/ |
|
42
|
58 |
|
public function apply(string $string): string |
|
43
|
|
|
{ |
|
44
|
58 |
|
switch ($this->_type) { |
|
45
|
|
|
// UTF-8 string as is |
|
46
|
|
|
case Element::TYPE_UTF8_STRING: |
|
47
|
51 |
|
return $string; |
|
48
|
|
|
// PrintableString maps directly to UTF-8 |
|
49
|
|
|
case Element::TYPE_PRINTABLE_STRING: |
|
50
|
2 |
|
return $string; |
|
51
|
|
|
// UCS-2 to UTF-8 |
|
52
|
|
|
case Element::TYPE_BMP_STRING: |
|
53
|
1 |
|
return mb_convert_encoding($string, 'UTF-8', 'UCS-2BE'); |
|
54
|
|
|
// UCS-4 to UTF-8 |
|
55
|
|
|
case Element::TYPE_UNIVERSAL_STRING: |
|
56
|
1 |
|
return mb_convert_encoding($string, 'UTF-8', 'UCS-4BE'); |
|
57
|
|
|
// TeletexString mapping is a local matter. |
|
58
|
|
|
// We take a shortcut here and encode it as a hexstring. |
|
59
|
|
|
case Element::TYPE_T61_STRING: |
|
60
|
2 |
|
$el = new T61String($string); |
|
61
|
2 |
|
return '#' . bin2hex($el->toDER()); |
|
62
|
|
|
} |
|
63
|
1 |
|
throw new \LogicException( |
|
64
|
1 |
|
'Unsupported string type ' . Element::tagToName($this->_type) . '.'); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|