♻️ Move validation to Input class

This commit is contained in:
Dan Jones 2022-03-25 17:02:09 -05:00
commit 3246004e58
5 changed files with 79 additions and 37 deletions

View file

@ -4,22 +4,52 @@ namespace App\Models;
use App\Exceptions\Quit;
class Input
class Input extends Model
{
public ?array $files;
public ?string $url;
public ?string $destination;
public ?string $title;
public bool $low;
public bool $sync;
public function assertValid(): void
public function assertValid(): self
{
// @todo probably should use a validator for this
throw_if(
empty($this->files) && empty($this->url),
Quit::class,
'Must have either a valid file or URL'
);
return $this;
}
public function hasURL(): bool
{
return !empty($this->url);
}
public function setInput(?array $files): void
{
$this->setFiles($files);
}
public function setFiles(?array $files): void
{
$this->files = array_map(function (string $file) {
if (!file_exists($file)) {
throw new Quit("$file is not a valid file");
}
return realpath($file);
}, $files ?? []);
}
public function setDestination(?string $dir): void
{
throw_if(!is_dir($dir), Quit::class, "$dir is not a valid directory");
$this->destination = $dir;
// @todo get title from .nfo file, if available
}
}

25
app/Models/Model.php Normal file
View file

@ -0,0 +1,25 @@
<?php
namespace App\Models;
use Illuminate\Support\Str;
abstract class Model
{
public function __construct(array $data = [])
{
foreach ($data as $k => $v) {
$this->__set($k, $v);
}
}
public function __set(string $key, $value)
{
$setter = 'set' . Str::studly($key);
if (method_exists($this, $setter)) {
$this->$setter($value);
} elseif (property_exists($this, $key)) {
$this->$key = $value;
}
}
}