From 787d97083eadd76498ef7d49b46203ebabc9e708 Mon Sep 17 00:00:00 2001 From: Vincent Vanwaelscappel Date: Wed, 24 May 2023 19:09:43 +0200 Subject: [PATCH] wip #5877 --- composer.json | 3 ++- composer.lock | 2 +- src/MatomoUtils.php | 40 ++++++++++++++++++++++++++++++++++++++-- 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/composer.json b/composer.json index 4eee7a6..9f94bee 100644 --- a/composer.json +++ b/composer.json @@ -25,6 +25,7 @@ "php": ">=7.2", "guzzlehttp/guzzle": "^7.7", "ext-json": "*", - "illuminate/cache": ">=5" + "illuminate/cache": ">=5", + "nesbot/carbon": "^2.66" } } diff --git a/composer.lock b/composer.lock index 65ca8b2..731d508 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "510c6ead0c5b49decdb21fa4fe18914c", + "content-hash": "b4abfad71e4d4f905f5ce400600696ac", "packages": [ { "name": "doctrine/inflector", diff --git a/src/MatomoUtils.php b/src/MatomoUtils.php index 03a0ec3..792154c 100644 --- a/src/MatomoUtils.php +++ b/src/MatomoUtils.php @@ -2,9 +2,10 @@ namespace Cubist\Matomo; +use Carbon\Carbon; + class MatomoUtils { - public static function parseDate($date) - { + public static function parseDate($date) { // Match possible date strings: // - YYYY // - YYYY-MM @@ -24,4 +25,39 @@ class MatomoUtils { return $date_matches; } + + public static function getBestPeriod($dates) { + // Extract array keys as variables for easier access: + // $start_date, $start_year, $start_month, $start_day, $end_date + extract($dates); + + // At this point, if the end_date still isn't set, it must either be a YYYY or YYYY-MM that was passed in. + // Therefore, we can also assume that $start_year will be set. All that's left to do is set appropriate + // start and end dates so that we can determine the best period based on the overall length of the range. + if (!isset($end_date)) { + if (isset($start_month) && !empty($start_month)) { // Month mode + $start_date = "{$start_year}-{$start_month}-01"; + $end_date = Carbon::parse($start_date)->endOfMonth()->isoFormat('YYYY-MM-DD'); + } else { // Year mode + $start_date = "{$start_year}-01-01"; + $end_date = Carbon::parse($start_date)->endOfYear()->isoFormat('YYYY-MM-DD'); + } + } + + // Count <= 60 days: period = day + // Count 61–180 days: period = week + // Count 180+ days: period = month + // Count 2+ years: period = year + $day_count = Carbon::parse($start_date)->diffInDays($end_date); + + if ($day_count <= 60) { + return 'day'; + } elseif ($day_count <= 180) { + return 'week'; + } elseif ($day_count <= 730) { + return 'month'; + } + + return 'year'; + } } -- 2.39.5