bootstrap.php 0000644 00000000334 15025063511 0007270 0 ustar 00 createParser($json, $jsonPointer) as $key => $value) {
$result[] = [$key => $value];
}
$this->assertSame($expectedResult, $result);
}
public function data_testSyntax()
{
return [
['', '{}', []],
['', '{"a": "b"}', [['a' => 'b']]],
['', '{"a":{"b":{"c":1}}}', [['a' => ['b' => ['c' => 1]]]]],
['', '[]', []],
['', '[null,true,false,"a",0,1,42.5]', [[0 => null], [1 => true], [2 => false], [3 => 'a'], [4 => 0], [5 => 1], [6 => 42.5]]],
['', '[{"c":1}]', [[['c' => 1]]]],
['', '[{"c":1},"string",{"d":2},false]', [[0 => ['c' => 1]], [1 => 'string'], [2 => ['d' => 2]], [3 => false]]],
['', '[false,{"c":1},"string",{"d":2}]', [[0 => false], [1 => ['c' => 1]], [2 => 'string'], [3 => ['d' => 2]]]],
['', '[{"c":1,"d":2}]', [[['c' => 1, 'd' => 2]]]],
['/', '{"":{"c":1,"d":2}}', [['c' => 1], ['d' => 2]]],
['/~0', '{"~":{"c":1,"d":2}}', [['c' => 1], ['d' => 2]]],
['/~1', '{"/":{"c":1,"d":2}}', [['c' => 1], ['d' => 2]]],
['/~01', '{"~1":{"c":1,"d":2}}', [['c' => 1], ['d' => 2]]],
['/~00', '{"~0":{"c":1,"d":2}}', [['c' => 1], ['d' => 2]]],
['/path', '{"path":{"c":1,"d":2}}', [['c' => 1], ['d' => 2]]],
['/path', '{"no":[null], "path":{"c":1,"d":2}}', [['c' => 1], ['d' => 2]]],
['/0', '[{"c":1,"d":2}, [null]]', [['c' => 1], ['d' => 2]]],
['/0/path', '[{"path":{"c":1,"d":2}}]', [['c' => 1], ['d' => 2]]],
['/1/path', '[[null], {"path":{"c":1,"d":2}}]', [['c' => 1], ['d' => 2]]],
['/path/0', '{"path":[{"c":1,"d":2}, [null]]}', [['c' => 1], ['d' => 2]]],
['/path/1', '{"path":[null,{"c":1,"d":2}, [null]]}', [['c' => 1], ['d' => 2]]],
['/path/to', '{"path":{"to":{"c":1,"d":2}}}', [['c' => 1], ['d' => 2]]],
['/path/after-vector', '{"path":{"array":[],"after-vector":{"c":1,"d":2}}}', [['c' => 1], ['d' => 2]]],
['/path/after-vector', '{"path":{"array":["item"],"after-vector":{"c":1,"d":2}}}', [['c' => 1], ['d' => 2]]],
['/path/after-vector', '{"path":{"object":{"item":null},"after-vector":{"c":1,"d":2}}}', [['c' => 1], ['d' => 2]]],
['/path/after-vectors', '{"path":{"array":[],"object":{},"after-vectors":{"c":1,"d":2}}}', [['c' => 1], ['d' => 2]]],
['/0/0', '[{"0":{"c":1,"d":2}}]', [['c' => 1], ['d' => 2]]],
['/1/1', '[0,{"1":{"c":1,"d":2}}]', [['c' => 1], ['d' => 2]]],
'PR-19-FIX' => ['/datafeed/programs/1', file_get_contents(__DIR__.'/PR-19-FIX.json'), [['program_info' => ['id' => 'X1']]]],
'ISSUE-41-FIX' => ['/path', '{"path":[{"empty":{}},{"value":1}]}', [[['empty' => []]], [1 => ['value' => 1]]]],
['/-', '[{"one": 1,"two": 2},{"three": 3,"four": 4}]', [['one' => 1], ['two' => 2], ['three' => 3], ['four' => 4]]],
['/zero/-', '{"zero":[{"one": 1,"two": 2},{"three": 3,"four": 4}]}', [['one' => 1], ['two' => 2], ['three' => 3], ['four' => 4]]],
['/zero/-/three', '{"zero":[{"one": 1,"two": 2},{"three": 3,"four": 4}]}', [['three' => 3]]],
'ISSUE-62#1' => ['/-/id', '[ {"id":125}, {"id":785}, {"id":459}, {"id":853} ]', [['id' => 125], ['id' => 785], ['id' => 459], ['id' => 853]]],
'ISSUE-62#2' => ['/key/-/id', '{"key": [ {"id":125}, {"id":785}, {"id":459}, {"id":853} ]}', [['id' => 125], ['id' => 785], ['id' => 459], ['id' => 853]]],
[
['/meta_data', '/data/companies'],
'{"meta_data": {"total_rows": 2},"data": {"type": "companies","companies": [{"id": "1","company": "Company 1"},{"id": "2","company": "Company 2"}]}}',
[
['total_rows' => 2],
['0' => ['id' => '1', 'company' => 'Company 1']],
['1' => ['id' => '2', 'company' => 'Company 2']],
],
],
[
['/-/id', '/-/company'],
'[{"id": "1","company": "Company 1"},{"id": "2","company": "Company 2"}]',
[
['id' => '1'],
['company' => 'Company 1'],
['id' => '2'],
['company' => 'Company 2'],
],
],
[
['/-/id', '/0/company'],
'[{"id": "1","company": "Company 1"},{"id": "2","company": "Company 2"}]',
[
['id' => '1'],
['company' => 'Company 1'],
['id' => '2'],
],
],
];
}
/**
* @dataProvider data_testThrowsOnNotFoundJsonPointer
*
* @param string $json
* @param string $jsonPointer
*/
public function testThrowsOnNotFoundJsonPointer($json, $jsonPointer)
{
$parser = $this->createParser($json, $jsonPointer);
$this->expectException(PathNotFoundException::class);
$this->expectExceptionMessage("Paths '".implode(', ', (array) $jsonPointer)."' were not found in json stream.");
iterator_to_array($parser);
}
public function data_testThrowsOnNotFoundJsonPointer()
{
return [
'non existing pointer' => ['{}', '/not/found'],
"empty string should not match '0'" => ['{"0":[]}', '/'],
'empty string should not match 0' => ['[[]]', '/'],
'0 should not match empty string' => ['{"":[]}', '/0'],
];
}
/**
* @dataProvider data_testSyntaxError
*
* @param string $malformedJson
*/
public function testSyntaxError($malformedJson)
{
$this->expectException(SyntaxErrorException::class);
iterator_to_array($this->createParser($malformedJson));
}
public function data_testSyntaxError()
{
return [
['[}'],
['{]'],
['null'],
['true'],
['false'],
['0'],
['100'],
['"string"'],
['}'],
[']'],
[','],
[':'],
[''],
['[null null]'],
['["string" "string"]'],
['[,"string","string"]'],
['["string",,"string"]'],
['["string","string",]'],
['["string",1eeee1]'],
['{"key\u000Z": "non hex key"}'],
];
}
/**
* @dataProvider data_testUnexpectedEndError
*
* @param string $malformedJson
*/
public function testUnexpectedEndError($malformedJson)
{
$this->expectException(UnexpectedEndSyntaxErrorException::class);
iterator_to_array($this->createParser($malformedJson));
}
public function data_testUnexpectedEndError()
{
return [
['['],
['{'],
['["string"'],
['["string",'],
['[{"string":"string"}'],
['[{"string":"string"},'],
['[{"string":"string"},{'],
['[{"string":"string"},{"str'],
['[{"string":"string"},{"string"'],
['{"string"'],
['{"string":'],
['{"string":"string"'],
['{"string":["string","string"]'],
['{"string":["string","string"'],
['{"string":["string","string",'],
['{"string":["string","string","str'],
];
}
public function testGeneratorQuitsAfterFirstFoundCollectionHasBeenFinished()
{
$json = '
{
"results": [1],
"other": [2],
"results": [3]
}
';
$parser = $this->createParser($json, '/results');
$this->assertSame([1], iterator_to_array($parser));
}
public function testScalarResult()
{
$result = $this->createParser('{"result":{"items": [1,2,3],"count": 3}}', '/result/count');
$this->assertSame([3], iterator_to_array($result));
}
public function testScalarResultInArray()
{
$result = $this->createParser('{"result":[1,2,3]}', '/result/0');
$this->assertSame([1], iterator_to_array($result));
}
public function testGeneratorQuitsAfterFirstScalarHasBeenFound()
{
$json = '
{
"result": "one",
"other": [2],
"result": "three"
}
';
$parser = $this->createParser($json, '/result');
$this->assertSame(['result' => 'one'], iterator_to_array($parser));
}
public function testGeneratorYieldsNestedValues()
{
$json = '
{
"zero": [
{
"one": "ignored",
"two": [
{
"three": 1
}
],
"four": [
{
"five": "ignored"
}
]
},
{
"one": 1,
"two": [
{
"three": 2
},
{
"three": 3
}
],
"four": [
{
"five": "ignored"
}
]
}
]
}
';
$parser = $this->createParser($json, '/zero/-/two/-/three');
$i = 0;
$expectedKey = 'three';
$expectedValues = [1, 2, 3];
foreach ($parser as $key => $value) {
$this->assertSame($expectedKey, $key);
$this->assertSame($expectedValues[$i++], $value);
}
}
private function createParser($json, $jsonPointer = '')
{
return new Parser(new Tokens(new \ArrayIterator([$json])), $jsonPointer, new ExtJsonDecoder(true));
}
public function testDefaultDecodingStructureIsObject()
{
$items = new Parser(new Tokens(new StringChunks('[{"key": "value"}]')));
foreach ($items as $item) {
$this->assertEquals((object) ['key' => 'value'], $item);
}
}
/**
* @dataProvider data_testGetCurrentJsonPointer
*/
public function testGetCurrentJsonPointer($jsonPointer, string $json, array $currentJsonPointers)
{
$parser = $this->createParser($json, $jsonPointer);
$i = 0;
foreach ($parser as $value) {
$this->assertEquals($currentJsonPointers[$i++], $parser->getCurrentJsonPointer());
}
}
public function data_testGetCurrentJsonPointer()
{
return [
['', '{"c":1,"d":2}', ['', '']],
['/', '{"":{"c":1,"d":2}}', ['/', '/']],
['/~0', '{"~":{"c":1,"d":2}}', ['/~0', '/~0']],
['/~1', '{"/":{"c":1,"d":2}}', ['/~1', '/~1']],
['/~01', '{"~1":{"c":1,"d":2}}', ['/~01', '/~01']],
['/~00', '{"~0":{"c":1,"d":2}}', ['/~00', '/~00']],
['/~1/c', '{"/":{"c":[1,2],"d":2}}', ['/~1/c', '/~1/c']],
['/0', '[{"c":1,"d":2}, [null]]', ['/0', '/0']],
['/-', '[{"one": 1,"two": 2},{"three": 3,"four": 4}]', ['/0', '/0', '/1', '/1']],
[
['/two', '/four'],
'{"one": [1,11], "two": [2,22], "three": [3,33], "four": [4,44]}',
['/two', '/two', '/four', '/four'],
],
[
['/-/two', '/-/one'],
'[{"one": 1, "two": 2}, {"one": 1, "two": 2}]',
['/0/one', '/0/two', '/1/one', '/1/two'],
],
];
}
/**
* @dataProvider data_testGetMatchedJsonPointer
*/
public function testGetMatchedJsonPointer($jsonPointer, string $json, array $matchedJsonPointers)
{
$parser = $this->createParser($json, $jsonPointer);
$i = 0;
foreach ($parser as $value) {
$this->assertEquals($matchedJsonPointers[$i++], $parser->getMatchedJsonPointer());
}
}
public function data_testGetMatchedJsonPointer()
{
return [
['', '{"c":1,"d":2}', ['', '']],
['/', '{"":{"c":1,"d":2}}', ['/', '/']],
['/~0', '{"~":{"c":1,"d":2}}', ['/~0', '/~0']],
['/~1', '{"/":{"c":1,"d":2}}', ['/~1', '/~1']],
['/~01', '{"~1":{"c":1,"d":2}}', ['/~01', '/~01']],
['/~00', '{"~0":{"c":1,"d":2}}', ['/~00', '/~00']],
['/~1/c', '{"/":{"c":[1,2],"d":2}}', ['/~1/c', '/~1/c']],
['/0', '[{"c":1,"d":2}, [null]]', ['/0', '/0']],
['/-', '[{"one": 1,"two": 2},{"three": 3,"four": 4}]', ['/-', '/-', '/-', '/-']],
[
['/two', '/four'],
'{"one": [1,11], "two": [2,22], "three": [3,33], "four": [4,44]}',
['/two', '/two', '/four', '/four'],
],
[
['/-/two', '/-/one'],
'[{"one": 1, "two": 2}, {"one": 1, "two": 2}]',
['/-/one', '/-/two', '/-/one', '/-/two'],
],
];
}
public function testGetCurrentJsonPointerThrowsWhenCalledOutsideOfALoop()
{
$this->expectException(JsonMachineException::class);
$this->expectExceptionMessage('must be called inside a loop');
$parser = $this->createParser('[]');
$parser->getCurrentJsonPointer();
}
public function testGetCurrentJsonPointerReturnsLiteralJsonPointer()
{
$parser = $this->createParser('{"\"key\\\\":"value"}', ['/\"key\\\\']);
foreach ($parser as $key => $item) {
$this->assertSame('/\"key\\\\', $parser->getCurrentJsonPointer());
}
}
public function testGetMatchedJsonPointerThrowsWhenCalledOutsideOfALoop()
{
$this->expectException(JsonMachineException::class);
$this->expectExceptionMessage('must be called inside a loop');
$parser = $this->createParser('[]');
$parser->getMatchedJsonPointer();
}
public function testGetMatchedJsonPointerReturnsLiteralMatch()
{
$parser = $this->createParser('{"\"key\\\\":"value"}', ['/\"key\\\\']);
foreach ($parser as $key => $item) {
$this->assertSame('/\"key\\\\', $parser->getMatchedJsonPointer());
}
}
public function testGetJsonPointers()
{
$parser = $this->createParser('{}', ['/one', '/two']);
$this->assertSame(['/one', '/two'], $parser->getJsonPointers());
$parser = $this->createParser('{}');
$this->assertSame([''], $parser->getJsonPointers());
}
public function testJsonPointerReferenceTokenMatchesJsonMemberNameLiterally()
{
$parser = $this->createParser('{"\\"key":"value"}', ['/\\"key']);
foreach ($parser as $key => $item) {
$this->assertSame('"key', $key);
$this->assertSame('value', $item);
}
}
public function testGetPositionReturnsCorrectPositionWithDebugEnabled()
{
$parser = new Parser(new TokensWithDebugging(['[ 1, "two", false ]']));
$expectedPosition = [5, 12, 19];
$this->assertSame(0, $parser->getPosition());
foreach ($parser as $index => $item) {
$this->assertSame($expectedPosition[$index], $parser->getPosition(), "index:$index, item:$item");
}
$this->assertSame(21, $parser->getPosition());
}
public function testGetPositionReturns0WithDebugDisabled()
{
$parser = new Parser(new Tokens(['[ 1, "two", false ]']));
$this->assertSame(0, $parser->getPosition());
foreach ($parser as $index => $item) {
$this->assertSame(0, $parser->getPosition());
}
$this->assertSame(0, $parser->getPosition());
}
public function testGetPositionThrowsIfTokensDoNotSupportGetPosition()
{
$parser = new Parser(new \ArrayObject());
$this->expectException(JsonMachineException::class);
$parser->getPosition();
}
}
JsonMachineTest/FileChunksTest.php 0000644 00000001507 15025063511 0013207 0 ustar 00 assertSame($expectedResult, $result);
}
public function data_testGeneratorYieldsFileChunks()
{
return [
[5, ['{"pat', 'h": {', '"key"', ':"val', 'ue"}}', "\n"]],
[6, ['{"path', '": {"k', 'ey":"v', 'alue"}', '}'."\n"]],
[1024, ['{"path": {"key":"value"}}'."\n"]],
];
}
}
JsonMachineTest/formatted-crlf.json 0000644 00000000132 15025063511 0013400 0 ustar 00 {
"id": 54640519019642880,
"user": {
"notifications": null
},
"geo": "test"
}
JsonMachineTest/ValidJsonPointersTest.php 0000644 00000004247 15025063511 0014575 0 ustar 00 expectException(InvalidArgumentException::class);
$this->expectExceptionMessage("'$jsonPointers[0]', '$jsonPointers[1]'");
(new ValidJsonPointers($jsonPointers))->toArray();
}
public function data_testThrowsOnIntersectingPaths()
{
return [
[['/companies/-/id', '/companies/0/id']],
[['/companies/-/id', '', '/companies/0/id']],
[['/companies/-/id', '']],
[['/companies/0/id', '']],
[['//in-empty-string-key', '/']],
[['/~0~1/in-escaped-key', '/~0~1']],
];
}
/**
* @dataProvider data_testThrowsOnMalformedJsonPointer
*/
public function testThrowsOnMalformedJsonPointer(array $jsonPointer)
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('not valid');
(new ValidJsonPointers($jsonPointer))->toArray();
}
public function data_testThrowsOnMalformedJsonPointer()
{
return [
[['apple']],
[['/apple/~']],
[['apple/pie']],
[['apple/pie/']],
[[' /apple/pie/']],
[[
'/valid',
'/valid/-',
'inv/alid',
]],
];
}
public function testThrowsOnDuplicatePaths()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage("'/one', '/one'");
(new ValidJsonPointers(['/one', '/one']))->toArray();
}
public function testToArrayReturnsJsonPointers()
{
$this->assertSame(
['/one', '/two'],
(new ValidJsonPointers(['/one', '/two']))->toArray()
);
}
}
JsonMachineTest/PR-19-FIX.json 0000644 00000000372 15025063511 0011671 0 ustar 00 {
"datafeed": {
"info": {
"category": "Category name"
},
"programs": [
{
"program_info": {
"id": "X0"
}
},
{
"program_info": {
"id": "X1"
}
}
]
}
}
JsonMachineTest/StreamChunksTest.php 0000644 00000001135 15025063511 0013560 0 ustar 00 expectException(InvalidArgumentException::class);
new StreamChunks(false);
}
public function testGeneratorYieldsData()
{
$result = iterator_to_array(new StreamChunks(fopen('data://text/plain,test', 'r')));
$this->assertSame(['test'], $result);
}
}
JsonMachineTest/ItemsOptionsTest.php 0000644 00000003010 15025063511 0013600 0 ustar 00 toArray();
$this->assertEquals($this->defaultOptions(), $optionsArray);
}
public function testHasArrayAccess()
{
$options = new ItemsOptions();
$this->assertTrue(isset($options['debug']));
$this->assertFalse($options['debug']);
}
/**
* @dataProvider defaultOptionNames
*/
public function testThrowsOnInvalidOptionType($optionName)
{
$this->expectException(InvalidArgumentException::class);
new ItemsOptions([$optionName => new InvalidValue()]);
}
public function defaultOptionNames()
{
foreach ($this->defaultOptions() as $name => $ignore) {
yield [$name];
}
}
private function defaultOptions()
{
return [
'pointer' => '',
'decoder' => new ExtJsonDecoder(),
'debug' => false,
];
}
public function testThrowsOnUnknownOption()
{
$this->expectException(InvalidArgumentException::class);
new ItemsOptions(['invalid_option_name' => 'value']);
}
}
class InvalidValue
{
}
JsonMachineTest/AutoloadingTest.php 0000644 00000004356 15025063511 0013427 0 ustar 00 createAutoloadableClass();
register_shutdown_function(function () use ($dummyFile) {
@unlink($dummyFile);
});
$autoloadersBackup = $this->unregisterCurrentAutoloaders();
$autoloader = require __DIR__.'/../../src/autoloader.php';
spl_autoload_register($autoloader);
$autoloaded = class_exists('JsonMachine\\AutoloadStub');
spl_autoload_unregister($autoloader);
$this->registerPreviousAutoloaders($autoloadersBackup);
$this->assertTrue($autoloaded);
}
/**
* @runInSeparateProcess
*/
public function testIgnoresInvalidBaseNamespace()
{
$dummyFile = $this->createAutoloadableClass();
register_shutdown_function(function () use ($dummyFile) {
@unlink($dummyFile);
});
$autoloadersBackup = $this->unregisterCurrentAutoloaders();
$autoloader = require __DIR__.'/../../src/autoloader.php';
spl_autoload_register($autoloader);
$autoloaded = class_exists('XXXsonMachine\\AutoloadStub');
spl_autoload_unregister($autoloader);
$this->registerPreviousAutoloaders($autoloadersBackup);
$this->assertFalse($autoloaded);
}
private function createAutoloadableClass(): string
{
$dummyFile = __DIR__.'/../../src/AutoloadStub.php';
file_put_contents($dummyFile, ' $args[1],
'decoder' => $args[2],
'debug' => $args[3],
],
]);
$this->assertSame($expected, iterator_to_array($iterator));
}
public function testItemsYieldsObjectItemsByDefault()
{
$iterator = Items::fromString('{"path": {"key":"value"}}');
foreach ($iterator as $item) {
$this->assertEquals((object) ['key' => 'value'], $item);
}
}
public function data_testFactories()
{
$extJsonResult = ['key' => 'value'];
$passThruResult = ['"key"' => '"value"'];
$ptDecoder = new PassThruDecoder();
foreach ([true, false] as $debug) {
foreach ([
[$extJsonResult, 'fromStream', fopen('data://text/plain,{"path": {"key":"value"}}', 'r'), '/path', null, $debug],
[$extJsonResult, 'fromString', '{"path": {"key":"value"}}', '/path', null, $debug],
[$extJsonResult, 'fromFile', __DIR__.'/ItemsTest.json', '/path', null, $debug],
[$extJsonResult, 'fromIterable', ['{"path": {"key', '":"value"}}'], '/path', null, $debug],
[$extJsonResult, 'fromIterable', new \ArrayIterator(['{"path": {"key', '":"value"}}']), '/path', null, $debug],
[$passThruResult, 'fromStream', fopen('data://text/plain,{"path": {"key":"value"}}', 'r'), '/path', $ptDecoder, $debug],
[$passThruResult, 'fromString', '{"path": {"key":"value"}}', '/path', $ptDecoder, $debug],
[$passThruResult, 'fromFile', __DIR__.'/ItemsTest.json', '/path', $ptDecoder, $debug],
[$passThruResult, 'fromIterable', ['{"path": {"key', '":"value"}}'], '/path', $ptDecoder, $debug],
[$passThruResult, 'fromIterable', new \ArrayIterator(['{"path": {"key', '":"value"}}']), '/path', $ptDecoder, $debug],
] as $case) {
yield $case;
}
}
}
public function testGetPositionDebugEnabled()
{
$expectedPosition = ['key1' => 9, 'key2' => 19];
$items = Items::fromString('{"key1":1, "key2":2} ', ['debug' => true]);
foreach ($items as $key => $val) {
$this->assertSame($expectedPosition[$key], $items->getPosition());
}
}
public function testIterationWithoutForeach()
{
$iterator =
Items::fromString('{"key1":1, "key2":2}')
->getIterator();
$iterator->rewind();
$this->assertTrue($iterator->valid());
$this->assertSame(['key1', 1], [$iterator->key(), $iterator->current()]);
$iterator->next();
$this->assertTrue($iterator->valid());
$this->assertSame(['key2', 2], [$iterator->key(), $iterator->current()]);
$iterator->next();
$this->assertFalse($iterator->valid());
}
public function testIsDebugEnabled()
{
$items = $iterator = Items::fromString('{}');
$this->assertFalse($items->isDebugEnabled());
$items = $iterator = Items::fromString('{}', ['debug' => true]);
$this->assertTrue($items->isDebugEnabled());
}
public function testGetCurrentJsonPointer()
{
$items = $iterator = Items::fromString(
'[{"two": 2, "one": 1}]',
['pointer' => ['/-/one', '/-/two']]
);
$iterator = $items->getIterator();
$iterator->rewind();
$iterator->current();
$this->assertSame('/0/two', $items->getCurrentJsonPointer());
$iterator->next();
$iterator->current();
$this->assertSame('/0/one', $items->getCurrentJsonPointer());
}
public function testGetMatchedJsonPointer()
{
$items = $iterator = Items::fromString(
'[{"two": 2, "one": 1}]',
['pointer' => ['/-/one', '/-/two']]
);
$iterator = $items->getIterator();
$iterator->rewind();
$iterator->current();
$this->assertSame('/-/two', $items->getMatchedJsonPointer());
$iterator->next();
$iterator->current();
$this->assertSame('/-/one', $items->getMatchedJsonPointer());
}
public function testGetJsonPointers()
{
$items = Items::fromString('[]', ['pointer' => ['/one', '/two']]);
$this->assertSame(['/one', '/two'], $items->getJsonPointers());
}
}
JsonMachineTest/Exception/SyntaxErrorExceptionTest.php 0000644 00000001026 15025063511 0017265 0 ustar 00 assertContains('msg 42', $exception->getMessage());
$this->assertContains('24', $exception->getMessage());
}
}
JsonMachineTest/formatted-cr.json 0000644 00000000132 15025063511 0013056 0 ustar 00 {
"id": 54640519019642880,
"user": {
"notifications": null
},
"geo": "test"
}
JsonMachineTest/formatted-lf.json 0000644 00000000132 15025063511 0013053 0 ustar 00 {
"id": 54640519019642880,
"user": {
"notifications": null
},
"geo": "test"
}
JsonMachineTest/JsonDecoder/ExtJsonDecoderTest.php 0000644 00000004107 15025063511 0016232 0 ustar 00 decode($json);
$this->assertTrue('object' === gettype($defaultResult->getValue()));
$this->assertFalse('string' === gettype($defaultResult->getValue()->bigint));
$this->assertSame([['deeper']], $defaultResult->getValue()->deep);
}
public function testPassesAssocTrueOptionToJsonDecode()
{
$json = '{"bigint": 123456789123456789123456789, "deep": [["deeper"]]}';
$assocDecoder = new ExtJsonDecoder(true);
$assocResult = $assocDecoder->decode($json);
$this->assertTrue('array' === gettype($assocResult->getValue()));
}
public function testPassesAssocFalseOptionToJsonDecode()
{
$json = '{"bigint": 123456789123456789123456789, "deep": [["deeper"]]}';
$objDecoder = new ExtJsonDecoder(false);
$objResult = $objDecoder->decode($json);
$this->assertTrue('object' === gettype($objResult->getValue()));
}
public function testPassesPassesDepthOptionToJsonDecode()
{
$json = '{"bigint": 123456789123456789123456789, "deep": [["deeper"]]}';
$depthDecoder = new ExtJsonDecoder(true, 1);
$depthResult = $depthDecoder->decode($json);
$this->assertFalse($depthResult->isOk());
$this->assertSame('Maximum stack depth exceeded', $depthResult->getErrorMessage());
}
public function testPassesPassesBigIntOptionToJsonDecode()
{
$bigintDecoder = new ExtJsonDecoder(false, 1, JSON_BIGINT_AS_STRING);
$bigintResult = $bigintDecoder->decode('123123123123123123123');
$this->assertSame('123123123123123123123', $bigintResult->getValue());
}
}
JsonMachineTest/JsonDecoder/DecodingErrorTest.php 0000644 00000001225 15025063511 0016076 0 ustar 00 assertSame('"json\"', $decodingError->getMalformedJson());
}
public function testGetErrorMessage()
{
$decodingError = new DecodingError('', 'something bad happened');
$this->assertSame('something bad happened', $decodingError->getErrorMessage());
}
}
JsonMachineTest/JsonDecoder/ValidResultTest.php 0000644 00000001020 15025063511 0015577 0 ustar 00 assertSame('Value X', $result->getValue());
}
public function testIsOk()
{
$result = new ValidResult('X');
$this->assertTrue($result->isOk());
}
}
JsonMachineTest/JsonDecoder/InvalidResultTest.php 0000644 00000001051 15025063511 0016132 0 ustar 00 assertSame('Error X', $result->getErrorMessage());
}
public function testIsOk()
{
$result = new InvalidResult('X');
$this->assertFalse($result->isOk());
}
}
JsonMachineTest/JsonDecoder/ErrorWrappingDecoderTest.php 0000644 00000004736 15025063511 0017451 0 ustar 00 decode('"json"');
$this->assertTrue($result->isOk());
$this->assertEquals($case['wrappedResult'], $result);
}
public function data_testCorrectlyWrapsResults()
{
$notOkResult = new InvalidResult('Error happened.');
$okResult = new ValidResult('json');
$wrappedNotOkResult = new ValidResult(new DecodingError('"json"', 'Error happened.'));
$wrappedOkResult = $okResult;
return [
[
[
'result' => $notOkResult,
'wrappedResult' => $wrappedNotOkResult,
],
],
[
[
'result' => $okResult,
'wrappedResult' => $wrappedOkResult,
],
],
];
}
public function testCatchesErrorInsideIteratedJsonChunk()
{
$json = /* @lang JSON */ '
{
"results": [
{"correct": "correct"},
{"incorrect": nulll},
{"correct": "correct"}
]
}
';
$items = Items::fromString($json, [
'pointer' => '/results',
'decoder' => new ErrorWrappingDecoder(new ExtJsonDecoder(true)),
]);
$result = iterator_to_array($items);
$this->assertSame('correct', $result[0]['correct']);
$this->assertSame('correct', $result[2]['correct']);
/** @var DecodingError $decodingError */
$decodingError = $result[1];
$this->assertInstanceOf(DecodingError::class, $decodingError);
$this->assertSame('{"incorrect":nulll}', $decodingError->getMalformedJson());
$this->assertSame('Syntax error', $decodingError->getErrorMessage());
}
}
JsonMachineTest/JsonDecoder/PassThruDecoderTest.php 0000644 00000000755 15025063511 0016416 0 ustar 00 decode('["json"]');
$this->assertSame('["json"]', $passThruResult->getValue());
}
}
JsonMachineTest/JsonDecoder/StubDecoder.php 0000644 00000000543 15025063511 0014715 0 ustar 00 decoded = $decoded;
}
public function decode($jsonValue)
{
return $this->decoded;
}
}
JsonMachineTest/StringChunksTest.php 0000644 00000001511 15025063511 0013571 0 ustar 00 assertSame($expectedResult, $result);
}
public function data_testGeneratorYieldsStringChunks()
{
return [
// single-byte:
['onetwo', 6, ['onetwo']],
['onetwo', 7, ['onetwo']],
['onetwo', 3, ['one', 'two']],
['onetwo', 4, ['onet', 'wo']],
];
}
}
JsonMachineTest/TokensTest.php 0000644 00000020067 15025063511 0012421 0 ustar 00 [TokensWithDebugging::class],
'debug disabled' => [Tokens::class],
];
}
/**
* @dataProvider bothDebugModes
*/
public function testCorrectlyYieldsZeroToken($tokensClass)
{
$data = ['0'];
$expected = ['0'];
$this->assertEquals($expected, iterator_to_array(new $tokensClass(new \ArrayIterator($data))));
$stream = fopen('data://text/plain,{"value":0}', 'r');
$expected = ['{', '"value"', ':', '0', '}'];
$this->assertEquals($expected, iterator_to_array(new $tokensClass(new StreamChunks($stream, 10))));
}
/**
* @dataProvider bothDebugModes
*/
public function testGeneratesTokens($tokensClass)
{
$data = ['{}[],:null,"string" false:', 'true,1,100000,1.555{-56]"","\\""'];
$expected = ['{', '}', '[', ']', ',', ':', 'null', ',', '"string"', 'false', ':', 'true', ',', '1', ',', '100000', ',', '1.555', '{', '-56', ']', '""', ',', '"\\""'];
$this->assertEquals($expected, iterator_to_array(new $tokensClass(new \ArrayIterator($data))));
}
/**
* @dataProvider bothDebugModes
*/
public function testWithBOM($tokensClass)
{
$data = ["\xEF\xBB\xBF".'{}'];
$expected = ['{', '}'];
$this->assertEquals($expected, iterator_to_array(new $tokensClass(new \ArrayIterator($data))));
}
/**
* @dataProvider bothDebugModes
*/
public function testCorrectlyParsesTwoBackslashesAtTheEndOfAString($tokensClass)
{
$this->assertEquals(['"test\\\\"', ':'], iterator_to_array(new $tokensClass(new \ArrayIterator(['"test\\\\":']))));
}
/**
* @dataProvider bothDebugModes
*/
public function testCorrectlyParsesEscapedQuotesInTheMiddleOfAString($tokensClass)
{
$json = '"test\"test":';
$expected = ['"test\"test"', ':'];
$this->assertEquals($expected, iterator_to_array(new $tokensClass(new \ArrayIterator([$json]))));
}
/**
* @dataProvider bothDebugModes
*/
public function testCorrectlyParsesChunksSplitBeforeStringEnd($tokensClass)
{
$chunks = ['{"path": {"key":"value', '"}}'];
$expected = ['{', '"path"', ':', '{', '"key"', ':', '"value"', '}', '}'];
$this->assertEquals($expected, iterator_to_array(new $tokensClass(new \ArrayIterator($chunks))));
}
/**
* @dataProvider bothDebugModes
*/
public function testCorrectlyParsesChunksSplitBeforeEscapedCharacter($tokensClass)
{
$chunks = ['{"path": {"key":"value\\', '""}}'];
$expected = ['{', '"path"', ':', '{', '"key"', ':', '"value\""', '}', '}'];
$this->assertEquals($expected, iterator_to_array(new $tokensClass(new \ArrayIterator($chunks))));
}
/**
* @dataProvider bothDebugModes
*/
public function testCorrectlyParsesChunksSplitAfterEscapedCharacter($tokensClass)
{
$chunks = ['{"path": {"key":"value\\"', '"}}'];
$expected = ['{', '"path"', ':', '{', '"key"', ':', '"value\""', '}', '}'];
$this->assertEquals($expected, iterator_to_array(new $tokensClass(new \ArrayIterator($chunks))));
}
/**
* @dataProvider bothDebugModes
*/
public function testAnyPossibleChunkSplit($tokensClass)
{
$json = '
{
"datafeed": {
"info": {
"category": "Category name"
},
"programs": [
{
"program_info": {
"id": "X0\"\\\\",
"number": 123,
"constant": false
}
},
{
"program_info": {
"id": "\b\f\n\r\t\u0020X1"
}
}
]
}
}
';
$expected = [
'{', '"datafeed"', ':', '{', '"info"', ':', '{', '"category"', ':', '"Category name"', '}', ',',
'"programs"', ':', '[', '{', '"program_info"', ':', '{', '"id"', ':', '"X0\\"\\\\"', ',', '"number"', ':',
'123', ',', '"constant"', ':', 'false', '}', '}', ',', '{', '"program_info"', ':', '{', '"id"', ':',
'"\b\f\n\r\t\u0020X1"', '}', '}', ']', '}', '}',
];
foreach (range(1, strlen($json)) as $chunkLength) {
$chunks = str_split($json, $chunkLength);
$result = iterator_to_array(new $tokensClass($chunks));
$this->assertSame($expected, $result);
}
}
/**
* @dataProvider jsonFilesWithDifferentLineEndings
*/
public function testProvidesLocationalDataWhenDebugEnabled(string $jsonFilePath)
{
$jsonFileContents = file_get_contents($jsonFilePath);
$tokens = new TokensWithDebugging(new StringChunks($jsonFileContents));
$expectedTokens = $this->expectedTokens();
$i = 0;
foreach ($tokens as $token) {
++$i;
$expectedToken = array_shift($expectedTokens);
$this->assertEquals($expectedToken[0], $token, 'token failed with expected token #'.$i);
$this->assertEquals($expectedToken[1], $tokens->getLine(), 'line failed with expected token #'.$i);
$this->assertEquals($expectedToken[2], $tokens->getColumn(), 'column failed with expected token #'.$i);
}
}
/**
* @dataProvider jsonFilesWithDifferentLineEndings
*/
public function testProvidesLocationalDataWhenDebugDisabled(string $jsonFilePath)
{
$tokens = new Tokens(new FileChunks($jsonFilePath));
$expectedTokens = $this->expectedTokens();
$i = 0;
foreach ($tokens as $token) {
++$i;
$expectedToken = array_shift($expectedTokens);
$this->assertEquals($expectedToken[0], $token, 'token failed with expected token #'.$i);
$this->assertEquals(1, $tokens->getLine(), 'line failed with expected token #'.$i);
$this->assertEquals(0, $tokens->getColumn(), 'column failed with expected token #'.$i);
}
}
public function testGetPositionWthDebugging()
{
$tokens = new TokensWithDebugging(['[ 1, "two", false ]']);
$expectedPosition = [1, 5, 6, 12, 13, 19, 21];
$this->assertSame(0, $tokens->getPosition());
foreach ($tokens as $index => $item) {
$this->assertSame($expectedPosition[$index], $tokens->getPosition(), "index:$index, item:$item");
}
$this->assertSame(21, $tokens->getPosition());
}
public function testGetPositionNoDebugging()
{
$tokens = new Tokens(['[ 1, "two", false ]']);
$this->assertSame(0, $tokens->getPosition());
foreach ($tokens as $index => $item) {
$this->assertSame(0, $tokens->getPosition(), "index:$index, item:$item");
}
$this->assertSame(0, $tokens->getPosition());
}
public function jsonFilesWithDifferentLineEndings()
{
return [
'cr new lines' => [__DIR__.'/formatted-cr.json'],
'lf new lines' => [__DIR__.'/formatted-lf.json'],
'crlf new lines' => [__DIR__.'/formatted-crlf.json'],
];
}
private function expectedTokens()
{
return [
// lexeme, line, column
['{', 1, 1],
['"id"', 2, 3],
[':', 2, 7],
['54640519019642880', 2, 9],
[',', 2, 26],
['"user"', 3, 3],
[':', 3, 9],
['{', 3, 11],
['"notifications"', 4, 5],
[':', 4, 20],
['null', 4, 22],
['}', 5, 3],
[',', 5, 4],
['"geo"', 6, 3],
[':', 6, 8],
['"test"', 6, 10],
['}', 7, 1],
];
}
}
JsonMachineTest/ItemsTest.json 0000644 00000000032 15025063511 0012407 0 ustar 00 {"path": {"key":"value"}}
performance/testPerformance.php 0000644 00000003706 15025063511 0012723 0 ustar 00 function ($file) {
return Items::fromFile($file);
},
'Items::fromString()' => function ($file) {
return Items::fromString(stream_get_contents(fopen($file, 'r')));
},
'Items::fromFile() - debug' => function ($file) {
return Items::fromFile($file, ['debug' => true]);
},
'Items::fromString() - debug' => function ($file) {
return Items::fromString(stream_get_contents(fopen($file, 'r')), ['debug' => true]);
},
'json_decode()' => function ($file) {
return json_decode(stream_get_contents(fopen($file, 'r')), true);
},
];
$tmpJsonFileName = createBigJsonFile();
$fileSizeMb = (filesize($tmpJsonFileName) / 1024 / 1024);
echo 'File size: '.round($fileSizeMb, 2),' MB'.PHP_EOL;
foreach ($decoders as $name => $decoder) {
$start = microtime(true);
$result = $decoder($tmpJsonFileName);
if ( ! $result instanceof \Traversable && ! is_array($result)) {
$textResult = 'Decoding error';
} else {
foreach ($result as $key => $item) {
}
$time = microtime(true) - $start;
$textResult = round($fileSizeMb / $time, 2).' MB/s';
}
echo str_pad($name.': ', 37, '.')." $textResult".PHP_EOL;
}
@unlink($tmpJsonFileName);
function createBigJsonFile()
{
$tmpJson = tempnam(sys_get_temp_dir(), 'json_');
$f = fopen($tmpJson, 'w');
$separator = '';
fputs($f, '[');
for ($i = 0; $i < 6000; ++$i) {
fputs($f, $separator);
fputs($f, file_get_contents(__DIR__.'/twitter_example_'.($i % 2).'.json'));
$separator = ",\n\n";
}
fputs($f, ']');
fclose($f);
return $tmpJson;
}
performance/twitter_example_1.json 0000644 00000010655 15025063511 0013402 0 ustar 00 {
"text": "RT @PostGradProblem: In preparation for the NFL lockout, I will be spending twice as much time analyzing my fantasy baseball team during ...",
"truncated": true,
"in_reply_to_user_id": null,
"in_reply_to_status_id": null,
"favorited": false,
"source": "Twitter for iPhone",
"in_reply_to_screen_name": null,
"in_reply_to_status_id_str": null,
"id_str": "54691802283900928",
"entities": {
"user_mentions": [
{
"indices": [
3,
19
],
"screen_name": "PostGradProblem",
"id_str": "271572434",
"name": "PostGradProblems",
"id": 271572434
}
],
"urls": [ ],
"hashtags": [ ]
},
"contributors": null,
"retweeted": false,
"in_reply_to_user_id_str": null,
"place": null,
"retweet_count": 4,
"created_at": "Sun Apr 03 23:48:36 +0000 2011",
"retweeted_status": {
"text": "In preparation for the NFL lockout, I will be spending twice as much time analyzing my fantasy baseball team during company time. #PGP",
"truncated": false,
"in_reply_to_user_id": null,
"in_reply_to_status_id": null,
"favorited": false,
"source": "HootSuite",
"in_reply_to_screen_name": null,
"in_reply_to_status_id_str": null,
"id_str": "54640519019642881",
"entities": {
"user_mentions": [ ],
"urls": [ ],
"hashtags": [
{
"text": "PGP",
"indices": [
130,
134
]
}
]
},
"contributors": null,
"retweeted": false,
"in_reply_to_user_id_str": null,
"place": null,
"retweet_count": 4,
"created_at": "Sun Apr 03 20:24:49 +0000 2011",
"user": {
"notifications": null,
"profile_use_background_image": true,
"statuses_count": 31,
"profile_background_color": "C0DEED",
"followers_count": 3066,
"profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg",
"listed_count": 6,
"profile_background_image_url": "http://a3.twimg.com/a/1301071706/images/themes/theme1/bg.png",
"description": "",
"screen_name": "PostGradProblem",
"default_profile": true,
"verified": false,
"time_zone": null,
"profile_text_color": "333333",
"is_translator": false,
"profile_sidebar_fill_color": "DDEEF6",
"location": "",
"id_str": "271572434",
"default_profile_image": false,
"profile_background_tile": false,
"lang": "en",
"friends_count": 21,
"protected": false,
"favourites_count": 0,
"created_at": "Thu Mar 24 19:45:44 +0000 2011",
"profile_link_color": "0084B4",
"name": "PostGradProblems",
"show_all_inline_media": false,
"follow_request_sent": null,
"geo_enabled": false,
"profile_sidebar_border_color": "C0DEED",
"url": null,
"id": 271572434,
"contributors_enabled": false,
"following": null,
"utc_offset": null
},
"id": 54640519019642880,
"coordinates": null,
"geo": null
},
"user": {
"notifications": null,
"profile_use_background_image": true,
"statuses_count": 351,
"profile_background_color": "C0DEED",
"followers_count": 48,
"profile_image_url": "http://a1.twimg.com/profile_images/455128973/gCsVUnofNqqyd6tdOGevROvko1_500_normal.jpg",
"listed_count": 0,
"profile_background_image_url": "http://a3.twimg.com/a/1300479984/images/themes/theme1/bg.png",
"description": "watcha doin in my waters?",
"screen_name": "OldGREG85",
"default_profile": true,
"verified": false,
"time_zone": "Hawaii",
"profile_text_color": "333333",
"is_translator": false,
"profile_sidebar_fill_color": "DDEEF6",
"location": "Texas",
"id_str": "80177619",
"default_profile_image": false,
"profile_background_tile": false,
"lang": "en",
"friends_count": 81,
"protected": false,
"favourites_count": 0,
"created_at": "Tue Oct 06 01:13:17 +0000 2009",
"profile_link_color": "0084B4",
"name": "GG",
"show_all_inline_media": false,
"follow_request_sent": null,
"geo_enabled": false,
"profile_sidebar_border_color": "C0DEED",
"url": null,
"id": 80177619,
"contributors_enabled": false,
"following": null,
"utc_offset": -36000
},
"id": 54691802283900930,
"coordinates": null,
"geo": null
}
performance/twitter_example_0.json 0000644 00000031044 15025063511 0013374 0 ustar 00 {
"statuses": [
{
"coordinates": null,
"favorited": false,
"truncated": false,
"created_at": "Mon Sep 24 03:35:21 +0000 2012",
"id_str": "250075927172759552",
"entities": {
"urls": [
],
"hashtags": [
{
"text": "freebandnames",
"indices": [
20,
34
]
}
],
"user_mentions": [
]
},
"in_reply_to_user_id_str": null,
"contributors": null,
"text": "Aggressive Ponytail #freebandnames",
"metadata": {
"iso_language_code": "en",
"result_type": "recent"
},
"retweet_count": 0,
"in_reply_to_status_id_str": null,
"id": 250075927172759552,
"geo": null,
"retweeted": false,
"in_reply_to_user_id": null,
"place": null,
"user": {
"profile_sidebar_fill_color": "DDEEF6",
"profile_sidebar_border_color": "C0DEED",
"profile_background_tile": false,
"name": "Sean Cummings",
"profile_image_url": "http://a0.twimg.com/profile_images/2359746665/1v6zfgqo8g0d3mk7ii5s_normal.jpeg",
"created_at": "Mon Apr 26 06:01:55 +0000 2010",
"location": "LA, CA",
"follow_request_sent": null,
"profile_link_color": "0084B4",
"is_translator": false,
"id_str": "137238150",
"entities": {
"url": {
"urls": [
{
"expanded_url": null,
"url": "",
"indices": [
0,
0
]
}
]
},
"description": {
"urls": [
]
}
},
"default_profile": true,
"contributors_enabled": false,
"favourites_count": 0,
"url": null,
"profile_image_url_https": "https://si0.twimg.com/profile_images/2359746665/1v6zfgqo8g0d3mk7ii5s_normal.jpeg",
"utc_offset": -28800,
"id": 137238150,
"profile_use_background_image": true,
"listed_count": 2,
"profile_text_color": "333333",
"lang": "en",
"followers_count": 70,
"protected": false,
"notifications": null,
"profile_background_image_url_https": "https://si0.twimg.com/images/themes/theme1/bg.png",
"profile_background_color": "C0DEED",
"verified": false,
"geo_enabled": true,
"time_zone": "Pacific Time (US & Canada)",
"description": "Born 330 Live 310",
"default_profile_image": false,
"profile_background_image_url": "http://a0.twimg.com/images/themes/theme1/bg.png",
"statuses_count": 579,
"friends_count": 110,
"following": null,
"show_all_inline_media": false,
"screen_name": "sean_cummings"
},
"in_reply_to_screen_name": null,
"source": "Twitter for Mac",
"in_reply_to_status_id": null
},
{
"coordinates": null,
"favorited": false,
"truncated": false,
"created_at": "Fri Sep 21 23:40:54 +0000 2012",
"id_str": "249292149810667520",
"entities": {
"urls": [
],
"hashtags": [
{
"text": "FreeBandNames",
"indices": [
20,
34
]
}
],
"user_mentions": [
]
},
"in_reply_to_user_id_str": null,
"contributors": null,
"text": "Thee Namaste Nerdz. #FreeBandNames",
"metadata": {
"iso_language_code": "pl",
"result_type": "recent"
},
"retweet_count": 0,
"in_reply_to_status_id_str": null,
"id": 249292149810667520,
"geo": null,
"retweeted": false,
"in_reply_to_user_id": null,
"place": null,
"user": {
"profile_sidebar_fill_color": "DDFFCC",
"profile_sidebar_border_color": "BDDCAD",
"profile_background_tile": true,
"name": "Chaz Martenstein",
"profile_image_url": "http://a0.twimg.com/profile_images/447958234/Lichtenstein_normal.jpg",
"created_at": "Tue Apr 07 19:05:07 +0000 2009",
"location": "Durham, NC",
"follow_request_sent": null,
"profile_link_color": "0084B4",
"is_translator": false,
"id_str": "29516238",
"entities": {
"url": {
"urls": [
{
"expanded_url": null,
"url": "http://bullcityrecords.com/wnng/",
"indices": [
0,
32
]
}
]
},
"description": {
"urls": [
]
}
},
"default_profile": false,
"contributors_enabled": false,
"favourites_count": 8,
"url": "http://bullcityrecords.com/wnng/",
"profile_image_url_https": "https://si0.twimg.com/profile_images/447958234/Lichtenstein_normal.jpg",
"utc_offset": -18000,
"id": 29516238,
"profile_use_background_image": true,
"listed_count": 118,
"profile_text_color": "333333",
"lang": "en",
"followers_count": 2052,
"protected": false,
"notifications": null,
"profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/9423277/background_tile.bmp",
"profile_background_color": "9AE4E8",
"verified": false,
"geo_enabled": false,
"time_zone": "Eastern Time (US & Canada)",
"description": "You will come to Durham, North Carolina. I will sell you some records then, here in Durham, North Carolina. Fun will happen.",
"default_profile_image": false,
"profile_background_image_url": "http://a0.twimg.com/profile_background_images/9423277/background_tile.bmp",
"statuses_count": 7579,
"friends_count": 348,
"following": null,
"show_all_inline_media": true,
"screen_name": "bullcityrecords"
},
"in_reply_to_screen_name": null,
"source": "web",
"in_reply_to_status_id": null
},
{
"coordinates": null,
"favorited": false,
"truncated": false,
"created_at": "Fri Sep 21 23:30:20 +0000 2012",
"id_str": "249289491129438208",
"entities": {
"urls": [
],
"hashtags": [
{
"text": "freebandnames",
"indices": [
29,
43
]
}
],
"user_mentions": [
]
},
"in_reply_to_user_id_str": null,
"contributors": null,
"text": "Mexican Heaven, Mexican Hell #freebandnames",
"metadata": {
"iso_language_code": "en",
"result_type": "recent"
},
"retweet_count": 0,
"in_reply_to_status_id_str": null,
"id": 249289491129438208,
"geo": null,
"retweeted": false,
"in_reply_to_user_id": null,
"place": null,
"user": {
"profile_sidebar_fill_color": "99CC33",
"profile_sidebar_border_color": "829D5E",
"profile_background_tile": false,
"name": "Thomas John Wakeman",
"profile_image_url": "http://a0.twimg.com/profile_images/2219333930/Froggystyle_normal.png",
"created_at": "Tue Sep 01 21:21:35 +0000 2009",
"location": "Kingston New York",
"follow_request_sent": null,
"profile_link_color": "D02B55",
"is_translator": false,
"id_str": "70789458",
"entities": {
"url": {
"urls": [
{
"expanded_url": null,
"url": "",
"indices": [
0,
0
]
}
]
},
"description": {
"urls": [
]
}
},
"default_profile": false,
"contributors_enabled": false,
"favourites_count": 19,
"url": null,
"profile_image_url_https": "https://si0.twimg.com/profile_images/2219333930/Froggystyle_normal.png",
"utc_offset": -18000,
"id": 70789458,
"profile_use_background_image": true,
"listed_count": 1,
"profile_text_color": "3E4415",
"lang": "en",
"followers_count": 63,
"protected": false,
"notifications": null,
"profile_background_image_url_https": "https://si0.twimg.com/images/themes/theme5/bg.gif",
"profile_background_color": "352726",
"verified": false,
"geo_enabled": false,
"time_zone": "Eastern Time (US & Canada)",
"description": "Science Fiction Writer, sort of. Likes Superheroes, Mole People, Alt. Timelines.",
"default_profile_image": false,
"profile_background_image_url": "http://a0.twimg.com/images/themes/theme5/bg.gif",
"statuses_count": 1048,
"friends_count": 63,
"following": null,
"show_all_inline_media": false,
"screen_name": "MonkiesFist"
},
"in_reply_to_screen_name": null,
"source": "web",
"in_reply_to_status_id": null
},
{
"coordinates": null,
"favorited": false,
"truncated": false,
"created_at": "Fri Sep 21 22:51:18 +0000 2012",
"id_str": "249279667666817024",
"entities": {
"urls": [
],
"hashtags": [
{
"text": "freebandnames",
"indices": [
20,
34
]
}
],
"user_mentions": [
]
},
"in_reply_to_user_id_str": null,
"contributors": null,
"text": "The Foolish Mortals #freebandnames",
"metadata": {
"iso_language_code": "en",
"result_type": "recent"
},
"retweet_count": 0,
"in_reply_to_status_id_str": null,
"id": 249279667666817024,
"geo": null,
"retweeted": false,
"in_reply_to_user_id": null,
"place": null,
"user": {
"profile_sidebar_fill_color": "BFAC83",
"profile_sidebar_border_color": "615A44",
"profile_background_tile": true,
"name": "Marty Elmer",
"profile_image_url": "http://a0.twimg.com/profile_images/1629790393/shrinker_2000_trans_normal.png",
"created_at": "Mon May 04 00:05:00 +0000 2009",
"location": "Wisconsin, USA",
"follow_request_sent": null,
"profile_link_color": "3B2A26",
"is_translator": false,
"id_str": "37539828",
"entities": {
"url": {
"urls": [
{
"expanded_url": null,
"url": "http://www.omnitarian.me",
"indices": [
0,
24
]
}
]
},
"description": {
"urls": [
]
}
},
"default_profile": false,
"contributors_enabled": false,
"favourites_count": 647,
"url": "http://www.omnitarian.me",
"profile_image_url_https": "https://si0.twimg.com/profile_images/1629790393/shrinker_2000_trans_normal.png",
"utc_offset": -21600,
"id": 37539828,
"profile_use_background_image": true,
"listed_count": 52,
"profile_text_color": "000000",
"lang": "en",
"followers_count": 608,
"protected": false,
"notifications": null,
"profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/106455659/rect6056-9.png",
"profile_background_color": "EEE3C4",
"verified": false,
"geo_enabled": false,
"time_zone": "Central Time (US & Canada)",
"description": "Cartoonist, Illustrator, and T-Shirt connoisseur",
"default_profile_image": false,
"profile_background_image_url": "http://a0.twimg.com/profile_background_images/106455659/rect6056-9.png",
"statuses_count": 3575,
"friends_count": 249,
"following": null,
"show_all_inline_media": true,
"screen_name": "Omnitarian"
},
"in_reply_to_screen_name": null,
"source": "Twitter for iPhone",
"in_reply_to_status_id": null
}
],
"search_metadata": {
"max_id": 250126199840518145,
"since_id": 24012619984051000,
"refresh_url": "?since_id=250126199840518145&q=%23freebandnames&result_type=mixed&include_entities=1",
"next_results": "?max_id=249279667666817023&q=%23freebandnames&count=4&include_entities=1&result_type=mixed",
"count": 4,
"completed_in": 0.035,
"since_id_str": "24012619984051000",
"query": "%23freebandnames",
"max_id_str": "250126199840518145"
}
}
Planet.php 0000644 00000003142 15025064731 0006503 0 ustar 00 mass = $mass;
$this->radius = $radius;
}
public function mass() : float
{
return $this->mass;
}
public function radius() : float
{
return $this->radius;
}
public function surfaceGravity() : float
{
return self::G * $this->mass / ($this->radius * $this->radius);
}
public function surfaceWeight(float $otherMass) : float
{
return $otherMass * $this->surfaceGravity();
}
}
NullValueTest.php 0000644 00000001624 15025064731 0010032 0 ustar 00 expectException(CloneNotSupportedException::class);
clone NullValue::instance();
}
public function testExceptionOnSerializeAttempt() : void
{
$this->expectException(SerializeNotSupportedException::class);
serialize(NullValue::instance());
}
public function testExceptionOnUnserializeAttempt() : void
{
$this->expectException(UnserializeNotSupportedException::class);
unserialize('O:22:"DASPRiD\\Enum\\NullValue":0:{}');
}
}
AbstractEnumTest.php 0000644 00000007323 15025064731 0010515 0 ustar 00 getProperty('constants');
$constantsProperty->setAccessible(true);
$constantsProperty->setValue([]);
$valuesProperty = $reflectionClass->getProperty('values');
$valuesProperty->setAccessible(true);
$valuesProperty->setValue([]);
$allValuesLoadedProperty = $reflectionClass->getProperty('allValuesLoaded');
$allValuesLoadedProperty->setAccessible(true);
$allValuesLoadedProperty->setValue([]);
}
public function testToString() : void
{
$weekday = WeekDay::FRIDAY();
self::assertSame('FRIDAY', (string) $weekday);
}
public function testName() : void
{
$this->assertSame('WEDNESDAY', WeekDay::WEDNESDAY()->name());
}
public function testOrdinal() : void
{
$this->assertSame(2, WeekDay::WEDNESDAY()->ordinal());
}
public function testSameInstanceIsReturned() : void
{
self::assertSame(WeekDay::FRIDAY(), WeekDay::FRIDAY());
}
public static function testValueOf() : void
{
self::assertSame(WeekDay::FRIDAY(), WeekDay::valueOf('FRIDAY'));
}
public function testValueOfInvalidConstant() : void
{
$this->expectException(IllegalArgumentException::class);
WeekDay::valueOf('CATURDAY');
}
public function testExceptionOnCloneAttempt() : void
{
$this->expectException(CloneNotSupportedException::class);
clone WeekDay::FRIDAY();
}
public function testExceptionOnSerializeAttempt() : void
{
$this->expectException(SerializeNotSupportedException::class);
serialize(WeekDay::FRIDAY());
}
public function testExceptionOnUnserializeAttempt() : void
{
$this->expectException(UnserializeNotSupportedException::class);
unserialize('O:24:"DASPRiD\\EnumTest\\WeekDay":0:{}');
}
public function testReturnValueOfValuesIsSortedByOrdinal() : void
{
// Initialize some week days out of order
WeekDay::SATURDAY();
WeekDay::TUESDAY();
$ordinals = array_values(array_map(function (WeekDay $weekDay) : int {
return $weekDay->ordinal();
}, WeekDay::values()));
self::assertSame([0, 1, 2, 3, 4, 5, 6], $ordinals);
$cachedOrdinals = array_values(array_map(function (WeekDay $weekDay) : int {
return $weekDay->ordinal();
}, WeekDay::values()));
$this->assertSame($ordinals, $cachedOrdinals);
}
public function testCompareTo() : void
{
$this->assertSame(-4, WeekDay::WEDNESDAY()->compareTo(WeekDay::SUNDAY()));
$this->assertSame(4, WeekDay::SUNDAY()->compareTo(WeekDay::WEDNESDAY()));
$this->assertSame(0, WeekDay::WEDNESDAY()->compareTo(WeekDay::WEDNESDAY()));
}
public function testCompareToWrongEnum() : void
{
$this->expectException(MismatchException::class);
WeekDay::MONDAY()->compareTo(Planet::EARTH());
}
public function testParameterizedEnum() : void
{
$planet = Planet::EARTH();
$this->assertSame(5.976e+24, $planet->mass());
$this->assertSame(6.37814e6, $planet->radius());
}
}
WeekDay.php 0000644 00000001171 15025064731 0006611 0 ustar 00 expectException(IllegalArgumentException::class);
new EnumMap(stdClass::class, 'string', false);
}
public function testUnexpectedKeyType() : void
{
$this->expectException(ExpectationException::class);
$map = new EnumMap(WeekDay::class, 'string', false);
$map->expect(Planet::class, 'string', false);
}
public function testUnexpectedValueType() : void
{
$this->expectException(ExpectationException::class);
$map = new EnumMap(WeekDay::class, 'string', false);
$map->expect(WeekDay::class, 'int', false);
}
public function testUnexpectedNullableValueType() : void
{
$this->expectException(ExpectationException::class);
$map = new EnumMap(WeekDay::class, 'string', true);
$map->expect(WeekDay::class, 'string', false);
}
public function testExpectedTypes() : void
{
$map = new EnumMap(WeekDay::class, 'string', true);
$map->expect(WeekDay::class, 'string', true);
$this->addToAssertionCount(1);
}
public function testSize() : void
{
$map = new EnumMap(WeekDay::class, 'string', true);
$this->assertSame(0, $map->size());
$map->put(WeekDay::MONDAY(), 'foo');
$this->assertSame(1, $map->size());
}
public function testContainsValue() : void
{
$map = new EnumMap(WeekDay::class, 'string', true);
$this->assertFalse($map->containsValue('foo'));
$map->put(WeekDay::TUESDAY(), 'foo');
$this->assertTrue($map->containsValue('foo'));
$this->assertFalse($map->containsValue(null));
$map->put(WeekDay::WEDNESDAY(), null);
$this->assertTrue($map->containsValue(null));
}
public function testContainsKey() : void
{
$map = new EnumMap(WeekDay::class, 'string', true);
$this->assertFalse($map->containsKey(WeekDay::TUESDAY()));
$map->put(WeekDay::TUESDAY(), 'foo');
$this->assertTrue($map->containsKey(WeekDay::TUESDAY()));
$map->put(WeekDay::WEDNESDAY(), null);
$this->assertTrue($map->containsKey(WeekDay::WEDNESDAY()));
}
public function testPutAndGet() : void
{
$map = new EnumMap(WeekDay::class, 'string', true);
$map->put(WeekDay::TUESDAY(), 'foo');
$map->put(WeekDay::FRIDAY(), null);
$this->assertSame('foo', $map->get(WeekDay::TUESDAY()));
$this->assertSame(null, $map->get(WeekDay::WEDNESDAY()));
$this->assertSame(null, $map->get(WeekDay::FRIDAY()));
}
public function testPutInvalidKey() : void
{
$this->expectException(IllegalArgumentException::class);
$map = new EnumMap(WeekDay::class, 'string', true);
$map->put(Planet::MARS(), 'foo');
}
public function invalidValues() : array
{
return [
['bool', null, false],
['bool', 0],
['boolean', 0],
['int', 2.4],
['integer', 5.3],
['float', 3],
['double', 7],
['string', 1],
['object', 1],
['array', 1],
[stdClass::class, 1],
];
}
/**
* @dataProvider invalidValues
* @param mixed $value
*/
public function testPutInvalidValue(string $valueType, $value, bool $allowNull = true) : void
{
$this->expectException(IllegalArgumentException::class);
$map = new EnumMap(WeekDay::class, $valueType, $allowNull);
$map->put(WeekDay::TUESDAY(), $value);
}
public function validValues() : array
{
return [
['bool', null],
['mixed', 'foo'],
['mixed', 1],
['mixed', new stdClass()],
['bool', true],
['boolean', false],
['int', 1],
['integer', 4],
['float', 2.5],
['double', 6.4],
['string', 'foo'],
['object', new stdClass()],
['array', ['foo']],
[stdClass::class, new stdClass()],
];
}
/**
* @dataProvider validValues
* @param mixed $value
*/
public function testPutValidValue(string $valueType, $value, bool $allowNull = true) : void
{
$map = new EnumMap(WeekDay::class, $valueType, $allowNull);
$map->put(WeekDay::TUESDAY(), $value);
$this->addToAssertionCount(1);
}
public function testRemove() : void
{
$map = new EnumMap(WeekDay::class, 'string', true);
$map->put(WeekDay::TUESDAY(), 'foo');
$map->remove(WeekDay::TUESDAY());
$map->remove(WeekDay::WEDNESDAY());
$this->assertSame(null, $map->get(WeekDay::TUESDAY()));
$this->assertSame(0, $map->size());
}
public function testClear() : void
{
$map = new EnumMap(WeekDay::class, 'string', true);
$map->put(WeekDay::TUESDAY(), 'foo');
$map->clear();
$this->assertSame(null, $map->get(WeekDay::TUESDAY()));
$this->assertSame(0, $map->size());
}
public function testEqualsWithSameInstance() : void
{
$map = new EnumMap(WeekDay::class, 'string', true);
$this->assertTrue($map->equals($map));
}
public function testEqualsWithDifferentSize() : void
{
$mapA = new EnumMap(WeekDay::class, 'string', true);
$mapB = new EnumMap(WeekDay::class, 'string', true);
$mapB->put(WeekDay::MONDAY(), 'foo');
$this->assertFalse($mapA->equals($mapB));
}
public function testEqualsWithDifferentValues() : void
{
$mapA = new EnumMap(WeekDay::class, 'string', true);
$mapA->put(WeekDay::MONDAY(), 'foo');
$mapB = new EnumMap(WeekDay::class, 'string', true);
$mapB->put(WeekDay::MONDAY(), 'bar');
$this->assertFalse($mapA->equals($mapB));
}
public function testEqualsWithDifferentConstants() : void
{
$mapA = new EnumMap(WeekDay::class, 'string', true);
$mapA->put(WeekDay::MONDAY(), 'foo');
$mapB = new EnumMap(WeekDay::class, 'string', true);
$mapB->put(WeekDay::TUESDAY(), 'foo');
$this->assertFalse($mapA->equals($mapB));
}
public function testValues() : void
{
$map = new EnumMap(WeekDay::class, 'string', true);
$this->assertSame([], $map->values());
$map->put(WeekDay::FRIDAY(), 'foo');
$map->put(WeekDay::TUESDAY(), 'bar');
$map->put(WeekDay::SUNDAY(), null);
$this->assertSame(['bar', 'foo', null], $map->values());
}
public function testSerializeAndUnserialize() : void
{
$mapA = new EnumMap(WeekDay::class, 'string', true);
$mapA->put(WeekDay::MONDAY(), 'foo');
$mapB = unserialize(serialize($mapA));
$this->assertTrue($mapA->equals($mapB));
}
public function testIterator() : void
{
$map = new EnumMap(WeekDay::class, 'string', true);
$map->put(WeekDay::FRIDAY(), 'foo');
$map->put(WeekDay::TUESDAY(), 'bar');
$map->put(WeekDay::SUNDAY(), null);
$result = [];
foreach ($map as $key => $value) {
$result[$key->ordinal()] = $value;
}
$this->assertSame([1 => 'bar', 4 => 'foo', 6 => null], $result);
}
}
Common/ErrorCorrectionLevelTest.php 0000644 00000001417 15025112054 0013454 0 ustar 00 assertSame(0x0, ErrorCorrectionLevel::M()->getBits());
$this->assertSame(0x1, ErrorCorrectionLevel::L()->getBits());
$this->assertSame(0x2, ErrorCorrectionLevel::H()->getBits());
$this->assertSame(0x3, ErrorCorrectionLevel::Q()->getBits());
}
public function testInvalidErrorCorrectionLevelThrowsException() : void
{
$this->expectException(OutOfBoundsException::class);
ErrorCorrectionLevel::forBits(4);
}
}
Common/ModeTest.php 0000644 00000001026 15025112054 0010223 0 ustar 00 assertSame(0x0, Mode::TERMINATOR()->getBits());
$this->assertSame(0x1, Mode::NUMERIC()->getBits());
$this->assertSame(0x2, Mode::ALPHANUMERIC()->getBits());
$this->assertSame(0x4, Mode::BYTE()->getBits());
$this->assertSame(0x8, Mode::KANJI()->getBits());
}
}
Common/FormatInformationTest.php 0000644 00000005651 15025112054 0013005 0 ustar 00 assertSame(0, FormatInformation::numBitsDiffering(1, 1));
$this->assertSame(1, FormatInformation::numBitsDiffering(0, 2));
$this->assertSame(2, FormatInformation::numBitsDiffering(1, 2));
$this->assertEquals(32, FormatInformation::numBitsDiffering(-1, 0));
}
public function testDecode() : void
{
$expected = FormatInformation::decodeFormatInformation(
self::MASKED_TEST_FORMAT_INFO,
self::MASKED_TEST_FORMAT_INFO
);
$this->assertNotNull($expected);
$this->assertSame(7, $expected->getDataMask());
$this->assertSame(ErrorCorrectionLevel::Q(), $expected->getErrorCorrectionLevel());
$this->assertEquals(
$expected,
FormatInformation::decodeFormatInformation(
self::UNMAKSED_TEST_FORMAT_INFO,
self::MASKED_TEST_FORMAT_INFO
)
);
}
public function testDecodeWithBitDifference() : void
{
$expected = FormatInformation::decodeFormatInformation(
self::MASKED_TEST_FORMAT_INFO,
self::MASKED_TEST_FORMAT_INFO
);
$this->assertEquals(
$expected,
FormatInformation::decodeFormatInformation(
self::MASKED_TEST_FORMAT_INFO ^ 0x1,
self::MASKED_TEST_FORMAT_INFO ^ 0x1
)
);
$this->assertEquals(
$expected,
FormatInformation::decodeFormatInformation(
self::MASKED_TEST_FORMAT_INFO ^ 0x3,
self::MASKED_TEST_FORMAT_INFO ^ 0x3
)
);
$this->assertEquals(
$expected,
FormatInformation::decodeFormatInformation(
self::MASKED_TEST_FORMAT_INFO ^ 0x7,
self::MASKED_TEST_FORMAT_INFO ^ 0x7
)
);
$this->assertNull(
FormatInformation::decodeFormatInformation(
self::MASKED_TEST_FORMAT_INFO ^ 0xf,
self::MASKED_TEST_FORMAT_INFO ^ 0xf
)
);
}
public function testDecodeWithMisRead() : void
{
$expected = FormatInformation::decodeFormatInformation(
self::MASKED_TEST_FORMAT_INFO,
self::MASKED_TEST_FORMAT_INFO
);
$this->assertEquals(
$expected,
FormatInformation::decodeFormatInformation(
self::MASKED_TEST_FORMAT_INFO ^ 0x3,
self::MASKED_TEST_FORMAT_INFO ^ 0xf
)
);
}
}
Common/BitUtilsTest.php 0000644 00000001420 15025112054 0011074 0 ustar 00 assertSame(1, BitUtils::unsignedRightShift(1, 0));
$this->assertSame(1, BitUtils::unsignedRightShift(10, 3));
$this->assertSame(536870910, BitUtils::unsignedRightShift(-10, 3));
}
public function testNumberOfTrailingZeros() : void
{
$this->assertSame(32, BitUtils::numberOfTrailingZeros(0));
$this->assertSame(1, BitUtils::numberOfTrailingZeros(10));
$this->assertSame(0, BitUtils::numberOfTrailingZeros(15));
$this->assertSame(2, BitUtils::numberOfTrailingZeros(20));
}
}
Common/BitArrayTest.php 0000644 00000013645 15025112054 0011066 0 ustar 00 assertFalse($array->get($i));
$array->set($i);
$this->assertTrue($array->get($i));
}
}
public function testGetNextSet1() : void
{
$array = new BitArray(32);
for ($i = 0; $i < $array->getSize(); ++$i) {
if ($this->getPhpUnitMajorVersion() === 7) {
$this->assertEquals($i, 32, '', $array->getNextSet($i));
} else {
$this->assertEqualsWithDelta($i, 32, $array->getNextSet($i));
}
}
$array = new BitArray(33);
for ($i = 0; $i < $array->getSize(); ++$i) {
if ($this->getPhpUnitMajorVersion() === 7) {
$this->assertEquals($i, 33, '', $array->getNextSet($i));
} else {
$this->assertEqualsWithDelta($i, 33, $array->getNextSet($i));
}
}
}
public function testGetNextSet2() : void
{
$array = new BitArray(33);
for ($i = 0; $i < $array->getSize(); ++$i) {
if ($this->getPhpUnitMajorVersion() === 7) {
$this->assertEquals($i, $i <= 31 ? 31 : 33, '', $array->getNextSet($i));
} else {
$this->assertEqualsWithDelta($i, $i <= 31 ? 31 : 33, $array->getNextSet($i));
}
}
$array = new BitArray(33);
for ($i = 0; $i < $array->getSize(); ++$i) {
if ($this->getPhpUnitMajorVersion() === 7) {
$this->assertEquals($i, 32, '', $array->getNextSet($i));
} else {
$this->assertEqualsWithDelta($i, 32, $array->getNextSet($i));
}
}
}
public function testGetNextSet3() : void
{
$array = new BitArray(63);
$array->set(31);
$array->set(32);
for ($i = 0; $i < $array->getSize(); ++$i) {
if ($i <= 31) {
$expected = 31;
} elseif ($i <= 32) {
$expected = 32;
} else {
$expected = 63;
}
if ($this->getPhpUnitMajorVersion() === 7) {
$this->assertEquals($i, $expected, '', $array->getNextSet($i));
} else {
$this->assertEqualsWithDelta($i, $expected, $array->getNextSet($i));
}
}
}
public function testGetNextSet4() : void
{
$array = new BitArray(63);
$array->set(33);
$array->set(40);
for ($i = 0; $i < $array->getSize(); ++$i) {
if ($i <= 33) {
$expected = 33;
} elseif ($i <= 40) {
$expected = 40;
} else {
$expected = 63;
}
if ($this->getPhpUnitMajorVersion() === 7) {
$this->assertEquals($i, $expected, '', $array->getNextSet($i));
} else {
$this->assertEqualsWithDelta($i, $expected, $array->getNextSet($i));
}
}
}
public function testGetNextSet5() : void
{
mt_srand(0xdeadbeef, MT_RAND_PHP);
for ($i = 0; $i < 10; ++$i) {
$array = new BitArray(mt_rand(1, 100));
$numSet = mt_rand(0, 19);
for ($j = 0; $j < $numSet; ++$j) {
$array->set(mt_rand(0, $array->getSize() - 1));
}
$numQueries = mt_rand(0, 19);
for ($j = 0; $j < $numQueries; ++$j) {
$query = mt_rand(0, $array->getSize() - 1);
$expected = $query;
while ($expected < $array->getSize() && ! $array->get($expected)) {
++$expected;
}
$actual = $array->getNextSet($query);
if ($actual !== $expected) {
$array->getNextSet($query);
}
$this->assertEquals($expected, $actual);
}
}
}
public function testSetBulk() : void
{
$array = new BitArray(64);
$array->setBulk(32, 0xFFFF0000);
for ($i = 0; $i < 48; ++$i) {
$this->assertFalse($array->get($i));
}
for ($i = 48; $i < 64; ++$i) {
$this->assertTrue($array->get($i));
}
}
public function testClear() : void
{
$array = new BitArray(32);
for ($i = 0; $i < 32; ++$i) {
$array->set($i);
}
$array->clear();
for ($i = 0; $i < 32; ++$i) {
$this->assertFalse($array->get($i));
}
}
public function testGetArray() : void
{
$array = new BitArray(64);
$array->set(0);
$array->set(63);
$ints = $array->getBitArray();
$this->assertSame(1, $ints[0]);
$this->assertSame(0x80000000, $ints[1]);
}
public function testIsRange() : void
{
$array = new BitArray(64);
$this->assertTrue($array->isRange(0, 64, false));
$this->assertFalse($array->isRange(0, 64, true));
$array->set(32);
$this->assertTrue($array->isRange(32, 33, true));
$array->set(31);
$this->assertTrue($array->isRange(31, 33, true));
$array->set(34);
$this->assertFalse($array->isRange(31, 35, true));
for ($i = 0; $i < 31; ++$i) {
$array->set($i);
}
$this->assertTrue($array->isRange(0, 33, true));
for ($i = 33; $i < 64; ++$i) {
$array->set($i);
}
$this->assertTrue($array->isRange(0, 64, true));
$this->assertFalse($array->isRange(0, 64, false));
}
}
Common/BitMatrixTest.php 0000644 00000006240 15025112054 0011245 0 ustar 00 assertEquals(33, $matrix->getHeight());
for ($y = 0; $y < 33; ++$y) {
for ($x = 0; $x < 33; ++$x) {
if ($y * $x % 3 === 0) {
$matrix->set($x, $y);
}
}
}
for ($y = 0; $y < 33; $y++) {
for ($x = 0; $x < 33; ++$x) {
$this->assertSame(0 === $x * $y % 3, $matrix->get($x, $y));
}
}
}
public function testSetRegion() : void
{
$matrix = new BitMatrix(5);
$matrix->setRegion(1, 1, 3, 3);
for ($y = 0; $y < 5; ++$y) {
for ($x = 0; $x < 5; ++$x) {
$this->assertSame($y >= 1 && $y <= 3 && $x >= 1 && $x <= 3, $matrix->get($x, $y));
}
}
}
public function testRectangularMatrix() : void
{
$matrix = new BitMatrix(75, 20);
$this->assertSame(75, $matrix->getWidth());
$this->assertSame(20, $matrix->getHeight());
$matrix->set(10, 0);
$matrix->set(11, 1);
$matrix->set(50, 2);
$matrix->set(51, 3);
$matrix->flip(74, 4);
$matrix->flip(0, 5);
$this->assertTrue($matrix->get(10, 0));
$this->assertTrue($matrix->get(11, 1));
$this->assertTrue($matrix->get(50, 2));
$this->assertTrue($matrix->get(51, 3));
$this->assertTrue($matrix->get(74, 4));
$this->assertTrue($matrix->get(0, 5));
$matrix->flip(50, 2);
$matrix->flip(51, 3);
$this->assertFalse($matrix->get(50, 2));
$this->assertFalse($matrix->get(51, 3));
}
public function testRectangularSetRegion() : void
{
$matrix = new BitMatrix(320, 240);
$this->assertSame(320, $matrix->getWidth());
$this->assertSame(240, $matrix->getHeight());
$matrix->setRegion(105, 22, 80, 12);
for ($y = 0; $y < 240; ++$y) {
for ($x = 0; $x < 320; ++$x) {
$this->assertEquals($y >= 22 && $y < 34 && $x >= 105 && $x < 185, $matrix->get($x, $y));
}
}
}
public function testGetRow() : void
{
$matrix = new BitMatrix(102, 5);
for ($x = 0; $x < 102; ++$x) {
if (0 === ($x & 3)) {
$matrix->set($x, 2);
}
}
$array1 = $matrix->getRow(2, null);
$this->assertSame(102, $array1->getSize());
$array2 = new BitArray(60);
$array2 = $matrix->getRow(2, $array2);
$this->assertSame(102, $array2->getSize());
$array3 = new BitArray(200);
$array3 = $matrix->getRow(2, $array3);
$this->assertSame(200, $array3->getSize());
for ($x = 0; $x < 102; ++$x) {
$on = (0 === ($x & 3));
$this->assertSame($on, $array1->get($x));
$this->assertSame($on, $array2->get($x));
$this->assertSame($on, $array3->get($x));
}
}
}
Common/VersionTest.php 0000644 00000004415 15025112054 0010771 0 ustar 00 assertNotNull($version);
$this->assertEquals($versionNumber, $version->getVersionNumber());
$this->assertNotNull($version->getAlignmentPatternCenters());
if ($versionNumber > 1) {
$this->assertTrue(count($version->getAlignmentPatternCenters()) > 0);
}
$this->assertEquals($dimension, $version->getDimensionForVersion());
$this->assertNotNull($version->getEcBlocksForLevel(ErrorCorrectionLevel::H()));
$this->assertNotNull($version->getEcBlocksForLevel(ErrorCorrectionLevel::L()));
$this->assertNotNull($version->getEcBlocksForLevel(ErrorCorrectionLevel::M()));
$this->assertNotNull($version->getEcBlocksForLevel(ErrorCorrectionLevel::Q()));
$this->assertNotNull($version->buildFunctionPattern());
}
/**
* @dataProvider versions
*/
public function testGetProvisionalVersionForDimension(int $versionNumber, int $dimension) : void
{
$this->assertSame(
$versionNumber,
Version::getProvisionalVersionForDimension($dimension)->getVersionNumber()
);
}
/**
* @dataProvider decodeInformation
*/
public function testDecodeVersionInformation(int $expectedVersion, int $mask) : void
{
$version = Version::decodeVersionInformation($mask);
$this->assertNotNull($version);
$this->assertSame($expectedVersion, $version->getVersionNumber());
}
}
Common/ReedSolomonCodecTest.php 0000644 00000006051 15025112054 0012526 0 ustar 00 encode($block, $parity);
// Copy parity into test blocks
for ($i = 0; $i < $numRoots; ++$i) {
$block[$i + $dataSize] = $parity[$i];
$tBlock[$i + $dataSize] = $parity[$i];
}
// Seed with errors
for ($i = 0; $i < $errors; ++$i) {
$errorValue = mt_rand(1, $blockSize);
do {
$errorLocation = mt_rand(0, $blockSize);
} while (0 !== $errorLocations[$errorLocation]);
$errorLocations[$errorLocation] = 1;
if (mt_rand(0, 1)) {
$erasures[] = $errorLocation;
}
$tBlock[$errorLocation] ^= $errorValue;
}
$erasures = SplFixedArray::fromArray($erasures, false);
// Decode the errored block
$foundErrors = $codec->decode($tBlock, $erasures);
if ($errors > 0 && null === $foundErrors) {
$this->assertSame($block, $tBlock, 'Decoder failed to correct errors');
}
$this->assertSame($errors, $foundErrors, 'Found errors do not equal expected errors');
for ($i = 0; $i < $foundErrors; ++$i) {
if (0 === $errorLocations[$erasures[$i]]) {
$this->fail(sprintf('Decoder indicates error in location %d without error', $erasures[$i]));
}
}
$this->assertEquals($block, $tBlock, 'Decoder did not correct errors');
}
}
}
Integration/__snapshots__/files/ImagickRenderingTest__testGenericQrCode__1.png 0000644 00000006047 15025112054 0023671 0 ustar 00 PNG
IHDR DS gAMA a cHRM z&