Skip to content

Commit 6ee42ad

Browse files
author
Zsolt Gál
committed
Add ability to construct TimeAgo with a translation code
1 parent 1076d49 commit 6ee42ad

File tree

2 files changed

+33
-4
lines changed

2 files changed

+33
-4
lines changed

spec/Technodelight/TimeAgoSpec.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,10 @@ function it_calculates_a_difference_between_two_dates(Translator $translator)
2525

2626
$this->inWords();
2727
}
28+
29+
function it_could_be_constructed_with_language_code()
30+
{
31+
$this->beConstructedWithTranslation(new DateTime('-1 minute'), 'nl');
32+
$this->inWords()->shouldReturn('1 minuut geleden');
33+
}
2834
}

src/Technodelight/TimeAgo.php

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22

33
namespace Technodelight;
44

5+
use Technodelight\TimeAgo\TranslationLoader;
56
use Technodelight\TimeAgo\Translator;
6-
use \DateTime;
77

88
class TimeAgo
99
{
@@ -16,15 +16,38 @@ class TimeAgo
1616
*/
1717
private $translator;
1818

19-
public function __construct(DateTime $dateTime, Translator $translator = null)
19+
/**
20+
* @param DateTime $dateTime
21+
* @param Translator|null $translator
22+
*/
23+
public function __construct(\DateTime $dateTime, Translator $translator = null)
2024
{
2125
$this->dateTime = $dateTime;
2226
$this->translator = $translator ?: new Translator;
2327
}
2428

25-
public function inWords(DateTime $now = null)
29+
/**
30+
* Instantiate TimeAgo with the desired built-in translation
31+
*
32+
* @param DateTime $dateTime
33+
* @param string $languageCode
34+
*
35+
* @return TimeAgo
36+
*/
37+
public static function withTranslation(\DateTime $dateTime, $languageCode)
38+
{
39+
$translationLoader = new TranslationLoader;
40+
return new self($dateTime, new Translator($translationLoader->load($languageCode)));
41+
}
42+
43+
/**
44+
* @param DateTime|null $now accepts a reference date
45+
*
46+
* @return string
47+
*/
48+
public function inWords(\DateTime $now = null)
2649
{
27-
$now = $now ?: new DateTime;
50+
$now = $now ?: new \DateTime;
2851
return $this->translator->translate(
2952
$now->getTimestamp() - $this->dateTime->getTimestamp()
3053
);

0 commit comments

Comments
 (0)