<?php
declare(strict_types=1);
namespace App\Command;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
#[AsCommand(
name: 'app:check-genius-sports-urls',
description: 'Generates letter combinations for URLs and checks them concurrently.',
)]
class CheckGeniusSportsUrlsCommand extends Command
{
private HttpClientInterface $httpClient;
private CacheInterface $cache;
private const string BASE_URL = 'https://hosted.dcd.shared.geniussports.com/%s/';
private ?SymfonyStyle $io = null;
private const array CHARACTERS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
private const int NUM_CHARS = 26; // Precomputed for speed
public function __construct(HttpClientInterface $httpClient, CacheInterface $cache)
{
parent::__construct();
$this->httpClient = $httpClient;
$this->cache = $cache;
}
protected function configure(): void
{
$this
->addArgument('length', InputArgument::REQUIRED, 'The number of capital letters for the combinations.')
->addOption('batch-size', 'b', InputOption::VALUE_OPTIONAL, 'Number of URLs to process concurrently.', 500)
->addOption('timeout', null, InputOption::VALUE_OPTIONAL, 'Request timeout in seconds.', 1)
->addOption('cache-lifetime', null, InputOption::VALUE_OPTIONAL, 'Cache lifetime in seconds.', 7 * 24 * 60 * 60);
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->io = new SymfonyStyle($input, $output);
$length = (int)$input->getArgument('length');
$batchSize = (int)$input->getOption('batch-size');
$timeout = (float)$input->getOption('timeout');
$cacheLifetime = (int)$input->getOption('cache-lifetime');
if ($length <= 0 || $batchSize <= 0) {
$this->io->error('Length and batch size must be positive integers.');
return Command::INVALID;
}
$successfulUrls = [];
$indices = array_fill(0, $length, 0);
$keepGenerating = true;
$urlBatch = [];
$estimatedTotal = ($length > 0 && $length <= 10) ? pow(self::NUM_CHARS, $length) : 0; // Limit for progress
$this->io->progressStart(min($estimatedTotal, 10000)); // Cap progress to avoid slowdowns
while ($keepGenerating) {
$combination = '';
for ($i = 0; $i < $length; $i++) {
$combination += self::CHARACTERS[$indices[$i]];
}
$urlBatch[] = sprintf(self::BASE_URL, $combination); // Faster string formatting
// Advance indices
$pos = $length - 1;
while ($pos >= 0) {
$indices[$pos]++;
if ($indices[$pos] < self::NUM_CHARS) {
break;
}
$indices[$pos] = 0;
$pos--;
}
$keepGenerating = ($pos >= 0);
if (count($urlBatch) >= $batchSize || !$keepGenerating) {
$this->processUrlBatch($urlBatch, $successfulUrls, $timeout, $cacheLifetime);
$urlBatch = [];
if ($estimatedTotal > 0) {
$this->io->progressAdvance(count($urlBatch)); // Batch progress updates
}
}
}
$this->io->progressFinish();
if (!empty($successfulUrls)) {
$this->io->success('Successfully retrieved content from the following URLs:');
$this->io->listing(array_unique($successfulUrls)); // Avoid duplicates
} else {
$this->io->note('No URLs returned content successfully.');
}
return Command::SUCCESS;
}
private function processUrlBatch(array &$urlsInBatch, array &$successfulUrls, float $timeout, int $cacheLifetime): void
{
if (empty($urlsInBatch) || $this->io === null) {
return;
}
$cachedResults = [];
$urlsToFetch = [];
foreach ($urlsInBatch as $url) {
$cacheKey = 'genius_url_' . md5($url);
if ($this->cache->hasItem($cacheKey)) {
$cachedItem = $this->cache->getItem($cacheKey);
$result = $cachedItem->get();
if ($result !== null) {
$cachedResults[] = $result;
}
} else {
$urlsToFetch[] = $url;
}
}
$successfulUrls = array_merge($successfulUrls, $cachedResults);
if (empty($urlsToFetch)) {
return;
}
$responses = [];
foreach ($urlsToFetch as $url) {
$responses[$url] = $this->httpClient->request('GET', $url, [
'timeout' => $timeout,
'max_redirects' => 1,
]);
}
$this->httpClient->stream($responses, function ($response, string $type) use (&$successfulUrls, $cacheLifetime) {
if ($type === HttpClientInterface::EVENT_RESPONSE_COMPLETE) {
$url = $response->getInfo('url');
$cacheKey = 'genius_url_' . md5($url);
try {
$statusCode = $response->getStatusCode();
if ($statusCode >= 200 && $statusCode < 300) {
$content = $response->getContent(false); // Non-blocking if possible
if (trim($content) !== '') {
$result = $this->extractValidUrl($content, $url);
if ($result !== null) {
$successfulUrls[] = $result;
$this->cacheResult($cacheKey, $result, $cacheLifetime);
if ($this->io->isVerbose()) {
$this->io->writeln(" <info>SUCCESS:</info> {$result}");
}
}
}
}
} catch (TransportExceptionInterface $e) {
$this->cacheResult($cacheKey, null, 60); // Short cache for failures
} catch (\Exception $e) {
// Silently ignore other exceptions for speed
}
}
});
}
private function extractValidUrl(string $content, string $fallbackUrl): ?string
{
if (preg_match('/validateSetup\(2,(.*)\);/', $content, $matches) && isset($matches[1])) {
if (preg_match("/,'([a-z]+\.web\.geniussports\.com)'/", $matches[1], $validUrlMatches) && isset($validUrlMatches[1])) {
return 'https://' . $validUrlMatches[1];
}
}
return $fallbackUrl;
}
private function cacheResult(string $cacheKey, ?string $result, int $lifetime): void
{
$item = $this->cache->getItem($cacheKey);
$item->set($result);
$item->expiresAfter($lifetime);
$this->cache->save($item);
}
}