IndexController.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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. 'productCheckouts'=>"ga:productCheckouts",
  70. 'itemQuantity'=>"ga:itemQuantity",
  71. 'productAddsToCart'=>"ga:productAddsToCart",
  72. ];
  73. $i=1;
  74. $datas=array_chunk($metrics,2,true);
  75. foreach($datas as $data){
  76. $response = $this->getReport($analytics,$data);
  77. // $this->printResults($response);
  78. $res=$this->getResults($response);
  79. echo "<pre>";
  80. print_r($res);
  81. }
  82. exit;
  83. return $this->render('index');
  84. }
  85. function initializeAnalytics()
  86. {
  87. // Use the developers console and download your service account
  88. // credentials in JSON format. Place them in this directory or
  89. // change the key file location if necessary.
  90. $KEY_FILE_LOCATION = BASE_DIR . 'config/savvy-theory-278005-43552bf9fe94.json';
  91. // Create and configure a new client object.
  92. $client = new \Google_Client();
  93. $client->setApplicationName("Hello Analytics Reporting");
  94. $client->setAuthConfig($KEY_FILE_LOCATION);
  95. $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
  96. $analytics = new \Google_Service_AnalyticsReporting($client);
  97. return $analytics;
  98. }
  99. /**
  100. * Queries the Analytics Reporting API V4.
  101. *
  102. * @param service An authorized Analytics Reporting API V4 service object.
  103. * @return The Analytics Reporting API V4 response.
  104. */
  105. function getReport($analytics,$data) {
  106. $VIEW_ID = "155703065";
  107. // Create the DateRange object.
  108. $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
  109. $dateRange->setStartDate("7daysAgo");
  110. $dateRange->setEndDate("today");
  111. $metrics=[];
  112. $dimensions=[];
  113. foreach($data as $k=>$v){
  114. $Metric = new \Google_Service_AnalyticsReporting_Metric();
  115. $Metric->setExpression($v);
  116. $Metric->setAlias($k);
  117. array_push($metrics,$Metric);
  118. }
  119. $date = new \Google_Service_AnalyticsReporting_Dimension();
  120. $date->setName("ga:date");
  121. array_push($dimensions,$date);
  122. // Create the ReportRequest object.
  123. $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  124. $request->setViewId($VIEW_ID);
  125. $request->setDateRanges($dateRange);
  126. $request->setMetrics($metrics);
  127. $request->setDimensions($dimensions);
  128. $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
  129. $body->setReportRequests( array( $request) );
  130. return $analytics->reports->batchGet( $body );
  131. }
  132. /**
  133. * Parses and prints the Analytics Reporting API V4 response.
  134. *
  135. * @param An Analytics Reporting API V4 response.
  136. */
  137. function printResults($reports) {
  138. for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
  139. $report = $reports[ $reportIndex ];
  140. $header = $report->getColumnHeader();
  141. $dimensionHeaders = $header->getDimensions();
  142. $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
  143. $rows = $report->getData()->getRows();
  144. for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
  145. $row = $rows[ $rowIndex ];
  146. $dimensions = $row->getDimensions();
  147. $metrics = $row->getMetrics();
  148. if($dimensionHeaders&&$dimensions){
  149. for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
  150. print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n\r");
  151. echo"<br/>";
  152. }
  153. }
  154. if($metricHeaders&&$metrics){
  155. for ($j = 0; $j < count($metrics); $j++) {
  156. $values = $metrics[$j]->getValues();
  157. for ($k = 0; $k < count($values); $k++) {
  158. $entry = $metricHeaders[$k];
  159. print($entry->getName() . ": " . $values[$k] . "\n\r");
  160. echo"<br/>";
  161. }
  162. }
  163. }
  164. }
  165. }
  166. }
  167. function getResults($reports) {
  168. $data=[];
  169. for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
  170. $item=[];
  171. $report = $reports[ $reportIndex ];
  172. $header = $report->getColumnHeader();
  173. $dimensionHeaders = $header->getDimensions();
  174. $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
  175. $rows = $report->getData()->getRows();
  176. for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
  177. $row = $rows[ $rowIndex ];
  178. $dimensions = $row->getDimensions();
  179. $metrics = $row->getMetrics();
  180. // echo "<pre>";
  181. if($dimensionHeaders&&$dimensions){
  182. // for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
  183. // $list[$dimensionHeaders[$i]]=
  184. // print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n\r");
  185. // echo"<br/>";
  186. // }
  187. $date=$dimensions[0];
  188. }else{
  189. continue;
  190. }
  191. if($metricHeaders&&$metrics){
  192. for ($j = 0; $j < count($metrics); $j++) {
  193. $values = $metrics[$j]->getValues();
  194. for ($k = 0; $k < count($values); $k++) {
  195. $entry = $metricHeaders[$k];
  196. $data[$date][$entry->getName()]=$values[$k];
  197. // print($entry->getName() . ": " . $values[$k] . "\n\r");
  198. // echo"<br/>";
  199. }
  200. }
  201. }
  202. }
  203. }
  204. return $data;
  205. }
  206. }