Schedule Formatter
<?php | |
use Carbon\Carbon; | |
use October\Rain\Database\Collection; | |
/** | |
* Class ScheduleFormatter | |
*/ | |
class ScheduleFormatter | |
{ | |
/** | |
* @var array | |
*/ | |
protected $cache = []; | |
/** | |
* @var string | |
*/ | |
protected $keyStartTime; | |
/** | |
* @var string | |
*/ | |
protected $keyEndTime; | |
/** | |
* @var | |
*/ | |
protected $keyDayOfWeek; | |
/** | |
* ScheduleFormatter constructor. | |
* | |
* @param Collection $collection | |
* @param string $keyStartTime - Ключ времени начала раб. дня. | |
* @param string $keyEndTime - Ключ времени окончания раб. дня. | |
* @param string $keyDayOfWeek - Ключ значения календарного дня недели | |
*/ | |
public function __construct(Collection $collection, string $keyStartTime = 'start_time', string $keyEndTime = 'end_time', string $keyDayOfWeek = 'day_of_week') | |
{ | |
$this->keyStartTime = $keyStartTime; | |
$this->keyEndTime = $keyEndTime; | |
$this->keyDayOfWeek = $keyDayOfWeek; | |
$this->parse($collection); | |
} | |
/** | |
* @param Collection $collection | |
*/ | |
protected function parse(Collection $collection): void | |
{ | |
$collection->groupBy($this->keyStartTime)->each(function($items, $key) use(&$cache) { | |
$times = []; | |
$items->each(function($item) use(&$times, $key) { | |
$times[$key .' - '. $item->{$this->keyEndTime}][] = $item->{$this->keyDayOfWeek}; | |
}); | |
$this->cache = $this->cache + $times; | |
}); | |
} | |
/** | |
* @return array | |
*/ | |
public function all(): array | |
{ | |
return \array_map(static function($items) { | |
return \array_map(static function($dayOfWeek) { | |
return Carbon::getDays()[$dayOfWeek]; | |
}, $items); | |
}, $this->cache); | |
} | |
/** | |
* @return string | |
*/ | |
public function render(): string | |
{ | |
$schedule = \array_map(static function($days) { | |
return implode(', ', $days); | |
}, $this->all()); | |
if (\count($schedule) === 1) { | |
return "Ежедневно ". array_keys($schedule)[0]; | |
} | |
$return = []; | |
foreach($schedule as $time => $days) { | |
$return[] = $days .' '. $time; | |
} | |
return implode("\n", $return); | |
} | |
/** | |
* @return string | |
*/ | |
public function __toString(): string | |
{ | |
return $this->render(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment