1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80:
<?php
namespace Deliverist\Builder\Commands;
use Deliverist\Builder\Builder;
use Deliverist\Builder\InvalidArgumentException;
use Deliverist\Builder\ICommand;
class GoogleAnalytics implements ICommand
{
public function run(Builder $builder, $file = NULL, $code = NULL, $placeholder = NULL)
{
$builder->log("Inserting Google Analytics code '$code' into '$file'.");
if (!is_string($file)) {
throw new InvalidArgumentException('File must be string, ' . gettype($file) . ' given.');
}
if (!is_string($code)) {
throw new InvalidArgumentException('Code must be string, ' . gettype($code) . ' given.');
}
$parameters = $this->prepareParameters($file, $placeholder);
$script = array(
'<script' . (isset($parameters['attributes']) ? (' ' . $parameters['attributes']) : '') . '>',
'ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;',
"ga('create'," . json_encode((string) $code) . ",'auto');ga('send','pageview');",
'</script>',
'<script src="https://www.google-analytics.com/analytics.js" async defer></script>',
);
$content = $builder->readFile($file);
$content = strtr($content, array(
$parameters['placeholder'] => implode('', $script),
));
$builder->writeFile($file, $content);
}
private function prepareParameters($file, $placeholder)
{
$parameters = array(
'attributes' => NULL,
'placeholder' => NULL,
);
$extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if ($extension === 'latte') {
$parameters['placeholder'] = '{* GA *}';
$parameters['attributes'] = 'n:syntax="off"';
} elseif ($extension === 'html') {
$parameters['placeholder'] = '<!-- GA -->';
}
if ($parameters['placeholder'] === NULL) {
$parameters['placeholder'] = $placeholder;
}
if ($parameters['placeholder'] === NULL) {
throw new InvalidArgumentException("Missing placeholder, unknow file extension '$extension'.");
}
return $parameters;
}
}