Skip to content

Instantly share code, notes, and snippets.

@BrockReece
Created November 1, 2015 12:36
Show Gist options
  • Save BrockReece/e0da3cfb75344ff8a6b2 to your computer and use it in GitHub Desktop.
Save BrockReece/e0da3cfb75344ff8a6b2 to your computer and use it in GitHub Desktop.
Generic CakePHP component to get basic Google analytics data for a page
<?php
App::uses('Component', 'Controller');
class AnalyticsComponent extends Component {
/**
* Default actions for component
*
* @var array
*/
public $actions = array('edit');
/**
* Startup method, gets config and initiates auth.
* return before auth if controller action is not in the list of actions for this component.
*
* @param Controller $controller A reference to the instantiating controller object
*
* @return void
*/
public function startup(Controller $controller) {
if (!in_array($controller->action, $this->actions)) {
return;
}
$this->config = Configure::read('Google.Analytics');
$this->auth();
}
/**
* Authenticate using config file ready to make API calls
*
* @return void
*/
public function auth() {
$this->client = new Google_Client();
$this->client->setApplicationName($this->config['app_name']);
$this->client->setAssertionCredentials(new Google_Auth_AssertionCredentials(
$this->config['app_email'],
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents(App::pluginPath('Google') . 'Config/' . $this->config['auth_file'])
));
$this->client->setClientId($this->config['client_id']);
$this->client->setAccessType('offline_access');
$this->analytics = new Google_Service_Analytics($this->client);
$profile = $this->analytics->management_profiles->get($this->config['account_id'], $this->config['web_property_id'], $this->config['profile_id']);
$this->profile = $profile->getId();
}
/**
* Abstraction method to find analytics for a specific page
*
* @param string $page google analytcs page path
* @param array $options list of additional options
*
* @return void
*/
public function findForPage($page = '', $options = array()) {
$page = !empty($page) ? $page : $_SERVER['REQUEST_URI'];
$options = Hash::merge(array(
'conditions' => array(
'pagePath' => $page,
),
), $options);
return $this->customFind($options)['totalsForAllResults'];
}
/**
* Build an array of api options and return results from the _getResults method
* This method mocks some of cake's find syntax
*
* @param array $options list of options to help build api query
*
* @return array
*/
public function customFind($options = array()) {
$options = Hash::merge(array(
'start' => '7daysAgo',
'end' => 'today',
'fields' => $this->config['default_fields'],
'conditions' => array(),
'group' => '',
), $options);
$metrics = array();
foreach ($options['fields'] as $field) {
$metrics[] = sprintf('ga:%s', $field);
}
$options['metrics'] = implode(',', $metrics);
$dimensions = array();
$filters = array();
foreach ($options['conditions'] as $field => $condition) {
$dimensions[] = sprintf('ga:%s', $field);
$filters[] = sprintf('ga:%s==%s', $field, $condition);
}
$options['params']['dimensions'] = implode(',', $dimensions);
$options['params']['filters'] = implode(';', $filters);
if (!empty($options['group'])) {
$options['params']['dimensions'] .= sprintf(',ga:%s', $options['group']);
$options['params']['sort'] = sprintf('-ga:%s', $options['group']);
}
return $this->_getResults($options);
}
/**
* Make Api calls and return results
*
* @param array $options api call options
*
* @return array
*/
protected function _getResults($options = array()) {
$options = Hash::merge(array(
'start' => '7daysAgo',
'end' => 'today',
'metrics' => '',
'params' => array(),
), $options);
$results = $this->analytics->data_ga->get(
'ga:' . $this->profile,
$options['start'],
$options['end'],
$options['metrics'],
$options['params']
);
return $results;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment