LZUtil16.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: sics
  5. * Date: 27.02.2016
  6. * Time: 15:54
  7. */
  8. namespace App\Game\Services\LZCompressor;
  9. class LZUtil16
  10. {
  11. /**
  12. * @return string
  13. */
  14. public static function fromCharCode()
  15. {
  16. return array_reduce(func_get_args(), function ($a, $b) {
  17. $a .= self::utf16_chr($b);
  18. return $a;
  19. });
  20. }
  21. /**
  22. * Phps chr() equivalent for UTF-16 encoding
  23. *
  24. * @param int|string $u
  25. * @return string
  26. */
  27. public static function utf16_chr($u)
  28. {
  29. return mb_convert_encoding('&#' . intval($u) . ';', 'UTF-16', 'HTML-ENTITIES');
  30. }
  31. /**
  32. * @param string $str
  33. * @param int $num
  34. *
  35. * @return bool|integer
  36. */
  37. public static function charCodeAt($data)
  38. {
  39. $sub = substr($data->str, $data->index, 2);
  40. $sub = self::utf16_charAt($sub, 0);
  41. $data->index += strlen($sub);
  42. $data->end = strlen($sub) <= 0;
  43. return self::utf16_ord($sub);
  44. }
  45. /**
  46. * @source http://blog.sarabande.jp/post/35970262740
  47. * @param string $ch
  48. * @return bool|integer
  49. */
  50. public static function utf16_ord($ch) {
  51. $length = strlen($ch);
  52. if (2 === $length) {
  53. return hexdec(bin2hex($ch));
  54. } else if (4 === $length) {
  55. $w1 = $ch[0].$ch[1];
  56. $w2 = $ch[2].$ch[3];
  57. if ($w1 < "\xD8\x00" || "\xDF\xFF" < $w1 || $w2 < "\xDC\x00" || "\xDF\xFF" < $w2) {
  58. return false;
  59. }
  60. $w1 = (hexdec(bin2hex($w1)) & 0x3ff) << 10;
  61. $w2 = hexdec(bin2hex($w2)) & 0x3ff;
  62. return $w1 + $w2 + 0x10000;
  63. }
  64. return false;
  65. }
  66. /**
  67. * @param string $str
  68. * @param integer $num
  69. *
  70. * @return string
  71. */
  72. public static function utf16_charAt($str, $num)
  73. {
  74. return mb_substr($str, $num, 1, 'UTF-16');
  75. }
  76. /**
  77. * @param string $str
  78. * @return integer
  79. */
  80. public static function utf16_strlen($str)
  81. {
  82. return mb_strlen($str, 'UTF-16');
  83. }
  84. }