mstroink/cakephp-google-analytics

This package is abandoned and no longer maintained. No replacement package was suggested.

A CakePHP package to retrieve Google Analytics data. Forked from spatie/laravel-analytics

0.0.3 2021-07-28 19:08 UTC

This package is not auto-updated.

Last update: 2023-11-20 19:03:16 UTC


README

Latest Version MIT Licensed Test Status Check & fix styling Total Downloads

Just a simple port of the spatie/laravel-analytics package re-worked for CakePHP ^4.2 (php 8.0). Be aware this plugin use the new Dependency Injection Container. This is an experimental feature that is not API stable yet.

Using this package you can easily retrieve data from Google Analytics.

Here are a few examples of the provided methods:

use MStroink\Analytics\Analytics;
use MStroink\Analytics\Period;

// In src/Controller/DashboardController.php
class DashboardController extends AppController
{
    public function view(Analytics $analytics)
    {
        //fetch the most visited pages for today and the past week
        $analytics->fetchMostVisitedPages(Period::days(7));

        //fetch visitors and page views for the past week
        $analytics->fetchVisitorsAndPageViews(Period::days(7));
    }
}

Most methods will return an \Cake\Collection\Collection object containing the results.

Installation

This package can be installed through Composer.

composer require mstroink/cakephp-google-analytics

Load the plugin

bin/cake plugin load MStroink/Analytics 

Configuration

Create your config file config/analytics.php

return [

    /*
     * The view id of which you want to display data.
     */
    'view_id' => env('ANALYTICS_VIEW_ID'),

    /*
     * Path to the client secret json file. Take a look at the README of this package
     * to learn how to get this file. You can also pass the credentials as an array
     * instead of a file path.
     */
    'service_account_credentials_json' => ROOT . DS . 'config' . DS . 'service-account-credentials.json',

    /*
     * The amount of minutes the Google API responses will be cached.
     * If you set this to zero, the responses won't be cached at all.
     */
    'cache_lifetime_in_minutes' => 60 * 24,

    /*
     * The name of the cache config engine
     */
    'cache' => [
        'analytics' => 'google_analytics',
        'auth' => 'google_auth',
    ],
];

In your config/app.php add a cache config named analytics_results under the Cache key with required config. For e.g.:

'analytics_results' => [
    'className' => FileEngine::class,
    'duration' => '+1 year', //note that lifetime is managed by setting cache_lifetime_in_minutes
],

How to obtain the credentials to communicate with Google Analytics

Getting credentials

The first thing you’ll need to do is to get some credentials to use Google API’s. I’m assuming that you’ve already created a Google account and are signed in. Head over to Google API’s site and click "Select a project" in the header.

1

Next up we must specify which API’s the project may consume. In the list of available API’s click "Google Analytics API". On the next screen click "Enable".

2

Now that you’ve created a project that has access to the Analytics API it’s time to download a file with these credentials. Click "Credentials" in the sidebar. You’ll want to create a "Service account key".

3

On the next screen you can give the service account a name. You can name it anything you’d like. In the service account id you’ll see an email address. We’ll use this email address later on in this guide. Select "JSON" as the key type and click "Create" to download the JSON file.

4

Save the json inside your Laravel project at the location specified in the service_account_credentials_json key of the config file of this package. Because the json file contains potentially sensitive information I don't recommend committing it to your git repository.

Granting permissions to your Analytics property

I'm assuming that you've already created a Analytics account on the Analytics site. Go to "User management" in the Admin-section of the property.

5

On this screen you can grant access to the email address found in the client_email key from the json file you download in the previous step. Read only access is enough.

6

Getting the view id

The last thing you'll have to do is fill in the view_id in the config file. You can get the right value on the Analytics site. Go to "View setting" in the Admin-section of the property.

7

You'll need the View ID displayed there.

8

Usage

When the installation is done you can easily retrieve Analytics data. Nearly all methods will return an Cake\Collection\Collection-instance.

Here are a few examples using periods

//retrieve visitors and pageview data for the current day and the last seven days
$analyticsData = $analytics->fetchVisitorsAndPageViews(Period::days(7));

//retrieve visitors and pageviews since the 6 months ago
$analyticsData = $analytics->fetchVisitorsAndPageViews(Period::months(6));

//retrieve sessions and pageviews with yearMonth dimension since 1 year ago
$analyticsData = $analytics->performQuery(
    Period::years(1),
    'ga:sessions',
    [
        'metrics' => 'ga:sessions, ga:pageviews',
        'dimensions' => 'ga:yearMonth'
    ]
);

$analyticsData is a Collection in which each item is an array that holds keys date, visitors and pageViews

If you want to have more control over the period you want to fetch data for, you can pass a startDate and an endDate to the period object.

$startDate = Chronos::now()->subYear();
$endDate = Chronos::now();

Period::create($startDate, $endDate);

Provided methods

Visitors and pageviews

public function fetchVisitorsAndPageViews(Period $period): Collection

The function returns a Collection in which each item is an array that holds keys date, visitors, pageTitle and pageViews.

Total visitors and pageviews

public function fetchTotalVisitorsAndPageViews(Period $period): Collection

The function returns a Collection in which each item is an array that holds keys date, visitors, and pageViews.

Most visited pages

public function fetchMostVisitedPages(Period $period, int $maxResults = 20): Collection

The function returns a Collection in which each item is an array that holds keys url, pageTitle and pageViews.

Top referrers

public function fetchTopReferrers(Period $period, int $maxResults = 20): Collection

The function returns a Collection in which each item is an array that holds keys url and pageViews.

User Types

public function fetchUserTypes(Period $period): Collection

The function returns a Collection in which each item is an array that holds keys type and sessions.

Top browsers

public function fetchTopBrowsers(Period $period, int $maxResults = 10): Collection

The function returns a Collection in which each item is an array that holds keys browser and sessions.

All other Google Analytics queries

To perform all other queries on the Google Analytics resource use performQuery. Google's Core Reporting API provides more information on which metrics and dimensions might be used.

public function performQuery(Period $period, string $metrics, array $others = [])

You can get access to the underlying Google_Service_Analytics object:

$analytics->getAnalyticsService();

Testing

Run the tests with:

vendor/bin/phpunit

Contributing

Please see CONTRIBUTING for details.

Support Spatie

68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f6c61726176656c2d616e616c79746963732e6a70673f743d31

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Credits

And a special thanks to Caneco for the logo ✨

License

The MIT License (MIT). Please see License File for more information.