-
composer.json
Open in GitHub{ "name" : "brendt/aggregate.stitcher.io", "require" : { "php": "^7.4", "abraham/twitteroauth": "^1.0", // ... "spatie/period": "^1.1", // ... }, }
-
app/Domain/Analytics/Analytics.php
Open in GitHub// These methods create Periods of the last 30 days // Spatie Period package helps to manipulate them easier use Spatie\Period\Period; final class Analytics { // ... other methods public function viewsPerDay(): Collection { $period = Period::make(now()->subDays(30), now()); /** @var \Domain\Post\Collections\ViewCollection $views */ $views = View::query() ->where('created_at', '>=', $period->getStart()) ->get(); return $views->spreadForPeriod($period); } public function votesPerDay(): Collection { $period = Period::make(now()->subDays(30), now()); /** @var \Domain\Post\Collections\VoteCollection $votes */ $votes = Vote::query() ->where('created_at', '>=', $period->getStart()) ->get(); return $votes->spreadForPeriod($period); } }
-
app/Domain/Post/Collections/SpreadForPeriod.php
Open in GitHub// This method prepares a collection of all period elements, one for each day // It's used for Analytics reports - all 30 days have 0 records by default, in the beginning use Carbon\Carbon; use Spatie\Period\Period; trait SpreadForPeriod { public function spreadForPeriod(Period $period) { $day = Carbon::make($period->getStart()); $data = collect([]); while ($day <= $period->getEnd()) { $data[$day->toDateString()] = 0; $day->addDay(); } foreach ($this as $model) { $data[$model->created_at->toDateString()] += 1; } return $data; } }