Skip to content

Commit

Permalink
Merge pull request #93 from transistive/optional-variables
Browse files Browse the repository at this point in the history
Make the Variable section in the Pattern optional
  • Loading branch information
marijnvanwezel committed May 3, 2023
2 parents 86e4956 + 8f4efee commit 715f423
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 4 deletions.
9 changes: 7 additions & 2 deletions src/Patterns/Pattern.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
12 changes: 10 additions & 2 deletions src/Traits/PatternTraits/PatternTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
19 changes: 19 additions & 0 deletions tests/unit/Traits/PatternTraits/PatternTraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down

0 comments on commit 715f423

Please sign in to comment.