MockSocket.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * This class is used by tests to mock and track various socket/stream calls.
  4. */
  5. namespace WebSocket;
  6. class MockSocket
  7. {
  8. private static $queue = [];
  9. private static $stored = [];
  10. private static $asserter;
  11. // Handler called by function overloads in mock-socket.php
  12. public static function handle($function, $params = [])
  13. {
  14. $current = array_shift(self::$queue);
  15. if ($function == 'get_resource_type' && is_null($current)) {
  16. return null; // Catch destructors
  17. }
  18. self::$asserter->assertEquals($function, $current['function']);
  19. foreach ($current['params'] as $index => $param) {
  20. self::$asserter->assertEquals($param, $params[$index], json_encode([$current, $params]));
  21. }
  22. if (isset($current['return-op'])) {
  23. return self::op($current['return-op'], $params, $current['return']);
  24. }
  25. if (isset($current['return'])) {
  26. return $current['return'];
  27. }
  28. return call_user_func_array($function, $params);
  29. }
  30. // Check if all expected calls are performed
  31. public static function isEmpty()
  32. {
  33. return empty(self::$queue);
  34. }
  35. // Initialize call queue
  36. public static function initialize($op_file, $asserter)
  37. {
  38. $file = dirname(__DIR__) . "/scripts/{$op_file}.json";
  39. self::$queue = json_decode(file_get_contents($file), true);
  40. self::$asserter = $asserter;
  41. }
  42. // Special output handling
  43. private static function op($op, $params, $data)
  44. {
  45. switch ($op) {
  46. case 'chr-array':
  47. // Convert int array to string
  48. $out = '';
  49. foreach ($data as $val) {
  50. $out .= chr($val);
  51. }
  52. return $out;
  53. case 'file':
  54. $content = file_get_contents(__DIR__ . "/{$data[0]}");
  55. return substr($content, $data[1], $data[2]);
  56. case 'key-save':
  57. preg_match('#Sec-WebSocket-Key:\s(.*)$#mUi', $params[1], $matches);
  58. self::$stored['sec-websocket-key'] = trim($matches[1]);
  59. return $data;
  60. case 'key-respond':
  61. $key = self::$stored['sec-websocket-key'] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
  62. $encoded = base64_encode(pack('H*', sha1($key)));
  63. return str_replace('{key}', $encoded, $data);
  64. }
  65. return $data;
  66. }
  67. }