Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion Datastore/src/Key.php
Original file line number Diff line number Diff line change
Expand Up @@ -477,13 +477,46 @@ private function determineIdentifierType($identifier, ?string $identifierType):
));
}

if (is_numeric($identifier)) {
if ($this->isInt64($identifier)) {
return self::TYPE_ID;
}

return self::TYPE_NAME;
}

/**
* Check whether the given identifier can be represented as a signed 64-bit integer.
*
* @param mixed $identifier
* @return bool
*/
private function isInt64($identifier): bool
{
if (is_int($identifier)) {
return true;
}

if (!is_string($identifier) || !preg_match('/^-?\d+$/', $identifier)) {
return false;
}

$negative = $identifier[0] === '-';
$digits = ltrim($negative ? substr($identifier, 1) : $identifier, '0');
if ($digits === '') {
return true;
}

$limit = $negative ? '9223372036854775808' : '9223372036854775807';
$len = strlen($digits);
$limitLen = strlen($limit);

if ($len !== $limitLen) {
return $len < $limitLen;
}

return strcmp($digits, $limit) <= 0;
}

/**
* Normalize the internal representation of a path
*
Expand Down
30 changes: 30 additions & 0 deletions Datastore/tests/Unit/KeyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,36 @@ public function testPathElementForceType()
$this->assertEquals(['kind' => 'Robots', 'id' => '1000'], $key->keyObject()['path'][1]);
}

/**
* @dataProvider inferredIdentifierTypeProvider
*/
public function testInferredIdentifierType($identifier, string $expectedType)
{
$key = new Key('foo');
$key->pathElement('Robots', $identifier);

$this->assertEquals($expectedType, $key->pathEndIdentifierType());
$this->assertEquals(['kind' => 'Robots', $expectedType => $identifier], $key->pathEnd());
}

public function inferredIdentifierTypeProvider(): array
{
return [
'int' => [1000, Key::TYPE_ID],
'negative int' => [-42, Key::TYPE_ID],
'numeric string' => ['1000', Key::TYPE_ID],
'zero string' => ['0', Key::TYPE_ID],
'int64 max string' => ['9223372036854775807', Key::TYPE_ID],
'int64 min string' => ['-9223372036854775808', Key::TYPE_ID],
'int64 max plus one' => ['9223372036854775808', Key::TYPE_NAME],
'int64 min minus one' => ['-9223372036854775809', Key::TYPE_NAME],
'32-digit numeric md5' => ['13975337727204308302793171870910', Key::TYPE_NAME],
'scientific notation md5' => ['0e462097431906509019562988736854', Key::TYPE_NAME],
'float string' => ['12.34', Key::TYPE_NAME],
'alphanumeric string' => ['abc123', Key::TYPE_NAME],
];
}

public function testPathElementInvalidIdentifierType()
{
$this->expectException(InvalidArgumentException::class);
Expand Down
Loading