PandaHugMonster / php-simputils

Framework that provides tools for developers and software architects to improve their performance, analyze code easier and improving overall experience with PHP.
MIT License
3 stars 0 forks source link

Converters and Smooth Conversions #136

Closed PandaHugMonster closed 3 months ago

PandaHugMonster commented 1 year ago

In python 3 exists really comfortable way to convert objects and other types through simple short methods. This ticket is for implementation of the minimal set of methods to allow objects to configure the way those should be converted to primitives. The following methods (and corresponding meta-magic methods) should be implemented as:

Example of they way it works:

Non-implemented ___int()

/**
 * @property $item1
 */
class NOBJ extends SimpleObject {

    #[Property]
    protected ?DateTime $_item1 = null;
}
PHP::init();

$obj1 = new NOBJ();
$obj1->item1 = now();

pd(int($obj1));

Output would be:

Fatal error: Uncaught spaf\simputils\exceptions\types\NonIntObjException: This object does not support int conversion. Override ___int()
/**
 * @property $item1
 */
class NOBJ extends SimpleObject {

    #[Property]
    protected ?DateTime $_item1 = null;

    protected function ___int(): int {
        return $this->_item1->timestamp;
    }
}
PHP::init();

$obj1 = new NOBJ();
$obj1->item1 = now();

pd(int($obj1));

Output would be:

1678048191
PandaHugMonster commented 1 year ago

IDEA. Maybe add possibility to convert to "resource":

PandaHugMonster commented 3 months ago

This functionality will be implemented in a separate repo aka "SimpUtils Caster"