-
Notifications
You must be signed in to change notification settings - Fork 0
/
IsDate.php
67 lines (55 loc) · 1.48 KB
/
IsDate.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php
declare(strict_types=1);
namespace PHPUnitExtraConstraints\Constraint;
use DateTime;
use Exception;
use PHPUnit\Framework\Constraint\Constraint;
use SebastianBergmann\Diff\Differ;
use SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder;
use function is_string;
/**
* Constraint that asserts that a string is a valid date according a given format.
*/
final class IsDate extends Constraint
{
/** @var string */
private $format;
public function __construct(string $format)
{
$this->format = $format;
}
/**
* @inheritDoc
*/
protected function matches($other): bool
{
if (!is_string($other)) {
return false;
}
$date = DateTime::createFromFormat($this->format, $other);
return $date !== false && $other === $date->format($this->format);
}
/**
* @inheritDoc
*/
protected function additionalFailureDescription($other): string
{
if (!is_string($other)) {
return '';
}
try {
$date = new DateTime($other);
return (new Differ(new UnifiedDiffOutputBuilder("--- Expected\n+++ Actual\n")))
->diff($date->format($this->format), $other);
} catch (Exception $e) {
return 'The string is not parsable as a date';
}
}
/**
* @inheritDoc
*/
public function toString(): string
{
return 'is a string respecting the ' . $this->format . ' datetime format';
}
}