Skip to content

Commit

Permalink
Merge pull request #621 from PHPCSStandards/feature/abstractarraydecl…
Browse files Browse the repository at this point in the history
…aration-getactualarraykeys-extra-test

AbstractArrayDeclaration::GetActualArrayKey(): add extra test
  • Loading branch information
jrfnl authored Aug 23, 2024
2 parents 8a1f3f5 + 3179443 commit aee74bb
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -146,3 +146,13 @@ $validStringKeys = array(
'_5_' => 'value5',
'_6_' => 'value6',
);

/* testZeroPrefixedNumericStringKeys */
$validNumericStringKeys = array(
'01' => 'value1',
'002' => 'value2',
'0o3' => 'value3',
'0b1' => 'value4',
'0x7' => 'value5',
'0.0' => 'value6',
);
Original file line number Diff line number Diff line change
Expand Up @@ -173,5 +173,51 @@ public function testStringLiteralsWithNumbers()
. \var_export($expected[$itemNr], true) . ' for item number ' . $itemNr
);
}

// Verify against handling by PHP itself.
$expectedKeys = array_values($expected);
$actualKeys = array_keys(array_combine($expected, $expected));
$this->assertSame($expectedKeys, $actualKeys, 'getActualArrayKey() results do not match PHP native handling');
}

/**
* Test retrieving the actual array key when string keys look like numeric keys but start with 0.
*
* @return void
*/
public function testZeroPrefixedNumericStringKeys()
{
$testObj = new ArrayDeclarationSniffTestDouble();
$testObj->tokens = self::$phpcsFile->getTokens();

$stackPtr = $this->getTargetToken('/* testZeroPrefixedNumericStringKeys */', [\T_ARRAY, \T_OPEN_SHORT_ARRAY]);
$arrayItems = PassedParameters::getParameters(self::$phpcsFile, $stackPtr);

$expected = [
1 => '01',
2 => '002',
3 => '0o3',
4 => '0b1',
5 => '0x7', // phpcs:ignore PHPCompatibility.Miscellaneous.ValidIntegers.HexNumericStringFound
6 => '0.0',
];

$this->assertCount(\count($expected), $arrayItems);

foreach ($arrayItems as $itemNr => $arrayItem) {
$arrowPtr = Arrays::getDoubleArrowPtr(self::$phpcsFile, $arrayItem['start'], $arrayItem['end']);
$result = $testObj->getActualArrayKey(self::$phpcsFile, $arrayItem['start'], ($arrowPtr - 1));
$this->assertSame(
$expected[$itemNr],
$result,
'Failed: actual key ' . \var_export($result, true) . ' is not the same as the expected key '
. \var_export($expected[$itemNr], true) . ' for item number ' . $itemNr
);
}

// Verify against handling by PHP itself.
$expectedKeys = array_values($expected);
$actualKeys = array_keys(array_combine($expected, $expected));
$this->assertSame($expectedKeys, $actualKeys, 'getActualArrayKey() results do not match PHP native handling');
}
}

0 comments on commit aee74bb

Please sign in to comment.