-
-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
e041c42
commit af71e16
Showing
2 changed files
with
86 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace Spiral\RoadRunner\GRPC; | ||
|
||
use Spiral\RoadRunner\GRPC\Internal\Json; | ||
|
||
/** | ||
* @psalm-type THeaderKey = non-empty-string | ||
* @psalm-type THeaderValue = string | ||
* @implements \IteratorAggregate<THeaderKey, string> | ||
*/ | ||
final class ResponseTrailers implements \IteratorAggregate, \Countable | ||
{ | ||
/** | ||
* @var array<THeaderKey, THeaderValue> | ||
*/ | ||
private array $trailers = []; | ||
|
||
/** | ||
* @param iterable<THeaderKey, THeaderValue> $trailers | ||
*/ | ||
public function __construct(iterable $trailers = []) | ||
{ | ||
foreach ($trailers as $key => $value) { | ||
$this->set($key, $value); | ||
} | ||
} | ||
|
||
/** | ||
* @param THeaderKey $key | ||
* @param THeaderValue $value | ||
*/ | ||
public function set(string $key, string $value): void | ||
{ | ||
$this->trailers[$key] = $value; | ||
} | ||
|
||
/** | ||
* @param THeaderKey $key | ||
* @param string|null $default | ||
* @return THeaderValue|null | ||
*/ | ||
public function get(string $key, string $default = null): ?string | ||
{ | ||
return $this->trailers[$key] ?? $default; | ||
} | ||
|
||
public function getIterator(): \Traversable | ||
{ | ||
return new \ArrayIterator($this->trailers); | ||
} | ||
|
||
public function count(): int | ||
{ | ||
return \count($this->trailers); | ||
} | ||
|
||
/** | ||
* @throws \JsonException | ||
*/ | ||
public function packTrailers(): string | ||
{ | ||
// If an empty array is serialized, it is cast to the string "[]" | ||
// instead of object string "{}" | ||
if ($this->trailers === []) { | ||
return '{}'; | ||
} | ||
|
||
return Json::encode($this->trailers); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters