IndexController.php 7.6 KB

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