Visual Console Refactor: added a base Model class

Former-commit-id: 6051b7706686c9254851c2f9314f6c40bbc2af4d
This commit is contained in:
Alejandro Gallardo Escobar 2019-03-18 12:47:09 +01:00
parent c0e7256339
commit 9eebf18622
1 changed files with 64 additions and 0 deletions

View File

@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace Models;
abstract class Model
{
private $data;
abstract function validateData(array $data): void;
abstract function decode(array $data): array;
private function __construct(array $unknownData)
{
$this->validateData($unknownData);
$this->data = $this->decode($unknownData);
}
public static function fromArray(array $data): self
{
return new self($data);
}
public function toJson(): string
{
return \json_encode($this->data);
}
public function __toString(): string
{
return $this->toJson();
}
protected static function parseBool(mixed $value): boolean
{
if (\is_bool($value) === true) {
return $value;
} else if (\is_numeric($value) === true) {
return $value > 0;
} else if (\is_string($value) === true) {
return $value === '1' || $value === 'true';
} else {
return false;
}
}
protected static function notEmptyStringOr(mixed $val, string $def): mixed
{
return (\is_string($val) === true && count($val) > 0) ? $val : $def;
}
}