mirror of
https://github.com/jez500/pricebuddy.git
synced 2026-11-24 19:58:13 +01:00
43 lines
1.2 KiB
PHP
Executable File
43 lines
1.2 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Rules;
|
|
|
|
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
|
|
{
|
|
$store = ScrapeUrl::new($value)->getStore();
|
|
|
|
$shouldCreateStore = data_get($this->data, 'data.create_store', true);
|
|
|
|
if (empty($value) || (empty($store) && ! $shouldCreateStore)) {
|
|
$fail('The domain does not belong to any stores');
|
|
}
|
|
|
|
if ($store) {
|
|
$scrape = ScrapeUrl::new($value)->scrape();
|
|
|
|
if (empty($scrape['title']) || empty($scrape['price'])) {
|
|
$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;
|
|
}
|
|
}
|