Skip to content

Commit

Permalink
feat: try to convert non-string tags to strings
Browse files Browse the repository at this point in the history
BREAKING CHANGE: addTags only accepts null and strings as $value. And InvalidArgumentException is thrown when a non-string value cannot be converted to string

Refs: #145
  • Loading branch information
mkrauser committed Jul 28, 2023
1 parent f72f191 commit 2252cff
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
## 3.5.0 [unreleased]

1. [#146](https://github.com/influxdata/influxdb-client-php/pull/146): Try to convert non-string-tags to strings, throw an exception if a value cannot be converted

## 3.4.0 [2023-07-28]

### Bug Fixes
Expand Down
16 changes: 15 additions & 1 deletion src/InfluxDB2/Point.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public static function fromArray($data): ?Point
* @param [Object] value the tag value
* @return Point
*/
public function addTag($key, $value): Point
public function addTag($key, ?string $value): Point
{
$this->tags[$key] = $value;

Expand Down Expand Up @@ -162,6 +162,20 @@ private function appendTags()
foreach (array_keys($this->tags) as $key) {
$value = $this->tags[$key];

if (!is_string($value) && null !== $value) {
if(
is_scalar($value) ||
(is_object($value) && method_exists($value, '__toString()')) ||
(\PHP_VERSION_ID >= 80000 && $value instanceof \Stringable)
) {
$value = (string) $value;
} else {
throw new \InvalidArgumentException(
sprintf('Tag value for key %s cannot be converted to string', $key)
);
}
}

if ($this->isNullOrEmptyString($key) || $this->isNullOrEmptyString($value)) {
continue;
}
Expand Down
6 changes: 3 additions & 3 deletions tests/PointTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -279,14 +279,14 @@ public function testFromArrayWithoutName()
$this->assertNull($pointArray);
}

public function testTagNotString()
public function testTagNonString()
{
$point = Point::measurement('h2o')
->addTag('location', 'europe')
->addTag('tag_not_string', [])
->addTag('tag_not_string', 4711)
->addTag('tag_not_null', null)
->addField('level', 2);

$this->assertEquals('h2o,location=europe level=2i', $point->toLineProtocol());
$this->assertEquals('h2o,location=europe,tag_not_string=4711 level=2i', $point->toLineProtocol());
}
}

0 comments on commit 2252cff

Please sign in to comment.