<?php
declare(strict_types=1);
namespace App\Command;
use Generator;
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\Cache\ItemInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
#[AsCommand(
name: 'app:check-genius-sports-urls',
description: 'Generates letter combinations for URLs and checks them concurrently at maximum speed.',
)]
class CheckGeniusSportsUrlsCommand extends Command
{
private const string BASE_URL = 'https://hosted.dcd.shared.geniussports.com/{letters}/';
private const int FAILURE_CACHE_TTL = 3600; // Cache failures for 1 hour to avoid re-checking
public function __construct(
private readonly HttpClientInterface $httpClient,
private readonly CacheInterface $cache
) {
parent::__construct();
}
protected function configure(): void
{
$this
->addArgument('length', InputArgument::REQUIRED, 'The number of capital letters for the combinations (e.g., 2 for AA-ZZ).')
->addOption('batch-size', 'b', InputOption::VALUE_OPTIONAL, 'Number of URLs to process concurrently in a batch.', 1000)
->addOption('timeout', null, InputOption::VALUE_OPTIONAL, 'Request timeout in seconds for each request.', 2.0)
->addOption('cache-lifetime', null, InputOption::VALUE_OPTIONAL, 'Cache lifetime in seconds for successful results.', 7 * 24 * 60 * 60)
->addOption('output-file', 'o', InputOption::VALUE_OPTIONAL, 'Optional file to write successful URLs to, one per line.');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$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');
$outputFile = $input->getOption('output-file');
if ($length <= 0 || $batchSize <= 0) {
$io->error('Length and batch-size must be positive integers.');
return Command::INVALID;
}
$fileHandle = null;
if ($outputFile) {
$fileHandle = fopen($outputFile, 'w');
if ($fileHandle === false) {
$io->error(sprintf('Could not open output file for writing: %s', $outputFile));
return Command::FAILURE;
}
}
$combinations = $this->generateCombinations($length);
$totalCombinations = 26 ** $length;
$io->progressStart((int) $totalCombinations);
$requests = [];
$processedCount = 0;
try {
foreach ($combinations as $combination) {
$url = str_replace('{letters}', $combination, self::BASE_URL);
// First, check cache to avoid network request entirely
$cacheKey = $this->getCacheKey($url);
$isHit = $this->cache->get($cacheKey, function(ItemInterface $item) use ($url, &$requests) {
// This callback is only executed on cache miss
$item->expiresAfter(self::FAILURE_CACHE_TTL); // Default to failure TTL
$requests[$url] = $this->httpClient->request('GET', $url, [
'timeout' => $timeout,
'max_redirects' => 1,
]);
return null; // Return null for now; we process the live request later
});
// If it was a cache hit and the result is a valid URL, process it
if (is_string($isHit)) {
$this->writeSuccess($io, $isHit, $fileHandle);
$io->progressAdvance();
$processedCount++;
continue; // Skip to the next combination
}
// If batch is full, process it
if (count($requests) >= $batchSize) {
$processedCount += $this->processBatch($io, $requests, $cacheLifetime, $fileHandle);
$requests = []; // Reset for next batch
}
}
// Process any remaining requests in the last batch
if (!empty($requests)) {
$processedCount += $this->processBatch($io, $requests, $cacheLifetime, $fileHandle);
}
} finally {
if ($fileHandle) {
fclose($fileHandle);
}
}
// Ensure progress bar completes fully, accounting for cache hits
$io->progressFinish();
$io->success(sprintf('Finished checking all %d combinations. Found %d working URLs.', $totalCombinations, $processedCount));
return Command::SUCCESS;
}
/**
* @param resource|null $fileHandle
* @return int The number of successful URLs found in this batch.
*/
private function processBatch(SymfonyStyle $io, array &$requests, int $cacheLifetime, $fileHandle): int
{
$successCount = 0;
// The stream() method processes responses as they complete, not in the order they were requested.
// This is the key to high concurrency.
foreach ($this->httpClient->stream($requests) as $response => $chunk) {
try {
// Process only when the response headers are received or an error occurs
if ($chunk->isFirst()) {
$url = $response->getInfo('url');
$cacheKey = $this->getCacheKey($url);
if ($response->getStatusCode() === 200) {
$content = $response->getContent(false); // false = don't throw on non-2xx
$extractedUrl = $this->extractValidUrl($content, $url);
if ($extractedUrl) {
$this->writeSuccess($io, $extractedUrl, $fileHandle);
$this->cacheResult($cacheKey, $extractedUrl, $cacheLifetime);
$successCount++;
}
}
// On any other status or error, the failure is already cached by the initial ->get() call.
// Advance progress bar after each response is handled (success or failure)
$io->progressAdvance();
}
} catch (TransportExceptionInterface $e) {
// This will catch timeouts, DNS errors, etc.
// The failure is already cached. We just need to advance the progress bar.
$io->progressAdvance();
if ($io->isVerbose()) {
$url = $response->getInfo('url') ?? 'unknown URL';
$io->writeln(sprintf(' <error>Transport Error:</error> %s (%s)', $url, $e->getMessage()));
}
}
}
return $successCount;
}
/**
* Generates all combinations of capital letters for a given length.
*/
private function generateCombinations(int $length): Generator
{
if ($length < 1) {
return;
}
$chars = range('A', 'Z');
$numChars = count($chars);
$indices = array_fill(0, $length, 0);
while (true) {
$combination = '';
foreach ($indices as $index) {
$combination .= $chars[$index];
}
yield $combination;
// Increment logic (like an odometer)
for ($i = $length - 1; $i >= 0; --$i) {
if (++$indices[$i] < $numChars) {
break;
}
$indices[$i] = 0;
if ($i === 0) { // All combinations have been generated
return;
}
}
}
}
private function extractValidUrl(string $content, string $fallbackUrl): ?string
{
if (strlen(trim($content)) === 0) {
return null;
}
// Fast check for expected content before running regex
if (str_contains($content, 'validateSetup(2,') && str_contains($content, '.web.geniussports.com')) {
if (preg_match("/,'([a-z]+\.web\.geniussports\.com)'/", $content, $matches)) {
return 'https://' . $matches[1];
}
}
// As a fallback, if content is present but regex fails, consider the original URL valid.
return $fallbackUrl;
}
private function getCacheKey(string $url): string
{
// PSR-6 cache keys have reserved characters. Replace them.
return 'genius_url_' . strtr($url, '{}()/\@:', '--------');
}
private function cacheResult(string $cacheKey, string $result, int $lifetime): void
{
$this->cache->get($cacheKey, function (ItemInterface $item) use ($result, $lifetime) {
$item->set($result);
$item->expiresAfter($lifetime);
return $result;
});
}
/**
* @param resource|null $fileHandle
*/
private function writeSuccess(SymfonyStyle $io, string $url, $fileHandle): void
{
if ($fileHandle) {
fwrite($fileHandle, $url . PHP_EOL);
}
// Only write to console if not writing to a file or in verbose mode
if (!$fileHandle || $io->isVerbose()) {
$io->writeln(" <info>SUCCESS:</info> {$url}");
}
}
}