IndexController.php 7.2 KB

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