| 1 |
<?php |
| 2 |
|
| 3 |
namespace App\Billingo\Service; |
| 4 |
|
| 5 |
use App\Billingo\Api\BillingoApi; |
| 6 |
use App\Billingo\Contracts\BillingoQueryInterface; |
| 7 |
use App\Billingo\Exceptions\BillingoException; |
| 8 |
use App\Billingo\Models\BillingoModel; |
| 9 |
use App\Billingo\Validation\Validator; |
| 10 |
use Closure; |
| 11 |
use http\Exception\BadMethodCallException; |
| 12 |
|
| 13 |
abstract class BillingoQuery implements BillingoQueryInterface |
| 14 |
{ |
| 15 |
protected array $filters = []; |
| 16 |
protected array $modified; |
| 17 |
protected string $callableMethod = 'getAll'; |
| 18 |
|
| 19 |
abstract protected function getValidator(): Validator; |
| 20 |
|
| 21 |
public function getApi(): ?BillingoApi |
| 22 |
{ |
| 23 |
return $this->send(); |
| 24 |
} |
| 25 |
|
| 26 |
public function getData(): null|array|BillingoModel|BillingoCollection |
| 27 |
{ |
| 28 |
if (isset($this->modified)) { |
| 29 |
|
| 30 |
return $this->modified; |
| 31 |
} |
| 32 |
|
| 33 |
$response = $this->send(); |
| 34 |
|
| 35 |
return $response?->getResponse()?->getData(); |
| 36 |
} |
| 37 |
|
| 38 |
public function getFilters(): array |
| 39 |
{ |
| 40 |
return $this->filters; |
| 41 |
} |
| 42 |
|
| 43 |
public function where(string $property, mixed $value): self |
| 44 |
{ |
| 45 |
$validator = $this->getValidator(); |
| 46 |
|
| 47 |
try { |
| 48 |
|
| 49 |
if ($validator->validateProperty($property, $value)) { |
| 50 |
|
| 51 |
$this->filters[$property] = $value; |
| 52 |
} |
| 53 |
|
| 54 |
} catch (BillingoException $exception) { |
| 55 |
//don't do anything |
| 56 |
} |
| 57 |
|
| 58 |
return $this; |
| 59 |
} |
| 60 |
|
| 61 |
public function __call(string $name, array $arguments): self |
| 62 |
{ |
| 63 |
if (str_starts_with($name, 'where')) { |
| 64 |
$name = camelToSnake(substr($name, 5)); |
| 65 |
|
| 66 |
if (!array_key_exists($name, $this->getValidator()->getRules())) { |
| 67 |
|
| 68 |
throw new BadMethodCallException(); |
| 69 |
} |
| 70 |
|
| 71 |
$this->where($name, $arguments[0]); |
| 72 |
|
| 73 |
return $this; |
| 74 |
} |
| 75 |
|
| 76 |
throw new BadMethodCallException(); |
| 77 |
} |
| 78 |
|
| 79 |
protected function send(): ?BillingoApi |
| 80 |
{ |
| 81 |
if (class_exists($this->getOwner())) { |
| 82 |
$method = $this->callableMethod; |
| 83 |
|
| 84 |
return (new ($this->getOwner()))->$method($this->getFilters()); |
| 85 |
} |
| 86 |
|
| 87 |
return null; |
| 88 |
} |
| 89 |
} |
| 90 |
|