<?php
namespace App\Twig;
use App\Service\Client\User\AmateurListingService;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Contracts\Cache\CacheInterface;
use Frivol\Common\JSON;
class AmateurExtension extends AbstractExtension
{
public function __construct(
private readonly AmateurListingService $service,
private readonly \Redis $redis,
private readonly ParameterBagInterface $params,
) {}
public function getFunctions(): array
{
return [
new TwigFunction('randomOnlineAmateurs', [$this, 'getRandomOnlineAmateurs']),
new TwigFunction('isWebcamOnline', [$this, 'isWebcamOnline']),
];
}
public function getRandomOnlineAmateurs(int $limit = 6): ?array
{
$result = $this->service->getOnlineAmateurs(1, 50, 10)->getItems();
if (empty($result)) {
return null;
}
shuffle($result);
return array_slice($result, 0, $limit);
}
public function isWebcamOnline(array $amateur): bool
{
if (!isset($amateur['id'])) {
return false;
}
try {
$json = $this->redis->get($this->params->get('redis_online_livecams_key'));
if (!is_string($json)) {
return false;
}
$data = JSON::decode($json);
if (!isset($data['streams'])) {
return false;
}
foreach ($data['streams'] as $stream) {
if (isset($stream['amateurMemberId']) && $stream['amateurMemberId'] === $amateur['id']) {
return true;
}
}
} catch (\Throwable $e) {}
return false;
}
}