2019-03-18 12:47:09 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
namespace Models;
|
|
|
|
|
|
|
|
abstract class Model
|
|
|
|
{
|
|
|
|
|
|
|
|
private $data;
|
|
|
|
|
|
|
|
|
2019-03-18 13:35:30 +01:00
|
|
|
protected abstract function validateData(array $data): void;
|
2019-03-18 12:47:09 +01:00
|
|
|
|
|
|
|
|
2019-03-18 13:35:30 +01:00
|
|
|
protected abstract function decode(array $data): array;
|
2019-03-18 12:47:09 +01:00
|
|
|
|
|
|
|
|
2019-03-19 12:03:02 +01:00
|
|
|
protected function __construct(array $unknownData)
|
2019-03-18 12:47:09 +01:00
|
|
|
{
|
|
|
|
$this->validateData($unknownData);
|
|
|
|
$this->data = $this->decode($unknownData);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public function toJson(): string
|
|
|
|
{
|
|
|
|
return \json_encode($this->data);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public function __toString(): string
|
|
|
|
{
|
|
|
|
return $this->toJson();
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2019-03-19 12:03:02 +01:00
|
|
|
protected static function parseBool($value): bool
|
2019-03-18 12:47:09 +01:00
|
|
|
{
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2019-03-19 12:03:02 +01:00
|
|
|
protected static function notEmptyStringOr($val, $def)
|
|
|
|
{
|
|
|
|
return (\is_string($val) === true && strlen($val) > 0) ? $val : $def;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
protected static function issetInArray(array $val, array $keys)
|
2019-03-18 12:47:09 +01:00
|
|
|
{
|
2019-03-19 12:03:02 +01:00
|
|
|
foreach ($keys as $key => $value) {
|
|
|
|
if (isset($val[$value])) {
|
|
|
|
return $val[$value];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
2019-03-18 12:47:09 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
}
|