61 lines
1.9 KiB
PHP
61 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace App\Service\Entities;
|
|
|
|
|
|
use Carbon\Carbon;
|
|
|
|
class InputEntity
|
|
{
|
|
public int $number;
|
|
public string $description;
|
|
public ?Carbon $date = null;
|
|
public ?string $phone = null;
|
|
|
|
public function __construct(private readonly array $data) {
|
|
$this->parse();
|
|
}
|
|
|
|
private function parse()
|
|
{
|
|
$this->validateNumber();
|
|
$this->validateDescription();
|
|
$this->validateDate();
|
|
$this->validatePhone();
|
|
|
|
}
|
|
|
|
private function validateNumber(): void {
|
|
if(!array_key_exists('number', $this->data) || !preg_match('/^\d+$/', trim($this->data['number']))) throw new \InvalidArgumentException('Invalid number');
|
|
$this->number = (int)$this->data['number'];
|
|
}
|
|
|
|
private function validateDescription(): void {
|
|
if(!array_key_exists('description', $this->data) || empty(trim($this->data['description']))) throw new \InvalidArgumentException('Empty description');
|
|
$this->description = trim($this->data['description']);
|
|
}
|
|
|
|
private function validateDate(): void {
|
|
if(!array_key_exists('dueDate', $this->data)) return;
|
|
$date = trim((string)$this->data['dueDate']);
|
|
if(!strlen($date)) return;
|
|
if (preg_match('/^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}(:\d{2})?)?$/', $date)) {
|
|
$this->date = Carbon::parse($date);
|
|
return;
|
|
}
|
|
throw new \InvalidArgumentException('Invalid date');
|
|
}
|
|
|
|
private function validatePhone(): void {
|
|
if(!array_key_exists('phone', $this->data)) return;
|
|
$rawPhone = $this->data['phone'];
|
|
$phone = trim((string)$rawPhone);
|
|
if(!strlen($phone)) return;
|
|
$checkPhone = str_replace([' ', '-'], '', $phone);
|
|
if(!preg_match('/^\+?\d{9,12}$/', $checkPhone)) {
|
|
throw new \InvalidArgumentException('Invalid phone number');
|
|
}
|
|
$this->phone = $rawPhone;
|
|
}
|
|
}
|