Skip to content

Commit

Permalink
Improve resolve format
Browse files Browse the repository at this point in the history
  • Loading branch information
brendt committed Nov 27, 2018
1 parent 5a0db64 commit a2b3b6b
Showing 1 changed file with 20 additions and 9 deletions.
29 changes: 20 additions & 9 deletions src/Period.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@ public function __construct(DateTimeImmutable $start, DateTimeImmutable $end)
$this->end = $end;
}

public static function make($start, $end, string $format = 'Y-m-d'): Period
public static function make($start, $end, string $format = null): Period
{
return new self(
self::resolveDate($start, $format),
self::resolveDate($end, $format)
);
}

protected static function resolveDate($date, string $format): DateTimeImmutable
protected static function resolveDate($date, ?string $format): DateTimeImmutable
{
if ($date instanceof DateTimeImmutable) {
return $date;
Expand All @@ -42,17 +42,12 @@ protected static function resolveDate($date, string $format): DateTimeImmutable
return DateTimeImmutable::createFromMutable($date);
}

$format = self::resolveFormat($date, $format);

if (! is_string($date)) {
throw InvalidDate::forFormat($date, $format);
}

if (
strpos($format, ' ') === false
&& strpos($date, ' ') !== false
) {
$format = 'Y-m-d H:i:s';
}

$dateTime = DateTimeImmutable::createFromFormat($format, $date);

if ($dateTime === false) {
Expand All @@ -66,6 +61,22 @@ protected static function resolveDate($date, string $format): DateTimeImmutable
return $dateTime;
}

protected static function resolveFormat($date, ?string $format): string
{
if ($format !== null) {
return $format;
}

if (
strpos($format, ' ') === false
&& strpos($date, ' ') !== false
) {
return 'Y-m-d H:i:s';
}

return 'Y-m-d';
}

public function getStart(): DateTimeImmutable
{
return $this->start;
Expand Down

0 comments on commit a2b3b6b

Please sign in to comment.