Files
pricebuddy/app/Services/ProductSourceSearchService.php
Jeremy 1a857e1582 feat: meta extraction API and typed scrape-strategy DTOs
Add a meta-extraction API endpoint and refactor store scrape strategies onto
strongly-typed DTOs.

- POST /api/meta-extraction endpoint with SSRF protection on the target URL
- Typed scrape-strategy DTOs and enums (StandardStrategyDto, AvailabilityMatchDto,
  AvailabilityMatchType, AvailabilityStrategyDto, StoreScraperStrategySetDto)
  with a model cast for the stores.scrape_strategy column
- Convert ScrapeUrl, StrategyExtractor and availability resolution to consume the
  typed strategy slots; preserve legacy plain-string availability match entries
- Filament scrape_strategy form bridge plus DTO test coverage
2026-06-18 23:13:01 +10:00

183 lines
5.6 KiB
PHP

<?php
namespace App\Services;
use App\Dto\StandardStrategyDto;
use App\Models\ProductSource;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Jez500\WebScraperForLaravel\Exceptions\DomSelectorException;
use Jez500\WebScraperForLaravel\Facades\WebScraper;
use Jez500\WebScraperForLaravel\WebScraperInterface;
use Psr\Log\LoggerInterface;
class ProductSourceSearchService
{
protected LoggerInterface $logger;
protected ?string $htmlMemoryCache = null;
public bool $logErrors = true;
protected array $keys = [
'list_container',
'product_title',
'product_url',
];
public function __construct(protected ProductSource $source)
{
// @phpstan-ignore-next-line - withContext is valid.
$this->logger = Log::channel('db')->withContext(['source' => $source->getKey()]);
}
public static function new(ProductSource $source): self
{
return resolve(static::class, ['source' => $source]);
}
public function makeScraper(string $query): WebScraperInterface
{
return WebScraper::make($this->source->scraper_service)
->from($this->buildSearchUrl($query));
}
public function search(string $query): Collection
{
$strategy = data_get($this->source, 'extraction_strategy', []);
$items = $this->getList($query);
try {
// For each result, instantiate a new scraper and extract the title and url.
return $items->map(function ($item) use ($strategy) {
$itemScraper = WebScraper::http()->setBody($item);
return [
'title' => $this->extractValue($itemScraper, $strategy['product_title'], 'product_title'),
'url' => $this->scrapeUrl($itemScraper, $strategy),
'content' => $item,
];
})
->reject(fn ($item) => empty($item['title']) || empty($item['url']))
->values();
} catch (DomSelectorException $e) {
$this->errorLog($e->getMessage());
return collect();
}
}
public function getHtml(string $query): ?string
{
if (is_null($this->htmlMemoryCache)) {
// We cache the body response for 5 minutes to prevent multiple scrapes.
$this->htmlMemoryCache = cache()
->remember(
'product_source_search:html:'.md5($this->source->updated_at.':'.$query),
now()->addMinutes(5),
fn () => $this->makeScraper($query)->get()->getBody()
);
}
return $this->htmlMemoryCache;
}
public function getList(string $query): Collection
{
$strategy = data_get($this->source, 'extraction_strategy', []);
$scraper = $this->makeScraper($query)->get();
if ($errors = $scraper->getErrors()) {
$this->errorLog('Error scraping Product Source search result page', [
'store_id' => $this->source->getKey(),
'errors' => $errors,
]);
return collect();
}
return $this->scrapeOption($scraper, ($strategy['list_container']));
}
public function buildSearchUrl(string $query): string
{
return str_replace(':search_term', urlencode($query), $this->source->search_url);
}
/**
* Extract a single value from a slot, applying prepend/append (and regex /
* schema.org handling) via the shared StrategyExtractor. Returns null and
* logs if the selector is invalid, so one bad item does not abort the search.
*
* @param array<string, mixed> $slot
*/
protected function extractValue(WebScraperInterface $scraper, array $slot, string $field): ?string
{
$dto = StandardStrategyDto::fromArray($slot);
if ($dto === null) {
return null;
}
try {
return StrategyExtractor::extract($scraper, $dto, $field);
} catch (DomSelectorException $e) {
$this->errorLog('Error extracting field from search result item', [
'field' => $field,
'error' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
]);
}
return null;
}
protected function scrapeOption(WebScraperInterface $scraper, array $options, bool $multiple = false): Collection
{
$type = data_get($options, 'type');
$value = data_get($options, 'value');
$value = match ($type) {
'selector' => ScrapeUrl::parseSelector($value),
default => [$value]
};
$method = ScrapeUrl::getMethodFromType($type);
try {
// Return a collection of values.
return call_user_func_array([$scraper, $method], $value);
} catch (DomSelectorException $e) {
$this->errorLog('Error scraping URL', [
'error' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
]);
}
return collect();
}
protected function scrapeUrl(WebScraperInterface $scraper, array $strategy): ?string
{
$url = $this->extractValue($scraper, $strategy['product_url'], 'product_url');
if (! empty($strategy['product_url']['url_decode'])) {
$url = urldecode((string) $url);
}
return $url;
}
protected function errorLog(string $message, array $data = []): void
{
if (! $this->logErrors) {
return;
}
$this->logger->error($message, $data);
}
}