Skip to content

Commit

Permalink
chore: makes lookup for Map getter to be case insensitive (#137). (#139)
Browse files Browse the repository at this point in the history
  • Loading branch information
jcchavezs committed Apr 24, 2020
1 parent 3a3ae88 commit 7df3e2b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/Zipkin/Propagation/Map.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@ final class Map implements Getter, Setter
{
/**
* {@inheritdoc}
*
* If the carrier is an array, the lookup is case insensitive, this is
* mainly because Map getter is commonly used for those cases where the
* HTTP framework does not follow the PSR request/response objects (e.g.
* Symfony) and thus the header bag should be treated as a map. ArrayAccess
* can't be case insensitive because we can not know the keys on beforehand.
*
* @param array|ArrayAccess $carrier
*/
public function get($carrier, $key)
Expand All @@ -21,7 +28,12 @@ public function get($carrier, $key)
}

if (is_array($carrier)) {
return array_key_exists($lKey, $carrier) ? $carrier[$lKey] : null;
if (empty($carrier)) {
return null;
}

$lcCarrier = array_change_key_case($carrier, CASE_LOWER);
return array_key_exists($lKey, $lcCarrier) ? $lcCarrier[$lKey] : null;
}

throw InvalidPropagationCarrier::forCarrier($carrier);
Expand All @@ -41,6 +53,8 @@ public function put(&$carrier, $key, $value)
throw InvalidPropagationKey::forEmptyKey();
}

// Lowercasing the key was a first attempt to be compatible with the
// getter when using the Map getter for HTTP headers.
$lKey = strtolower($key);

if ($carrier instanceof ArrayAccess || is_array($carrier)) {
Expand Down
17 changes: 17 additions & 0 deletions tests/Unit/Propagation/MapTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
final class MapTest extends PHPUnit_Framework_TestCase
{
const TEST_KEY = 'test_key';
const TEST_KEY_INSENSITIVE = 'tEsT_KEy';
const TEST_VALUE = 'test_value';
const TEST_INVALID_KEY = 1;
const TEST_EMPTY_KEY = '';
Expand All @@ -32,6 +33,22 @@ public function testGetFromMapSuccessForArrayAccessCarrier()
$this->assertEquals(self::TEST_VALUE, $value);
}

public function testGetFromMapCaseInsensitiveSuccess()
{
$carrier = [self::TEST_KEY_INSENSITIVE => self::TEST_VALUE];
$map = new Map();
$value = $map->get($carrier, self::TEST_KEY);
$this->assertEquals(self::TEST_VALUE, $value);
}

public function testGetFromMapCaseInsensitiveReturnsNull()
{
$carrier = new ArrayObject([self::TEST_KEY_INSENSITIVE => self::TEST_VALUE]);
$map = new Map();
$value = $map->get($carrier, self::TEST_KEY);
$this->assertNull($value);
}

public function testPutToMapFailsDueToInvalidKey()
{
$carrier = new ArrayObject();
Expand Down

0 comments on commit 7df3e2b

Please sign in to comment.