Skip to content

Commit

Permalink
Refactored TimeAgo.php and added test
Browse files Browse the repository at this point in the history
  • Loading branch information
SerhiiCho committed Jan 16, 2022
1 parent 7199031 commit 235feee
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

use Exception;

class WrongDateFormatException extends Exception
class InvalidDateFormatException extends Exception
{
//
}
18 changes: 11 additions & 7 deletions src/TimeAgo.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
namespace Serhii\Ago;

use Carbon\CarbonImmutable;
use Carbon\Exceptions\InvalidFormatException;
use Serhii\Ago\Exceptions\InvalidDateFormatException;
use Serhii\Ago\Exceptions\MissingRuleException;
use Serhii\Ago\Exceptions\WrongDateFormatException;

final class TimeAgo
{
Expand Down Expand Up @@ -40,19 +41,22 @@ public static function singleton(): self
*
* @return string
* @throws \Serhii\Ago\Exceptions\MissingRuleException
* @throws \Serhii\Ago\Exceptions\WrongDateFormatException
* @throws \Serhii\Ago\Exceptions\InvalidDateFormatException
*/
public static function trans($date, $options = []): string
{
if (\is_int($options)) {
$options = [$options];
}

/** @phpstan-ignore-next-line */
$timestamp = CarbonImmutable::parse($date)->timestamp;

if (!\is_int($timestamp)) {
throw new WrongDateFormatException("Cannot convert date to a timestamp");
try {
/**
* @phpstan-ignore-next-line
* @var int $timestamp
*/
$timestamp = CarbonImmutable::parse($date)->timestamp;
} catch (InvalidFormatException $e) {
throw new InvalidDateFormatException($e->getMessage());
}

return self::singleton()->handle($timestamp, $options);
Expand Down
8 changes: 8 additions & 0 deletions tests/TimeAgoTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Carbon\CarbonInterface;
use DateTimeInterface;
use PHPUnit\Framework\TestCase;
use Serhii\Ago\Exceptions\InvalidDateFormatException;
use Serhii\Ago\Lang;
use Serhii\Ago\TimeAgo;

Expand Down Expand Up @@ -123,4 +124,11 @@ public function provider_for_trans_method_returns_correct_result_after_passing_a
[Carbon::now()->subMonths(8), '8 months ago'],
];
}

/** @test */
public function trans_method_throws_exception_if_input_has_incorrect_string(): void
{
$this->expectException(InvalidDateFormatException::class);
TimeAgo::trans('sfdafsd');
}
}

0 comments on commit 235feee

Please sign in to comment.