ldc-com-app-bo/app/Lib/Inputs/Definition/InputData.php

93 lines
3.2 KiB
PHP

<?php
namespace App\Lib\Inputs\Definition;
use App\Enums\Formularies\InputTypeEnum;
/**
* @property-read string $title The input type placeholder
* @property-read integer $type The input type value
* @property-read string|array<integer,string> $value The input value, either a string or an array
* with the value index and label
* (for Multiselect and checkboxes)
* @property-read boolean $required The input is required ?
* @package App\Lib\Inputs
*/
class InputData extends \stdClass
{
/**
* Get property
*
* @param string $name
* @return mixed
* @throws \TypeError If prop is undefined.
*/
public function __get(string $name): mixed
{
if (in_array($name, ['title', 'type', 'value', 'required'])) {
return $this->{$name};
}
throw new \TypeError("undefined property {$name}");
}
/**
* Make and instance
*
* @param string $title
* @param \App\Enums\Formularies\InputTypeEnum|integer $type
* @param string|array<integer,string> $data
* @param boolean $required
* @return \App\Lib\Inputs\Definition\InputData
* @throws \RuntimeException If $type or $data is wrong.
*/
public static function make(string $title, $type, $data, bool $required): self
{
$ipTypeData = new self();
$ipTypeData->title = $title;
$ipTypeData->type = (\is_object($type) and \get_class($type) === InputTypeEnum::class) ?
$type->value : $type;
$ipTypeData->value = $data;
$ipTypeData->required = $required;
self::assertIsInputTypeData($ipTypeData);
return $ipTypeData;
}
/**
* Confirm $data is of type InputTypeData
*
* @param \App\Lib\Inputs\Definition\InputData $data
* @return void
* @throws \RuntimeException If $data is wrong.
*/
public static function assertIsInputTypeData(InputData $data)
{
$title = $data->title;
$type = $data->type;
$value = $data->value;
$required = $data->required;
if (!\is_string($title)) {
throw new \RuntimeException("InputTypeData 'title' should be a string");
}
if (!\is_integer($type)) {
throw new \RuntimeException("InputTypeData 'type' should be an integer");
}
if (!\is_bool($required)) {
throw new \RuntimeException("InputTypeData 'required' should be a boolean");
}
try {
$type = InputTypeEnum::make($type);
} catch (\BadMethodCallException $e) {
throw new \RuntimeException($e->getMessage());
}
if (!\is_null($value) && !\is_string($value) && !\is_array($value)) {
$type = \gettype($value);
$value = \json_encode($value);
throw new \RuntimeException(
"InputTypeData 'value' should be string or array given '{$value}' of type '{$type}'"
);
}
}
}