clrghouz/app/Classes/BBS/Frame/Field.php

110 lines
1.9 KiB
PHP
Raw Normal View History

2023-08-10 02:17:01 +00:00
<?php
namespace App\Classes\BBS\Frame;
use Illuminate\Support\Arr;
final class Field
{
private array $attributes = [];
private const attributes = [
'attribute', // Color attribute when rendering values
'pad', // Pad character remaining characters up to length
'size', // Size of the field
'name', // Field name
'type', // Type of field
'value', // Current value
'x', // X position in the frame
'y', // Y position in the frame
];
/** @var string[] Attributes that should be masked */
private const mask = [
'p',
];
private const mask_attribute = '*';
public function __construct(array $values)
{
array_walk($values,function($value,$key) {
$this->{$key} = $value;
});
}
public function __get($key): mixed
{
switch ($key) {
case 'can_add':
return strlen($this->value) < $this->size;
case 'mask':
return in_array($this->type,self::mask) ? '*' : NULL;
case 'X':
return $this->x+strlen($this->value);
default:
return Arr::get($this->attributes,$key);
}
}
public function __isset($key): bool
{
return isset($this->attributes[$key]);
}
public function __set($key,$value): void
{
if (! in_array($key,self::attributes))
throw new \Exception('Unknown attribute key:'.$key);
$this->attributes[$key] = $value;
}
/**
* Append a char to the value, only if there is space to do so
*
* @param string $char
* @return bool
*/
public function append(string $char): bool
{
if (is_null($this->value))
$this->clear();
if ($this->can_add) {
$this->value .= $char;
return TRUE;
}
return FALSE;
}
/**
* Clear the field value
*
* @return void
*/
public function clear(): void
{
$this->value = '';
}
/**
* Delete a character from the value, only if there are chars to do so
*
* @return bool
*/
public function delete(): bool
{
if (strlen($this->value)) {
$this->value = substr($this->value,0,-1);
return TRUE;
}
return FALSE;
}
}