IndexController.php 6.8 KB

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