2020-12-18 05:57:23 +01:00
|
|
|
<?php
|
|
|
|
|
2021-07-19 07:53:45 +02:00
|
|
|
declare(strict_types=1);
|
|
|
|
|
2020-12-18 05:57:23 +01:00
|
|
|
namespace App\Service;
|
|
|
|
|
2022-02-15 06:21:56 +01:00
|
|
|
use App\Service\DeviceDetector\DeviceResult;
|
|
|
|
use Psr\Cache\CacheItemPoolInterface;
|
|
|
|
use Symfony\Component\Cache\Adapter\ProxyAdapter;
|
|
|
|
|
2022-07-01 08:06:29 +02:00
|
|
|
final class DeviceDetector
|
2020-12-18 05:57:23 +01:00
|
|
|
{
|
2023-03-02 15:33:57 +01:00
|
|
|
private CacheItemPoolInterface $psr6Cache;
|
2022-02-15 04:56:20 +01:00
|
|
|
|
2022-07-01 08:06:29 +02:00
|
|
|
private \DeviceDetector\DeviceDetector $dd;
|
2020-12-18 05:57:23 +01:00
|
|
|
|
2022-02-16 00:04:59 +01:00
|
|
|
/** @var array<string, DeviceResult> */
|
2022-07-01 08:06:29 +02:00
|
|
|
private array $deviceResults = [];
|
2022-02-16 00:04:59 +01:00
|
|
|
|
2022-02-15 06:21:56 +01:00
|
|
|
public function __construct(
|
|
|
|
CacheItemPoolInterface $psr6Cache
|
|
|
|
) {
|
2023-03-02 15:33:57 +01:00
|
|
|
$this->psr6Cache = new ProxyAdapter($psr6Cache, 'device_detector.');
|
2022-02-15 06:21:56 +01:00
|
|
|
|
2022-02-15 04:56:20 +01:00
|
|
|
$this->dd = new \DeviceDetector\DeviceDetector();
|
2020-12-18 05:57:23 +01:00
|
|
|
}
|
|
|
|
|
2022-02-15 06:21:56 +01:00
|
|
|
public function parse(string $userAgent): DeviceResult
|
2020-12-18 05:57:23 +01:00
|
|
|
{
|
2022-02-15 04:56:20 +01:00
|
|
|
$userAgentHash = md5($userAgent);
|
|
|
|
|
2022-02-16 00:04:59 +01:00
|
|
|
if (isset($this->deviceResults[$userAgentHash])) {
|
|
|
|
return $this->deviceResults[$userAgentHash];
|
|
|
|
}
|
|
|
|
|
2023-03-02 15:33:57 +01:00
|
|
|
$cacheItem = $this->psr6Cache->getItem($userAgentHash);
|
2022-02-15 04:56:20 +01:00
|
|
|
|
2023-03-02 15:33:57 +01:00
|
|
|
if (!$cacheItem->isHit()) {
|
|
|
|
$this->dd->setUserAgent($userAgent);
|
|
|
|
$this->dd->parse();
|
2020-12-18 05:57:23 +01:00
|
|
|
|
2023-03-02 15:33:57 +01:00
|
|
|
$cacheItem->set(DeviceResult::fromDeviceDetector($userAgent, $this->dd));
|
2022-02-16 00:04:59 +01:00
|
|
|
|
2023-03-02 15:33:57 +01:00
|
|
|
/** @noinspection SummerTimeUnsafeTimeManipulationInspection */
|
|
|
|
$cacheItem->expiresAfter(86400 * 7);
|
|
|
|
|
|
|
|
$this->psr6Cache->saveDeferred($cacheItem);
|
|
|
|
}
|
|
|
|
|
|
|
|
$deviceResult = $cacheItem->get();
|
2022-02-16 00:04:59 +01:00
|
|
|
$this->deviceResults[$userAgentHash] = $deviceResult;
|
|
|
|
|
|
|
|
return $deviceResult;
|
2020-12-18 05:57:23 +01:00
|
|
|
}
|
|
|
|
}
|