diff --git a/src/EvaluationContextConverter.php b/src/EvaluationContextConverter.php index 0300e1f..2a0a746 100644 --- a/src/EvaluationContextConverter.php +++ b/src/EvaluationContextConverter.php @@ -80,9 +80,10 @@ private function getTargetingKey(?string $targetingKey, $key): string $this->logger->warning("A non-string 'key' attribute was provided."); } - if ($key !== null && is_string($key)) { - // Targeting key takes precedence over key, because targeting key is in the spec. - $targetingKey = $targetingKey ?: $key; + // Targeting key takes precedence over key, because targeting key is in the spec. + // Compare against "" explicitly, because "0" is falsy in PHP but is a valid key. + if (($targetingKey === null || $targetingKey === "") && is_string($key)) { + $targetingKey = $key; } if ($targetingKey === null || $targetingKey === "") { diff --git a/tests/EvaluationContextConverterTest.php b/tests/EvaluationContextConverterTest.php index b70c666..cdf3738 100644 --- a/tests/EvaluationContextConverterTest.php +++ b/tests/EvaluationContextConverterTest.php @@ -58,6 +58,34 @@ public function testTargetingKeyTakesPrecedenceOverAttributeKey(): void $this->assertEquals("should-use", $ldContext->getKey()); } + public function testZeroTargetingKeyTakesPrecedenceOverAttributeKey(): void + { + $attributes = new Attributes(["key" => "do-not-use"]); + $context = new EvaluationContext("0", $attributes); + + $ldContext = $this->contextConverter->toLdContext($context); + + $this->assertTrue($ldContext->isValid()); + $this->assertEquals("0", $ldContext->getKey()); + } + + public function testZeroTargetingKeyTakesPrecedenceOverAttributeKeyInMultiContext(): void + { + $attributes = [ + 'kind' => 'multi', + 'user' => ['targetingKey' => '0', 'key' => 'do-not-use'], + ]; + $context = new EvaluationContext(null, new Attributes($attributes)); + + $ldContext = $this->contextConverter->toLdContext($context); + + $this->assertTrue($ldContext->isValid()); + + /** @var \LaunchDarkly\LDContext */ + $userContext = $ldContext->getIndividualContext("user"); + $this->assertEquals("0", $userContext->getKey()); + } + public function testCreateContextWithKeyAndKind(): void { $attributes = new Attributes(["kind" => "org"]);