bezhanSalleh / filament-google-analytics

Google Analytics integration with Filamentphp (FilamentAdmin)
MIT License
169 stars 30 forks source link

Undefined array key 1 - Traits/Visitors.php #38

Closed beataburczyk closed 1 year ago

beataburczyk commented 1 year ago

Hello, while implementing this future to my website I have spotted an error: Undefined array key 1 I did some debugging and found In Traits/Visitors.php

private function visitorsToday(): array
    {
        $analyticsData = Analytics::fetchTotalVisitorsAndPageViews(Period::days(1));

        return [
            'result' => $analyticsData[0]['activeUsers'],
            'previous' => $analyticsData[1]['activeUsers'],
        ];
    }

For small websites with minimal traffic, key $analyticsData[1] will not exists and this is rising a error. Just wondering if creators have better idea than simple

'previous' => isset($analyticsData[1]) ? $analyticsData[1]['activeUsers'] : $analyticsData[0]['activeUsers'],

beataburczyk commented 1 year ago

Thank you for immediate action, already tested this fix, and its working well!

RChutchev commented 5 months ago

@bezhanSalleh, hello.

I've same problem with your package on ver. 2.0.0, with Filament v.2, with about to empty GA data, on test environment. We're unable to use package without pass all tests on Test environment (b/c some time it's possible to have 0 as "today unique users" for example at 0:01AM for current day.

We're unable to update to Filament v.3 for some reasons. Can u please add same fix for your package (2.0.0 ver) b/c 2.0.0 ver last supported version for Filament v.2, or add support for Filament v.2 to 2.0.1 package version if 2.0.1 works with Filament v.2.

vendor/bezhansalleh/filament-google-analytics/src/Traits/Visitors.php

Undefined array key 1 {"userId":1,"exception":"[object] (ErrorException(code: 0): Undefined array key 1 at .../vendor/laravel/framework/src/Illuminate/Collections/Collection.php:1781)

It's require to modify this function

private function visitorsToday(): array
    {
        $analyticsData = Analytics::fetchTotalVisitorsAndPageViews(Period::days(1));

        return [
            'result' => $analyticsData[0]['activeUsers'],
            'previous' => $analyticsData[1]['activeUsers'],
        ];
    }

and here too, to be sure that we are never get 500 if data empty...

    private function visitorsYesterday(): array
    {
        $analyticsData = Analytics::fetchTotalVisitorsAndPageViews(Period::create(Carbon::yesterday()->clone()->subDay(), Carbon::yesterday()));

        return [
            'result' => $analyticsData[0]['activeUsers'],
            'previous' => $analyticsData[1]['activeUsers'],
        ];
    }