77use Google \Analytics \Data \V1beta \FilterExpression ;
88use Google \Analytics \Data \V1beta \Metric ;
99use Google \Analytics \Data \V1beta \RunReportResponse ;
10+ use Google \Analytics \Data \V1beta \RunRealtimeReportResponse ;
1011use Illuminate \Contracts \Cache \Repository ;
1112use Illuminate \Support \Collection ;
1213
@@ -76,6 +77,56 @@ public function get(
7677 return $ result ;
7778 }
7879
80+ public function getRealtime (
81+ string $ propertyId ,
82+ Period $ period ,
83+ array $ metrics ,
84+ array $ dimensions = [],
85+ int $ maxResults = 10 ,
86+ array $ orderBy = [],
87+ int $ offset = 0 ,
88+ ?FilterExpression $ dimensionFilter = null ,
89+ bool $ keepEmptyRows = false ,
90+ ?FilterExpression $ metricFilter = null ,
91+ ): Collection {
92+ $ typeCaster = resolve (TypeCaster::class);
93+
94+ $ response = $ this ->runRealtimeReport ([
95+ 'property ' => "properties/ {$ propertyId }" ,
96+ 'dateRanges ' => [
97+ $ period ->toDateRange (),
98+ ],
99+ 'metrics ' => $ this ->getFormattedMetrics ($ metrics ),
100+ 'dimensions ' => $ this ->getFormattedDimensions ($ dimensions ),
101+ 'limit ' => $ maxResults ,
102+ 'offset ' => $ offset ,
103+ 'orderBys ' => $ orderBy ,
104+ 'dimensionFilter ' => $ dimensionFilter ,
105+ 'keepEmptyRows ' => $ keepEmptyRows ,
106+ 'metricFilter ' => $ metricFilter ,
107+ ]);
108+
109+ $ result = collect ();
110+
111+ foreach ($ response ->getRows () as $ row ) {
112+ $ rowResult = [];
113+
114+ foreach ($ row ->getDimensionValues () as $ i => $ dimensionValue ) {
115+ $ rowResult [$ dimensions [$ i ]] =
116+ $ typeCaster ->castValue ($ dimensions [$ i ], $ dimensionValue ->getValue ());
117+ }
118+
119+ foreach ($ row ->getMetricValues () as $ i => $ metricValue ) {
120+ $ rowResult [$ metrics [$ i ]] =
121+ $ typeCaster ->castValue ($ metrics [$ i ], $ metricValue ->getValue ());
122+ }
123+
124+ $ result ->push ($ rowResult );
125+ }
126+
127+ return $ result ;
128+ }
129+
79130 public function runReport (array $ request ): RunReportResponse
80131 {
81132 $ cacheName = $ this ->determineCacheName (func_get_args ());
@@ -91,6 +142,22 @@ public function runReport(array $request): RunReportResponse
91142 );
92143 }
93144
145+ public function runRealtimeReport (array $ request ): RunRealtimeReportResponse
146+ {
147+ $ cacheName = $ this ->determineCacheName (func_get_args ());
148+
149+ if ($ this ->cacheLifeTimeInMinutes === 0 ) {
150+ $ this ->cache ->forget ($ cacheName );
151+ }
152+
153+ return $ this ->cache ->remember (
154+ $ cacheName ,
155+ $ this ->cacheLifeTimeInMinutes ,
156+ fn () => $ this ->service ->runRealtimeReport ($ request ),
157+ );
158+ }
159+
160+
94161 public function getAnalyticsService (): BetaAnalyticsDataClient
95162 {
96163 return $ this ->service ;
0 commit comments