<?php
trait LazyGetSet
{
private $useFluentSetter = true;
/**
* Change fluent setter.
*/
public function setFluentSetter($flag)
{
$this->useFluentSetter = $flag;
}
public function __call($method, $args)
{
if ((0 === strpos($method, 'get')) && ($ptyName = $this->getLazyPropertyName($method))) {
return $this->lazyGet($ptyName, $args);
}
if ((0 === strpos($method, 'set')) && ($ptyName = $this->getLazyPropertyName($method))) {
return $this->lazySet($ptyName, $args);
}
}
/**
* Detect property name from setter/getter methods.
*/
private function getLazyPropertyName($method)
{
$ptyName = lcfirst(substr($method, 3));
if (property_exists($this, $ptyName)) {
return $ptyName;
}
}
/**
* Get property value
*/
private function lazyGet($ptyName)
{
return $this->{$ptyName};
}
/**
* Inject property value.
*
* @todo Validate data type
*/
private function lazySet($ptyName, $args)
{
if($this->validate($ptyName, $args[0])) {
$this->{$ptyName} = $args[0];
}
if ($this->useFluentSetter) {
return $this;
}
}
private function validate($variable_name, $variable_value) {
$hints = $this->getPropertyHintType(__CLASS__, $variable_name);
if(isset($hints['@var'])) {
$validateCallback = array(
'string' => 'is_string',
'integer' => 'is_integer',
'array' => 'is_array',
'float' => 'is_float',
'double' => 'is_double',
'boolean' => 'is_bool',
'object' => 'is_object',
'resource' => 'is_resource',
);
if(isset($validateCallback[$hints['@var']])) {
return call_user_func($validateCallback[$hints['@var']], $variable_value);
} else {
return $variable_value instanceof $hints['@var'];
}
}
}
public function getPropertyHintType($className, $propertyName) {
$class = new ReflectionClass($className);
$match = array();
$docs = array();
foreach(explode("\n",(str_replace(array('*', '/'),'', $class->getProperty($propertyName)->getDocComment()))) as $doc) {
$docs[] = trim($doc);
}
$return = array();
foreach(array_filter($docs) as $doc) {
$match = array();
preg_match('/^([@].*)\ (.*)$/', $doc, $match);
if($match){
$return[$match[1]] = trim($match[2]);
}
}
return $return;
}
}
namespace quyentest;
class MyClass
{
use LazyGetSet;
/**
* @var integer
*/
private $name;
/**
* @var MyClass
*/
private $instant;
}
//echo (new MyClass())->setName(123)->getName();
$MyClass = new MyClass();
echo $MyClass->setInstant('a')->getInstant();
preferences:
37.06 ms | 402 KiB | 5 Q