Skip to content

getMultiple returns invalid values when use a numeric key #39

@arima-ryunosuke

Description

@arima-ryunosuke

Numeric keys (like '1') are valid keys in PSR-16.

However getMultiple returns invalid values because it uses array_merge (array_merge renumbers the numeric index of an array).
It should use array_replace here.

test code:

public function testGetMultipleWithIntegerKeys()
{
    $values = [
        '1' => uniqid('value1', true),
        '2' => uniqid('value2', true),
    ];
    $keys = array_map('strval', array_keys($values));

    $psrCache = new SimpleCacheAdapter(new ArrayCache());
    foreach ($values as $k => $v) {
        $psrCache->set((string) $k, $v);
    }

    $default = uniqid('default', true);
    $invalid_key = uniqid('key3', true);
    $keys[] = $invalid_key;
    $values[$invalid_key] = $default;

    self::assertSame($values, $psrCache->getMultiple($keys, $default));
}

results:

1) RoaveTest\DoctrineSimpleCache\SimpleCacheAdapterTest::testGetMultipleWithIntegerKeys
Failed asserting that two arrays are identical.
--- Expected
+++ Actual
@@ @@
 Array &0 (
-    1 => 'value160519bac1ea400.91716645'
-    2 => 'value260519bac1ea486.88148617'
+    0 => 'default60519bac1ea755.33267710'
+    1 => 'default60519bac1ea755.33267710'
     'key360519bac1ea776.08717164' => 'default60519bac1ea755.33267710'
+    2 => 'value160519bac1ea400.91716645'
+    3 => 'value260519bac1ea486.88148617'
 )

Fix as follows.

public function getMultiple($keys, $default = null) : array
{
    $keys = $this->filterValidateMultipleKeys($keys);
    return array_replace(array_fill_keys($keys, $default), $this->doctrineCache->fetchMultiple($keys));
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions