TokensTest.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. <?php
  2. declare(strict_types=1);
  3. namespace JsonMachineTest;
  4. use JsonMachine\FileChunks;
  5. use JsonMachine\StreamChunks;
  6. use JsonMachine\StringChunks;
  7. use JsonMachine\Tokens;
  8. use JsonMachine\TokensWithDebugging;
  9. /**
  10. * @covers \JsonMachine\Tokens
  11. * @covers \JsonMachine\TokensWithDebugging
  12. */
  13. class TokensTest extends \PHPUnit_Framework_TestCase
  14. {
  15. public function bothDebugModes()
  16. {
  17. return [
  18. 'debug enabled' => [TokensWithDebugging::class],
  19. 'debug disabled' => [Tokens::class],
  20. ];
  21. }
  22. /**
  23. * @dataProvider bothDebugModes
  24. */
  25. public function testCorrectlyYieldsZeroToken($tokensClass)
  26. {
  27. $data = ['0'];
  28. $expected = ['0'];
  29. $this->assertEquals($expected, iterator_to_array(new $tokensClass(new \ArrayIterator($data))));
  30. $stream = fopen('data://text/plain,{"value":0}', 'r');
  31. $expected = ['{', '"value"', ':', '0', '}'];
  32. $this->assertEquals($expected, iterator_to_array(new $tokensClass(new StreamChunks($stream, 10))));
  33. }
  34. /**
  35. * @dataProvider bothDebugModes
  36. */
  37. public function testGeneratesTokens($tokensClass)
  38. {
  39. $data = ['{}[],:null,"string" false:', 'true,1,100000,1.555{-56]"","\\""'];
  40. $expected = ['{', '}', '[', ']', ',', ':', 'null', ',', '"string"', 'false', ':', 'true', ',', '1', ',', '100000', ',', '1.555', '{', '-56', ']', '""', ',', '"\\""'];
  41. $this->assertEquals($expected, iterator_to_array(new $tokensClass(new \ArrayIterator($data))));
  42. }
  43. /**
  44. * @dataProvider bothDebugModes
  45. */
  46. public function testWithBOM($tokensClass)
  47. {
  48. $data = ["\xEF\xBB\xBF".'{}'];
  49. $expected = ['{', '}'];
  50. $this->assertEquals($expected, iterator_to_array(new $tokensClass(new \ArrayIterator($data))));
  51. }
  52. /**
  53. * @dataProvider bothDebugModes
  54. */
  55. public function testCorrectlyParsesTwoBackslashesAtTheEndOfAString($tokensClass)
  56. {
  57. $this->assertEquals(['"test\\\\"', ':'], iterator_to_array(new $tokensClass(new \ArrayIterator(['"test\\\\":']))));
  58. }
  59. /**
  60. * @dataProvider bothDebugModes
  61. */
  62. public function testCorrectlyParsesEscapedQuotesInTheMiddleOfAString($tokensClass)
  63. {
  64. $json = '"test\"test":';
  65. $expected = ['"test\"test"', ':'];
  66. $this->assertEquals($expected, iterator_to_array(new $tokensClass(new \ArrayIterator([$json]))));
  67. }
  68. /**
  69. * @dataProvider bothDebugModes
  70. */
  71. public function testCorrectlyParsesChunksSplitBeforeStringEnd($tokensClass)
  72. {
  73. $chunks = ['{"path": {"key":"value', '"}}'];
  74. $expected = ['{', '"path"', ':', '{', '"key"', ':', '"value"', '}', '}'];
  75. $this->assertEquals($expected, iterator_to_array(new $tokensClass(new \ArrayIterator($chunks))));
  76. }
  77. /**
  78. * @dataProvider bothDebugModes
  79. */
  80. public function testCorrectlyParsesChunksSplitBeforeEscapedCharacter($tokensClass)
  81. {
  82. $chunks = ['{"path": {"key":"value\\', '""}}'];
  83. $expected = ['{', '"path"', ':', '{', '"key"', ':', '"value\""', '}', '}'];
  84. $this->assertEquals($expected, iterator_to_array(new $tokensClass(new \ArrayIterator($chunks))));
  85. }
  86. /**
  87. * @dataProvider bothDebugModes
  88. */
  89. public function testCorrectlyParsesChunksSplitAfterEscapedCharacter($tokensClass)
  90. {
  91. $chunks = ['{"path": {"key":"value\\"', '"}}'];
  92. $expected = ['{', '"path"', ':', '{', '"key"', ':', '"value\""', '}', '}'];
  93. $this->assertEquals($expected, iterator_to_array(new $tokensClass(new \ArrayIterator($chunks))));
  94. }
  95. /**
  96. * @dataProvider bothDebugModes
  97. */
  98. public function testAnyPossibleChunkSplit($tokensClass)
  99. {
  100. $json = '
  101. {
  102. "datafeed": {
  103. "info": {
  104. "category": "Category name"
  105. },
  106. "programs": [
  107. {
  108. "program_info": {
  109. "id": "X0\"\\\\",
  110. "number": 123,
  111. "constant": false
  112. }
  113. },
  114. {
  115. "program_info": {
  116. "id": "\b\f\n\r\t\u0020X1"
  117. }
  118. }
  119. ]
  120. }
  121. }
  122. ';
  123. $expected = [
  124. '{', '"datafeed"', ':', '{', '"info"', ':', '{', '"category"', ':', '"Category name"', '}', ',',
  125. '"programs"', ':', '[', '{', '"program_info"', ':', '{', '"id"', ':', '"X0\\"\\\\"', ',', '"number"', ':',
  126. '123', ',', '"constant"', ':', 'false', '}', '}', ',', '{', '"program_info"', ':', '{', '"id"', ':',
  127. '"\b\f\n\r\t\u0020X1"', '}', '}', ']', '}', '}',
  128. ];
  129. foreach (range(1, strlen($json)) as $chunkLength) {
  130. $chunks = str_split($json, $chunkLength);
  131. $result = iterator_to_array(new $tokensClass($chunks));
  132. $this->assertSame($expected, $result);
  133. }
  134. }
  135. /**
  136. * @dataProvider jsonFilesWithDifferentLineEndings
  137. */
  138. public function testProvidesLocationalDataWhenDebugEnabled(string $jsonFilePath)
  139. {
  140. $jsonFileContents = file_get_contents($jsonFilePath);
  141. $tokens = new TokensWithDebugging(new StringChunks($jsonFileContents));
  142. $expectedTokens = $this->expectedTokens();
  143. $i = 0;
  144. foreach ($tokens as $token) {
  145. ++$i;
  146. $expectedToken = array_shift($expectedTokens);
  147. $this->assertEquals($expectedToken[0], $token, 'token failed with expected token #'.$i);
  148. $this->assertEquals($expectedToken[1], $tokens->getLine(), 'line failed with expected token #'.$i);
  149. $this->assertEquals($expectedToken[2], $tokens->getColumn(), 'column failed with expected token #'.$i);
  150. }
  151. }
  152. /**
  153. * @dataProvider jsonFilesWithDifferentLineEndings
  154. */
  155. public function testProvidesLocationalDataWhenDebugDisabled(string $jsonFilePath)
  156. {
  157. $tokens = new Tokens(new FileChunks($jsonFilePath));
  158. $expectedTokens = $this->expectedTokens();
  159. $i = 0;
  160. foreach ($tokens as $token) {
  161. ++$i;
  162. $expectedToken = array_shift($expectedTokens);
  163. $this->assertEquals($expectedToken[0], $token, 'token failed with expected token #'.$i);
  164. $this->assertEquals(1, $tokens->getLine(), 'line failed with expected token #'.$i);
  165. $this->assertEquals(0, $tokens->getColumn(), 'column failed with expected token #'.$i);
  166. }
  167. }
  168. public function testGetPositionWthDebugging()
  169. {
  170. $tokens = new TokensWithDebugging(['[ 1, "two", false ]']);
  171. $expectedPosition = [1, 5, 6, 12, 13, 19, 21];
  172. $this->assertSame(0, $tokens->getPosition());
  173. foreach ($tokens as $index => $item) {
  174. $this->assertSame($expectedPosition[$index], $tokens->getPosition(), "index:$index, item:$item");
  175. }
  176. $this->assertSame(21, $tokens->getPosition());
  177. }
  178. public function testGetPositionNoDebugging()
  179. {
  180. $tokens = new Tokens(['[ 1, "two", false ]']);
  181. $this->assertSame(0, $tokens->getPosition());
  182. foreach ($tokens as $index => $item) {
  183. $this->assertSame(0, $tokens->getPosition(), "index:$index, item:$item");
  184. }
  185. $this->assertSame(0, $tokens->getPosition());
  186. }
  187. public function jsonFilesWithDifferentLineEndings()
  188. {
  189. return [
  190. 'cr new lines' => [__DIR__.'/formatted-cr.json'],
  191. 'lf new lines' => [__DIR__.'/formatted-lf.json'],
  192. 'crlf new lines' => [__DIR__.'/formatted-crlf.json'],
  193. ];
  194. }
  195. private function expectedTokens()
  196. {
  197. return [
  198. // lexeme, line, column
  199. ['{', 1, 1],
  200. ['"id"', 2, 3],
  201. [':', 2, 7],
  202. ['54640519019642880', 2, 9],
  203. [',', 2, 26],
  204. ['"user"', 3, 3],
  205. [':', 3, 9],
  206. ['{', 3, 11],
  207. ['"notifications"', 4, 5],
  208. [':', 4, 20],
  209. ['null', 4, 22],
  210. ['}', 5, 3],
  211. [',', 5, 4],
  212. ['"geo"', 6, 3],
  213. [':', 6, 8],
  214. ['"test"', 6, 10],
  215. ['}', 7, 1],
  216. ];
  217. }
  218. }