Skip to content

Instantly share code, notes, and snippets.

@deivamagalhaes
Created April 17, 2019 02:21
Show Gist options
  • Save deivamagalhaes/f7d49bd130a7cd9e239eee3bf7cf6aa5 to your computer and use it in GitHub Desktop.
Save deivamagalhaes/f7d49bd130a7cd9e239eee3bf7cf6aa5 to your computer and use it in GitHub Desktop.
<?php
namespace App\Services;
use Analytics;
use Config;
use Illuminate\Support\Facades\App;
use Spatie\Analytics\Period;
/**
* Class GoogleAnalyticsService
*
* @package App\Services
*/
class GoogleAnalyticsService
{
/**
* @param App\Models\Site $site
* @param Carbon $start_date
* @param Carbon $end_date
* @param array $page_paths Optional, if you want to get visitors and page views for specific paths
*
* @return mixed
*/
public function getVisitorsAndPageViews($site, $start_date, $end_date, $page_paths = [])
{
// We only get stats for sites with domains.
if (empty($site->domains)) {
return;
}
// Extract site's domains.
$domains = $site->domains->pluck('url')->toArray();
// Build the hostname filter string.
$domains_filter = array_map(function ($domain) {
// Filter string for each domain.
return "ga:hostname==$domain";
}, $domains);
$filters = implode(',', $domains_filter);
// Build the page path filter string.
$page_paths_filter = array_map(function ($page_path) {
// Filter string for each path.
return "ga:pagePath=@$page_path";
}, $page_paths);
if (!empty ($page_paths_filter)) {
$filters .= ';' . implode(',', $page_paths_filter);
}
// Retrieve stats from Google Analytics.
$analytics_response = Analytics::performQuery(
Period::create($start_date, $end_date),
'ga:pageviews, ga:users',
[
// Filter by hostname and, optionally, page path.
'filters' => $filters,
// Group by date.
'dimensions' => 'ga:date',
]
);
$results = array_get($analytics_response, 'rows');
return $results;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment