Encoder.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace PHPSocketIO\Parser;
  3. use \PHPSocketIO\Parser\Parser;
  4. use \PHPSocketIO\Event\Emitter;
  5. use \PHPSocketIO\Debug;
  6. class Encoder extends Emitter
  7. {
  8. public function __construct()
  9. {
  10. Debug::debug('Encoder __construct');
  11. }
  12. public function __destruct()
  13. {
  14. Debug::debug('Encoder __destruct');
  15. }
  16. public function encode($obj)
  17. {
  18. if(Parser::BINARY_EVENT == $obj['type'] || Parser::BINARY_ACK == $obj['type'])
  19. {
  20. echo new \Exception("not support BINARY_EVENT BINARY_ACK");
  21. return array();
  22. }
  23. else
  24. {
  25. $encoding = self::encodeAsString($obj);
  26. return array($encoding);
  27. }
  28. }
  29. public static function encodeAsString($obj) {
  30. $str = '';
  31. $nsp = false;
  32. // first is type
  33. $str .= $obj['type'];
  34. // attachments if we have them
  35. if (Parser::BINARY_EVENT == $obj['type'] || Parser::BINARY_ACK == $obj['type'])
  36. {
  37. $str .= $obj['attachments'];
  38. $str .= '-';
  39. }
  40. // if we have a namespace other than `/`
  41. // we append it followed by a comma `,`
  42. if (!empty($obj['nsp']) && '/' !== $obj['nsp'])
  43. {
  44. $nsp = true;
  45. $str .= $obj['nsp'];
  46. }
  47. // immediately followed by the id
  48. if (isset($obj['id']))
  49. {
  50. if($nsp)
  51. {
  52. $str .= ',';
  53. $nsp = false;
  54. }
  55. $str .= $obj['id'];
  56. }
  57. // json data
  58. if(isset($obj['data']))
  59. {
  60. if ($nsp) $str .= ',';
  61. $str .= json_encode($obj['data']);
  62. }
  63. return $str;
  64. }
  65. }