Skip to content

Instantly share code, notes, and snippets.

@josipjelic
Last active October 18, 2017 05:26
Show Gist options
  • Save josipjelic/f69548795b10f1e62dddcc1c6584ee56 to your computer and use it in GitHub Desktop.
Save josipjelic/f69548795b10f1e62dddcc1c6584ee56 to your computer and use it in GitHub Desktop.
Laravel - Create report data placeholder array for certain period and merge it with collection from database
<?php
use Carbon\Carbon;
use DateInterval;
use DatePeriod;
use Illuminate\Support\Collection;
class Report
{
/**
*
* Returns period as array ie.
*
* ['hour' => [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]]
*
* @param $from Carbon|\DateTime Start of interval
* @param $to Carbon|\DateTime End of interval
* @param $interval string DateTime interval ie 'P1D' or 'PT1H'
* @param $format string Date format as in date()
* @param $key string Key to use
* @param bool $reversed
*
* @throws \Exception
* @return array
*/
public function getPeriod($from, $to, $interval, $format, $key, $reversed = false): array
{
$return = [];
$dateRange = new DatePeriod($from, new DateInterval($interval), $to);
foreach ($dateRange as $date) {
$return[] = $date->format($format);
}
return [$key => $reversed ? array_reverse($return) : $return];
}
/**
*
* Merges data from getPeriod with Collection from database. Matching: key defined in getPeriod = key from database
*
* @param $period array Period from getPeriod
* @param $data Collection Data from database
*
* @return array
*
*/
public function mergeData(array $period, Collection $data): array
{
$key = key($period);
foreach ($period[$key] as $periodValue) {
$result = $data->where($key, $periodValue)->first();
if ($result) {
$return[] = $result->toArray();
continue;
}
$return[][$key] = $periodValue;
}
return $return ?? [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment