IndexController.php 6.7 KB

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