From 8f4efee614d006b5793fbb8edc6b0a09aaf89564 Mon Sep 17 00:00:00 2001 From: Ghlen Nagels Date: Wed, 3 May 2023 17:01:32 +0530 Subject: [PATCH] added tests and nullable functionality/querying for variables in patterns --- src/Patterns/Pattern.php | 9 +++++++-- src/Traits/PatternTraits/PatternTrait.php | 12 ++++++++++-- .../Traits/PatternTraits/PatternTraitTest.php | 19 +++++++++++++++++++ 3 files changed, 36 insertions(+), 4 deletions(-) diff --git a/src/Patterns/Pattern.php b/src/Patterns/Pattern.php index 3880611..a3daba2 100644 --- a/src/Patterns/Pattern.php +++ b/src/Patterns/Pattern.php @@ -35,17 +35,22 @@ */ interface Pattern extends QueryConvertible { + /** + * Returns whether a variable has been set for this pattern. + */ + public function hasVariableSet(): bool; + /** * Explicitly assign a named variable to this pattern. * - * @param string|Variable $variable + * @param null|string|Variable $variable * * @return $this */ public function withVariable($variable): self; /** - * Returns the variable of this pattern. This function generates a variable if none has been set. + * Returns the variable of this pattern. This function generates a variable if none has been set. It will implicitly set the variable of the pattern as well. */ public function getVariable(): Variable; } diff --git a/src/Traits/PatternTraits/PatternTrait.php b/src/Traits/PatternTraits/PatternTrait.php index 1e8e8bd..6fd8514 100644 --- a/src/Traits/PatternTraits/PatternTrait.php +++ b/src/Traits/PatternTraits/PatternTrait.php @@ -24,16 +24,24 @@ trait PatternTrait */ protected ?Variable $variable = null; + /** + * Returns whether a variable has been set for this pattern. + */ + public function hasVariableSet(): bool + { + return $this->variable !== null; + } + /** * Explicitly assign a named variable to this object. * - * @param string|Variable $variable + * @param null|string|Variable $variable * * @return $this */ public function withVariable($variable): self { - $this->variable = self::toName($variable); + $this->variable = $variable === null ? null : self::toName($variable); return $this; } diff --git a/tests/unit/Traits/PatternTraits/PatternTraitTest.php b/tests/unit/Traits/PatternTraits/PatternTraitTest.php index cbb9ce5..3e767f8 100644 --- a/tests/unit/Traits/PatternTraits/PatternTraitTest.php +++ b/tests/unit/Traits/PatternTraits/PatternTraitTest.php @@ -72,6 +72,25 @@ public function testDoesNotAcceptAnyType(): void $this->stub->withVariable(new stdClass()); } + public function testPatternNotSet(): void + { + $this->assertFalse($this->stub->hasVariableSet()); + } + + public function testPatternSet(): void + { + $this->stub->withVariable("hello"); + $this->assertTrue($this->stub->hasVariableSet()); + } + + public function testPatternUnSet(): void + { + $this->stub->withVariable("hello"); + $this->stub->withVariable(null); + + $this->assertFalse($this->stub->hasVariableSet()); + } + /** * @doesNotPerformAssertions */