Skip to content

Commit

Permalink
Convert carrier key to string in Zipkin\Propagation\Map (#5780)
Browse files Browse the repository at this point in the history
  • Loading branch information
huangdijia committed Jun 1, 2023
1 parent 7be4124 commit 88512a2
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
79 changes: 79 additions & 0 deletions class_map/Map.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Zipkin\Propagation;

use ArrayAccess;
use Zipkin\Propagation\Exceptions\InvalidPropagationCarrier;
use Zipkin\Propagation\Exceptions\InvalidPropagationKey;

use function is_array;

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, string $key): ?string
{
$lKey = \strtolower($key);

if ($carrier instanceof ArrayAccess) {
return $carrier->offsetExists($lKey) ? $carrier->offsetGet($lKey) : null;
}

if (is_array($carrier)) {
if (empty($carrier)) {
return null;
}

foreach ($carrier as $k => $value) {
if (strtolower((string) $k) === $lKey) {
return $value;
}
}

return null;
}

throw InvalidPropagationCarrier::forCarrier($carrier);
}

/**
* {@inheritdoc}
* @param array|ArrayAccess $carrier
*/
public function put(&$carrier, string $key, string $value): void
{
if ($key === '') {
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)) {
$carrier[$lKey] = $value;
return;
}

throw InvalidPropagationCarrier::forCarrier($carrier);
}
}
2 changes: 2 additions & 0 deletions src/ConfigProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Hyperf\Tracer\Listener\DbQueryExecutedListener;
use Jaeger\ThriftUdpTransport;
use OpenTracing\Tracer;
use Zipkin\Propagation\Map;

class ConfigProvider
{
Expand All @@ -36,6 +37,7 @@ public function __invoke(): array
'annotations' => [
'scan' => [
'class_map' => [
Map::class => __DIR__ . '/../class_map/Map.php',
ThriftUdpTransport::class => __DIR__ . '/../class_map/ThriftUdpTransport.php',
],
],
Expand Down

0 comments on commit 88512a2

Please sign in to comment.