Skip to content

Commit

Permalink
Greeterの実装をロケールに対応させた [FAIL]
Browse files Browse the repository at this point in the history
  • Loading branch information
hidenorigoto committed Jul 25, 2018
1 parent 4231676 commit 410038d
Showing 1 changed file with 43 additions and 16 deletions.
59 changes: 43 additions & 16 deletions src/Greeter.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,35 +8,62 @@ class Greeter
*/
private $clock;
/**
* @var array
* @var array|TimeRange[]
*/
private $timeRangeAndGreetings = [];
private $timeRanges = [];
/**
* @var array|string[]
*/
private $greetings = [];
/**
* @var Globe
*/
private $globe;

public function __construct(Clock $clock)
public function __construct(Clock $clock, Globe $globe)
{
$this->clock = $clock;
$this->globe = $globe;
}

public function addTimeRange(TimeRange $timeRange)
{
$this->timeRanges[] = $timeRange;
}

public function addTimeRangeAndGreeting(TimeRange $timeRange, $greeting)
public function addGreeting(string $locale, string $timeRangeId, string $greeting)
{
$this->timeRangeAndGreetings[] = [
'range' => $timeRange,
'greeting' => $greeting,
];
$this->greetings[$locale][$timeRangeId] = $greeting;
}

/**
* @return string
*/
public function greet() :string
{
$currentTime = $this->clock->getCurrentTime();
foreach ($this->timeRangeAndGreetings as $timeRangeAndGreeting)
{
if ($timeRangeAndGreeting['range']->contains($currentTime))
{
return $timeRangeAndGreeting['greeting'];
}
}
$currentTime = $this->clock->getCurrentTime();
$timeRangeId = $this->decideTimeRange($currentTime);
$currentLocale = $this->globe->getLocale();

if (isset($this->greetings[$currentLocale][$timeRangeId])) {
return $this->greetings[$currentLocale][$timeRangeId];
}

return '';
}

/**
* @param \DateTimeInterface $currentTime
* @return string
*/
private function decideTimeRange(\DateTimeInterface $currentTime) :string
{
foreach ($this->timeRanges as $timeRange) {
if ($timeRange->contains($currentTime)) {
return $timeRange->getId();
}
}

throw new \LogicException('Uncovered time range:' . $currentTime->format('H:i'));
}
}

0 comments on commit 410038d

Please sign in to comment.