class UserAgentService
{
public function getBrowser(string $userAgent): string
{
$browserArray = [
'Chrome' => 'Chrome',
'Firefox' => 'Firefox',
'Safari' => 'Safari',
'Edge' => 'Edge',
'Opera' => 'Opera',
'Internet Explorer' => 'MSIE|Trident',
];
foreach ($browserArray as $key => $pattern) {
if (preg_match("/$pattern/i", $userAgent)) {
return $key;
}
}
return 'Unknown Browser';
}
public function getOS(string $userAgent): string
{
$osArray = [
'Windows' => 'Windows',
'MacOS' => '(Mac_PowerPC)|(Macintosh)',
'Linux' => 'Linux',
'iOS' => 'iPhone|iPad',
'Android' => 'Android',
];
foreach ($osArray as $key => $pattern) {
if (preg_match("/$pattern/i", $userAgent)) {
return $key;
}
}
return 'Unknown OS';
}
public function getDevice(string $userAgent): string
{
if (preg_match("/Mobile|Android|iPhone|iPad/i", $userAgent)) {
return 'Mobile';
} elseif (preg_match("/Tablet|iPad/i", $userAgent)) {
return 'Tablet';
}
return 'Desktop';
}
public function getLanguage(array $languages): string
{
if (!empty($languages)) {
return trim($languages[0]);
}
return 'Unknown Language';
}
public function getReferer(?string $referers): string
{
if ($referers && !empty($referers)) {
return $referers;
}
return 'Direct';
}
public function getUserDetails(string $userAgent, array $languages): array
{
return [
'browser' => $this->getBrowser($userAgent),
'os' => $this->getOS($userAgent),
'device' => $this->getDevice($userAgent),
'language' => $this->getLanguage($languages),
];
}
}