| 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 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
final class TranscodeStep implements PrepareStep |
| 19 |
{ |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 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 |
|
| 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 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
public static function isTypeSupported(int $type): bool |
| 52 |
{ |
| 53 |
return in_array($type, self::SUPPORTED_TYPES, true); |
| 54 |
} |
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
public function apply(string $string): string |
| 62 |
{ |
| 63 |
switch ($this->_type) { |
| 64 |
|
| 65 |
case Element::TYPE_UTF8_STRING: |
| 66 |
|
| 67 |
case Element::TYPE_PRINTABLE_STRING: |
| 68 |
return $string; |
| 69 |
|
| 70 |
case Element::TYPE_BMP_STRING: |
| 71 |
return mb_convert_encoding($string, 'UTF-8', 'UCS-2BE'); |
| 72 |
|
| 73 |
case Element::TYPE_UNIVERSAL_STRING: |
| 74 |
return mb_convert_encoding($string, 'UTF-8', 'UCS-4BE'); |
| 75 |
|
| 76 |
|
| 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 |
} |