Skip to content

Commit

Permalink
Allow retrieving a single piece of data from the span by it’s key
Browse files Browse the repository at this point in the history
  • Loading branch information
stayallive committed Aug 1, 2024
1 parent 6222d31 commit 03a6795
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 6 deletions.
18 changes: 12 additions & 6 deletions src/Tracing/Span.php
Original file line number Diff line number Diff line change
Expand Up @@ -357,18 +357,24 @@ public function setSampled(?bool $sampled)
}

/**
* Gets a map of arbitrary data.
* Gets a map of arbitrary data or a specific key from the map of data attached to this span.
*
* @return array<string, mixed>
* @param string|null $key Select a specific key from the data to return the value of
* @param mixed $default When the $key is not found, return this value
*
* @return ($key is null ? array<string, mixed> : mixed|null)
*/
public function getData(): array
public function getData(?string $key = null, $default = null)
{
return $this->data;
if ($key === null) {
return $this->data;
}

return $this->data[$key] ?? $default;
}

/**
* Sets a map of arbitrary data. This method will merge the given data with
* the existing one.
* Sets a map of arbitrary data. This method will merge the given data with the existing one.
*
* @param array<string, mixed> $data The data
*
Expand Down
37 changes: 37 additions & 0 deletions tests/Tracing/SpanTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -272,4 +272,41 @@ public function testMetricsSummary(): void
],
], $span->getMetricsSummary());
}

public function testDataGetter(): void
{
$span = new Span();

$initialData = [
'foo' => 'bar',
'baz' => 1,
];

$span->setData($initialData);

$this->assertSame($initialData, $span->getData());
$this->assertSame('bar', $span->getData('foo'));
$this->assertSame(1, $span->getData('baz'));
}

public function testDataIsMergedWhenSet(): void
{
$span = new Span();

$span->setData([
'foo' => 'bar',
'baz' => 1,
]);

$span->setData([
'baz' => 2,
]);

$this->assertSame(2, $span->getData('baz'));
$this->assertSame('bar', $span->getData('foo'));
$this->assertSame([
'foo' => 'bar',
'baz' => 2,
], $span->getData());
}
}

0 comments on commit 03a6795

Please sign in to comment.