Skip to content

Commit 715f423

Browse files
Merge pull request #93 from transistive/optional-variables
Make the Variable section in the Pattern optional
2 parents 86e4956 + 8f4efee commit 715f423

File tree

3 files changed

+36
-4
lines changed

3 files changed

+36
-4
lines changed

src/Patterns/Pattern.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,17 +35,22 @@
3535
*/
3636
interface Pattern extends QueryConvertible
3737
{
38+
/**
39+
* Returns whether a variable has been set for this pattern.
40+
*/
41+
public function hasVariableSet(): bool;
42+
3843
/**
3944
* Explicitly assign a named variable to this pattern.
4045
*
41-
* @param string|Variable $variable
46+
* @param null|string|Variable $variable
4247
*
4348
* @return $this
4449
*/
4550
public function withVariable($variable): self;
4651

4752
/**
48-
* Returns the variable of this pattern. This function generates a variable if none has been set.
53+
* 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.
4954
*/
5055
public function getVariable(): Variable;
5156
}

src/Traits/PatternTraits/PatternTrait.php

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,24 @@ trait PatternTrait
2424
*/
2525
protected ?Variable $variable = null;
2626

27+
/**
28+
* Returns whether a variable has been set for this pattern.
29+
*/
30+
public function hasVariableSet(): bool
31+
{
32+
return $this->variable !== null;
33+
}
34+
2735
/**
2836
* Explicitly assign a named variable to this object.
2937
*
30-
* @param string|Variable $variable
38+
* @param null|string|Variable $variable
3139
*
3240
* @return $this
3341
*/
3442
public function withVariable($variable): self
3543
{
36-
$this->variable = self::toName($variable);
44+
$this->variable = $variable === null ? null : self::toName($variable);
3745

3846
return $this;
3947
}

tests/unit/Traits/PatternTraits/PatternTraitTest.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,25 @@ public function testDoesNotAcceptAnyType(): void
7272
$this->stub->withVariable(new stdClass());
7373
}
7474

75+
public function testPatternNotSet(): void
76+
{
77+
$this->assertFalse($this->stub->hasVariableSet());
78+
}
79+
80+
public function testPatternSet(): void
81+
{
82+
$this->stub->withVariable("hello");
83+
$this->assertTrue($this->stub->hasVariableSet());
84+
}
85+
86+
public function testPatternUnSet(): void
87+
{
88+
$this->stub->withVariable("hello");
89+
$this->stub->withVariable(null);
90+
91+
$this->assertFalse($this->stub->hasVariableSet());
92+
}
93+
7594
/**
7695
* @doesNotPerformAssertions
7796
*/

0 commit comments

Comments
 (0)