|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | +/** |
| 5 | + * This file is part of Hyperf. |
| 6 | + * |
| 7 | + * @link https://www.hyperf.io |
| 8 | + * @document https://hyperf.wiki |
| 9 | + |
| 10 | + * @license https://github.com/hyperf/hyperf/blob/master/LICENSE |
| 11 | + */ |
| 12 | +namespace Zipkin\Propagation; |
| 13 | + |
| 14 | +use ArrayAccess; |
| 15 | +use Zipkin\Propagation\Exceptions\InvalidPropagationCarrier; |
| 16 | +use Zipkin\Propagation\Exceptions\InvalidPropagationKey; |
| 17 | + |
| 18 | +use function is_array; |
| 19 | + |
| 20 | +class Map implements Getter, Setter |
| 21 | +{ |
| 22 | + /** |
| 23 | + * {@inheritdoc} |
| 24 | + * |
| 25 | + * If the carrier is an array, the lookup is case insensitive, this is |
| 26 | + * mainly because Map getter is commonly used for those cases where the |
| 27 | + * HTTP framework does not follow the PSR request/response objects (e.g. |
| 28 | + * Symfony) and thus the header bag should be treated as a map. ArrayAccess |
| 29 | + * can't be case insensitive because we can not know the keys on beforehand. |
| 30 | + * |
| 31 | + * @param array|ArrayAccess $carrier |
| 32 | + */ |
| 33 | + public function get($carrier, string $key): ?string |
| 34 | + { |
| 35 | + $lKey = \strtolower($key); |
| 36 | + |
| 37 | + if ($carrier instanceof ArrayAccess) { |
| 38 | + return $carrier->offsetExists($lKey) ? $carrier->offsetGet($lKey) : null; |
| 39 | + } |
| 40 | + |
| 41 | + if (is_array($carrier)) { |
| 42 | + if (empty($carrier)) { |
| 43 | + return null; |
| 44 | + } |
| 45 | + |
| 46 | + foreach ($carrier as $k => $value) { |
| 47 | + if (strtolower((string) $k) === $lKey) { |
| 48 | + return $value; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return null; |
| 53 | + } |
| 54 | + |
| 55 | + throw InvalidPropagationCarrier::forCarrier($carrier); |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * {@inheritdoc} |
| 60 | + * @param array|ArrayAccess $carrier |
| 61 | + */ |
| 62 | + public function put(&$carrier, string $key, string $value): void |
| 63 | + { |
| 64 | + if ($key === '') { |
| 65 | + throw InvalidPropagationKey::forEmptyKey(); |
| 66 | + } |
| 67 | + |
| 68 | + // Lowercasing the key was a first attempt to be compatible with the |
| 69 | + // getter when using the Map getter for HTTP headers. |
| 70 | + $lKey = \strtolower($key); |
| 71 | + |
| 72 | + if ($carrier instanceof ArrayAccess || is_array($carrier)) { |
| 73 | + $carrier[$lKey] = $value; |
| 74 | + return; |
| 75 | + } |
| 76 | + |
| 77 | + throw InvalidPropagationCarrier::forCarrier($carrier); |
| 78 | + } |
| 79 | +} |
0 commit comments