eesyphp/src/Db/Attr.php
Benjamin Renard 347de8eeaf
Add DbObject
2024-02-18 18:27:58 +01:00

81 lines
1.9 KiB
PHP

<?php
namespace EesyPHP\Db;
class Attr {
/**
* Attribute default value
* @var mixed
*/
protected $default = null;
/**
* Attribute required flag
* @var bool
*/
public $required = false;
/**
* Constructor
* @param array<string,mixed>|null $parameters Attribute parameters
*/
public function __construct($parameters=null) {
if (!is_array($parameters))
return;
foreach($parameters as $key => $value) {
if (!property_exists($this, $key))
throw new DbException("Attribute %s as no %s property", get_called_class(), $key);
$this -> $key = $value;
}
}
/**
* Compute attribute default value
* @param mixed $value Override configured default value
* @return mixed
*/
public function default($value=null) {
$value = $value?$value:$this -> default;
return is_callable($value)?$value():$value;
}
/**
* Compute attribute value from DB
* @param mixed $value The value as retrieved from debug
* @return mixed The attribute value
*/
public function from_db($value) {
return is_null($value)?$this -> default():$value;
}
/**
* Compute attribute value for DB
* @param mixed $value The value as handled in PHP
* @return mixed The attribute value as stored in DB
*/
public function to_db($value) {
return is_null($value)?$this -> default():$value;
}
/**
* Compute attribute value from string
* @param string $value The input value
* @return mixed The attribute value as handled in PHP
*/
public function from_string($value) {
return self :: from_db($value);
}
/**
* Compute attribute value to string
* @param mixed $value The input value as handled in PHP
* @return string The attribute value as string
*/
public function to_string($value) {
$value = self :: to_db($value);
return is_null($value)?'':strval($value);
}
}