Skip to content

Commit

Permalink
Merge pull request #394 from tienvx/add-date-matcher-class
Browse files Browse the repository at this point in the history
refactor: Add Date matcher class
  • Loading branch information
tienvx committed Dec 17, 2023
2 parents b673c29 + 99e1a8f commit f51ff78
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/PhpPact/Consumer/Matcher/Matchers/AbstractDateTime.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace PhpPact\Consumer\Matcher\Matchers;

abstract class AbstractDateTime extends GeneratorAwareMatcher
{
public function __construct(protected string $format, private ?string $value = null)
{
}

/**
* @return array<string, string>
*/
protected function getAttributesData(): array
{
return ['format' => $this->format];
}

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

namespace PhpPact\Consumer\Matcher\Matchers;

use PhpPact\Consumer\Matcher\Generators\Date as DateGenerator;

/**
* Matches the string representation of a value against the date format.
*
* NOTE: Java's datetime format is used, not PHP's datetime format
* For Java one, see https://www.digitalocean.com/community/tutorials/java-simpledateformat-java-date-format#patterns
* For PHP one, see https://www.php.net/manual/en/datetime.format.php#refsect1-datetime.format-parameters
*/
class Date extends AbstractDateTime
{
public function __construct(string $format = 'yyyy-MM-dd', ?string $value = null)
{
if ($value === null) {
$this->setGenerator(new DateGenerator($format));
}
parent::__construct($format, $value);
}

public function getType(): string
{
return 'date';
}
}
24 changes: 24 additions & 0 deletions tests/PhpPact/Consumer/Matcher/Matchers/DateTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

namespace PhpPactTest\Consumer\Matcher\Matchers;

use PhpPact\Consumer\Matcher\Matchers\Date;

class DateTest extends GeneratorAwareMatcherTestCase
{
protected function setUp(): void
{
$this->matcher = new Date();
}

/**
* @testWith [null, "{\"pact:matcher:type\":\"date\",\"pact:generator:type\":\"Date\",\"format\":\"yyyy-MM-dd\"}"]
* ["1995-02-04", "{\"pact:matcher:type\":\"date\",\"format\":\"yyyy-MM-dd\",\"value\":\"1995-02-04\"}"]
*/
public function testSerialize(?string $value, string $json): void
{
$format = 'yyyy-MM-dd';
$this->matcher = new Date($format, $value);
$this->assertSame($json, json_encode($this->matcher));
}
}

0 comments on commit f51ff78

Please sign in to comment.