mirror of
https://github.com/jez500/pricebuddy.git
synced 2026-11-24 19:58:13 +01:00
52 lines
1.5 KiB
PHP
Executable File
52 lines
1.5 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Rules;
|
|
|
|
use App\Enums\StockStatus;
|
|
use App\Services\AutoCreateStore;
|
|
use App\Services\ScrapeUrl;
|
|
use Closure;
|
|
use Illuminate\Contracts\Validation\DataAwareRule;
|
|
use Illuminate\Contracts\Validation\ValidationRule;
|
|
|
|
class StoreUrl implements DataAwareRule, ValidationRule
|
|
{
|
|
protected array $data = [];
|
|
|
|
public function validate(string $attribute, mixed $value, Closure $fail): void
|
|
{
|
|
if (empty($value) || ! filter_var($value, FILTER_VALIDATE_URL)) {
|
|
$fail('The url must be a valid URL starting with http:// or https://');
|
|
|
|
return;
|
|
}
|
|
|
|
$store = ScrapeUrl::new($value)->getStore();
|
|
|
|
$shouldCreateStore = data_get($this->data, 'data.create_store', true);
|
|
|
|
if (empty($store) && ! $shouldCreateStore) {
|
|
$fail('The domain does not belong to any stores');
|
|
}
|
|
|
|
if ($store) {
|
|
$scrape = ScrapeUrl::new($value)->scrape();
|
|
|
|
$isUnavailable = StockStatus::matchFromScrapedValue($scrape['availability'] ?? null, $scrape['store']?->availability_match_config)->isUnavailable();
|
|
|
|
if (empty($scrape['title']) || (empty($scrape['price']) && ! $isUnavailable)) {
|
|
$fail('The url does not contain a valid title or price');
|
|
}
|
|
} elseif ($shouldCreateStore && ! AutoCreateStore::canAutoCreateFromUrl($value)) {
|
|
$fail('Unable to auto create store');
|
|
}
|
|
}
|
|
|
|
public function setData(array $data): static
|
|
{
|
|
$this->data = $data;
|
|
|
|
return $this;
|
|
}
|
|
}
|