Files
lucent-laravel/src/Schema/Ui/Number.php
T
2024-03-21 22:33:41 +02:00

106 lines
2.8 KiB
PHP

<?php
namespace Lucent\Schema\Ui;
use Lucent\JsonSchema\Property\Property;
use Lucent\JsonSchema\Property\PropertyType;
use Lucent\JsonSchema\Property\TypeProperty;
use Lucent\Record\RecordData;
use Lucent\Schema\Field\FieldDataInterface;
use Lucent\Schema\Field\FieldInfo;
use Lucent\Schema\Field\FieldInterface;
use Lucent\Schema\Field\FieldType;
use Lucent\Schema\Validator\MinMaxInterface;
use Lucent\Schema\Validator\RequiredInterface;
use PhpOption\Option;
class Number implements FieldInterface, RequiredInterface,FieldDataInterface, MinMaxInterface
{
public FieldInfo $info;
public function __construct(
public string $name,
public string $label,
public bool $required = false,
public int $decimals = 0,
public ?int $min = null,
public ?int $max = null,
public ?float $default = null,
public bool $readonly = false,
public string $help = "",
public string $optionsFrom = "",
public string $optionsField = "",
public bool $optionsSuggest = false,
public string $group = "",
)
{
$this->info = new FieldInfo("number", "Number", FieldType::NUMBER);
}
public function format(RecordData $input, RecordData $output): RecordData
{
$value = $input->get($this->name);
if (!is_numeric($value)) {
$newValue = null;
} else {
$newValue = number_format(
$value,
$this->decimals,
".",
""
);
$newValue = $this->decimals === 0 ? (int)$newValue : floatval($newValue);
}
$output->set($this->name,$newValue);
return $output;
}
public function failRequired(mixed $value): bool
{
return is_null($value);
}
public function failMin(mixed $value): bool
{
if (is_null($value)) {
return false;
}
return $value < $this->min;
}
public function failMax(mixed $value): bool
{
if (is_null($value)) {
return false;
}
return $value > $this->min;
}
public function isRequired(): bool
{
return $this->required;
}
public function toJsonSchema(): Property
{
return new TypeProperty(
type: PropertyType::STRING,
id: $this->name,
title: Option::fromValue($this->label),
description: Option::fromValue($this->help, ""),
default: Option::fromValue($this->default, ""),
minLength: Option::fromValue($this->min),
maxLength: Option::fromValue($this->max),
readOnly: Option::fromValue($this->readonly, false),
enum: none(),
comment: Option::fromValue($this->group, ""),
format: none(),
);
}
}