44
55use Psr \Http \Message \ResponseInterface as Response ;
66use Psr \Http \Message \ServerRequestInterface as Request ;
7+ use Shika \Helpers \DeviceInfo ;
8+ use Shika \Helpers \GeoLocation ;
79use Shika \Helpers \JsonResponse ;
810use Shika \Repositories \SiteRepository ;
911use Shika \Repositories \VisitRepository ;
@@ -14,11 +16,13 @@ class AnalyticsController
1416
1517 private VisitRepository $ visits ;
1618 private SiteRepository $ sites ;
19+ private GeoLocation $ location ;
1720
18- public function __construct (VisitRepository $ visits , SiteRepository $ sites )
21+ public function __construct (VisitRepository $ visits , SiteRepository $ sites, GeoLocation $ location )
1922 {
2023 $ this ->visits = $ visits ;
2124 $ this ->sites = $ sites ;
25+ $ this ->location = $ location ;
2226 }
2327
2428 public function send (Request $ request , Response $ response )
@@ -62,13 +66,25 @@ public function send(Request $request, Response $response)
6266 return $ response ->withStatus (204 );
6367 }
6468
69+ // get the agent info
70+ $ device = new DeviceInfo ($ request );
71+
72+ if (!$ device ->isBrowser ())
73+ {
74+ return $ response ->withStatus (204 );
75+ }
76+
6577 // build the visit
6678 $ visit = [
6779 "site_id " => $ site ->id ,
6880 "visit_at " => gmdate ("Y-m-d H:i:s " ),
6981
7082 "visit_host " => $ location ["host " ],
7183 "visit_path " => $ location ["path " ],
84+
85+ "browser " => $ device ->getBrowser (),
86+ "operating_system " => $ device ->getOperatingSystem (),
87+ "device_type " => $ device ->getDeviceType (),
7288 ];
7389
7490 // add the referrer if we have one
@@ -82,6 +98,18 @@ public function send(Request $request, Response $response)
8298 }
8399 }
84100
101+ // add location info
102+ if ($ this ->location ->isAvailable ())
103+ {
104+ $ address = $ request ->getServerParams ()["REMOTE_ADDR " ];
105+ $ country = $ this ->location ->getCountry ($ address );
106+
107+ if ($ country !== null )
108+ {
109+ $ visit ["country_code " ] = $ country ["iso_code " ];
110+ }
111+ }
112+
85113 // insert the visit
86114 $ this ->visits ->addVisit ($ visit );
87115
0 commit comments