Skip to content

Commit

Permalink
Merge pull request #413 from tienvx/add-string-value-matcher-class
Browse files Browse the repository at this point in the history
refactor: Add StringValue matcher class
  • Loading branch information
tienvx committed Dec 17, 2023
2 parents eb1ce56 + 7be55cc commit 90783d4
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/PhpPact/Consumer/Matcher/Matchers/StringValue.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

namespace PhpPact\Consumer\Matcher\Matchers;

use PhpPact\Consumer\Matcher\Generators\RandomString;

/**
* There is no matcher for string. We re-use `type` matcher.
*/
class StringValue extends GeneratorAwareMatcher
{
public function __construct(private ?string $value = null)
{
if ($value === null) {
$this->setGenerator(new RandomString());
}
}

public function getType(): string
{
return 'type';
}

/**
* @return array<string, mixed>
*/
public function jsonSerialize(): array
{
$data = [
'pact:matcher:type' => $this->getType(),
'value' => $this->getValue() ?? 'some string',
];

if ($this->getGenerator()) {
return $data + ['pact:generator:type' => $this->getGenerator()->getType()] + $this->getMergedAttributes()->getData();
}

return $data;
}

protected function getAttributesData(): array
{
return [];
}

protected function getValue(): ?string
{
return $this->value;
}
}
26 changes: 26 additions & 0 deletions tests/PhpPact/Consumer/Matcher/Matchers/StringValueTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace PhpPactTest\Consumer\Matcher\Matchers;

use PhpPact\Consumer\Matcher\Matchers\StringValue;
use PHPUnit\Framework\TestCase;

class StringValueTest extends TestCase
{
protected StringValue $matcher;

protected function setUp(): void
{
$this->matcher = new StringValue();
}

/**
* @testWith [null, "{\"pact:matcher:type\":\"type\",\"value\":\"some string\",\"pact:generator:type\":\"RandomString\",\"size\":10}"]
* ["test", "{\"pact:matcher:type\":\"type\",\"value\":\"test\"}"]
*/
public function testSerialize(?string $value, string $json): void
{
$this->matcher = new StringValue($value);
$this->assertSame($json, json_encode($this->matcher));
}
}

0 comments on commit 90783d4

Please sign in to comment.