IndexController.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. <?php
  2. namespace app\controllers;
  3. use Yii;
  4. use yii\filters\AccessControl;
  5. use yii\web\Controller;
  6. use yii\web\Response;
  7. use yii\filters\VerbFilter;
  8. use app\models\LoginForm;
  9. use app\models\ContactForm;
  10. class IndexController extends Controller
  11. {
  12. /**
  13. * {@inheritdoc}
  14. */
  15. public function behaviors()
  16. {
  17. return [
  18. 'access' => [
  19. 'class' => AccessControl::className(),
  20. 'only' => ['logout'],
  21. 'rules' => [
  22. [
  23. 'actions' => ['logout'],
  24. 'allow' => true,
  25. 'roles' => ['@'],
  26. ],
  27. ],
  28. ],
  29. 'verbs' => [
  30. 'class' => VerbFilter::className(),
  31. 'actions' => [
  32. 'logout' => ['post'],
  33. ],
  34. ],
  35. ];
  36. }
  37. /**
  38. * {@inheritdoc}
  39. */
  40. public function actions()
  41. {
  42. return [
  43. 'error' => [
  44. 'class' => 'yii\web\ErrorAction',
  45. ],
  46. 'captcha' => [
  47. 'class' => 'yii\captcha\CaptchaAction',
  48. 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
  49. ],
  50. ];
  51. }
  52. /**
  53. * Displays homepage.
  54. *
  55. * @return string
  56. */
  57. public function actionIndex()
  58. {
  59. $analytics=$this->initializeAnalytics();
  60. $metrics=[
  61. 'sessions'=>"ga:sessions",
  62. 'bounceRate'=>"ga:bounceRate",
  63. 'sessionDuration'=>"ga:sessionDuration",
  64. 'hits'=>"ga:hits",
  65. 'transactions'=>"ga:transactions",
  66. 'transactionsPerSession'=>"ga:transactionsPerSession",
  67. 'transactionRevenue'=>"ga:transactionRevenue",
  68. 'totalValue'=>"ga:totalValue",
  69. 'itemQuantity'=>"ga:itemQuantity",
  70. 'productAddsToCart'=>"ga:productAddsToCart",
  71. 'productCheckouts'=>"ga:productCheckouts",
  72. 'productDetailViews'=>"ga:productDetailViews",
  73. ];
  74. $i=1;
  75. $res=[];
  76. $metrics=array_chunk($metrics,6,true);
  77. foreach($metrics as $metric){
  78. $response = $this->getReport($analytics,$metric);
  79. // $this->printResults($response);
  80. $data=$this->getResults($response);
  81. if(!empty($data)){
  82. $res=empty($res)?$data:array_merge_recursive($res,$data);
  83. }
  84. }
  85. echo "<pre>";
  86. print_r($res);
  87. exit;
  88. return $this->render('index');
  89. }
  90. function initializeAnalytics()
  91. {
  92. // Use the developers console and download your service account
  93. // credentials in JSON format. Place them in this directory or
  94. // change the key file location if necessary.
  95. $KEY_FILE_LOCATION = BASE_DIR . 'config/savvy-theory-278005-43552bf9fe94.json';
  96. // Create and configure a new client object.
  97. $client = new \Google_Client();
  98. $client->setApplicationName("Hello Analytics Reporting");
  99. $client->setAuthConfig($KEY_FILE_LOCATION);
  100. $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
  101. $analytics = new \Google_Service_AnalyticsReporting($client);
  102. return $analytics;
  103. }
  104. /**
  105. * Queries the Analytics Reporting API V4.
  106. *
  107. * @param service An authorized Analytics Reporting API V4 service object.
  108. * @return The Analytics Reporting API V4 response.
  109. */
  110. function getReport($analytics,$data) {
  111. $VIEW_ID = "155703065";
  112. // Create the DateRange object.
  113. $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
  114. $dateRange->setStartDate("7daysAgo");
  115. $dateRange->setEndDate("today");
  116. $metrics=[];
  117. $dimensions=[];
  118. foreach($data as $k=>$v){
  119. $Metric = new \Google_Service_AnalyticsReporting_Metric();
  120. $Metric->setExpression($v);
  121. $Metric->setAlias($k);
  122. array_push($metrics,$Metric);
  123. }
  124. $date = new \Google_Service_AnalyticsReporting_Dimension();
  125. $date->setName("ga:date");
  126. array_push($dimensions,$date);
  127. // Create the ReportRequest object.
  128. $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  129. $request->setViewId($VIEW_ID);
  130. $request->setDateRanges($dateRange);
  131. $request->setMetrics($metrics);
  132. $request->setDimensions($dimensions);
  133. $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
  134. $body->setReportRequests( array( $request) );
  135. return $analytics->reports->batchGet( $body );
  136. }
  137. /**
  138. * Parses and prints the Analytics Reporting API V4 response.
  139. *
  140. * @param An Analytics Reporting API V4 response.
  141. */
  142. function printResults($reports) {
  143. for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
  144. $report = $reports[ $reportIndex ];
  145. $header = $report->getColumnHeader();
  146. $dimensionHeaders = $header->getDimensions();
  147. $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
  148. $rows = $report->getData()->getRows();
  149. for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
  150. $row = $rows[ $rowIndex ];
  151. $dimensions = $row->getDimensions();
  152. $metrics = $row->getMetrics();
  153. if($dimensionHeaders&&$dimensions){
  154. for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
  155. print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n\r");
  156. echo"<br/>";
  157. }
  158. }
  159. if($metricHeaders&&$metrics){
  160. for ($j = 0; $j < count($metrics); $j++) {
  161. $values = $metrics[$j]->getValues();
  162. for ($k = 0; $k < count($values); $k++) {
  163. $entry = $metricHeaders[$k];
  164. print($entry->getName() . ": " . $values[$k] . "\n\r");
  165. echo"<br/>";
  166. }
  167. }
  168. }
  169. }
  170. }
  171. }
  172. function getResults($reports) {
  173. $data=[];
  174. for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
  175. $item=[];
  176. $report = $reports[ $reportIndex ];
  177. $header = $report->getColumnHeader();
  178. $dimensionHeaders = $header->getDimensions();
  179. $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
  180. $rows = $report->getData()->getRows();
  181. for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
  182. $row = $rows[ $rowIndex ];
  183. $dimensions = $row->getDimensions();
  184. $metrics = $row->getMetrics();
  185. // echo "<pre>";
  186. if($dimensionHeaders&&$dimensions){
  187. // for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
  188. // $list[$dimensionHeaders[$i]]=
  189. // print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n\r");
  190. // echo"<br/>";
  191. // }
  192. $date=$dimensions[0];
  193. }else{
  194. continue;
  195. }
  196. if($metricHeaders&&$metrics){
  197. for ($j = 0; $j < count($metrics); $j++) {
  198. $values = $metrics[$j]->getValues();
  199. for ($k = 0; $k < count($values); $k++) {
  200. $entry = $metricHeaders[$k];
  201. $data[$date][$entry->getName()]=$values[$k];
  202. // print($entry->getName() . ": " . $values[$k] . "\n\r");
  203. // echo"<br/>";
  204. }
  205. }
  206. }
  207. }
  208. }
  209. return $data;
  210. }
  211. }