.
*/
/**
* Callable object.
*
* Inspects and converts callables.
*
*
* echo Txp::get('\Textpattern\Type\TypeCallable', array('class', 'method'))->toString();
*
*
* @since 4.6.0
* @package Type
*/
namespace Textpattern\Type;
class TypeCallable implements TypeInterface
{
/**
* The callable.
*
* @var callable
*/
protected $callable;
/**
* Constructor.
*
* @param string $callable The callable
*/
public function __construct($callable)
{
$this->callable = $callable;
}
/**
* Gets the callable string presentation.
*
* @return string
*/
public function __toString()
{
return (string)$this->toString();
}
/**
* Converts a callable to a string presentation.
*
* If the callable is an object, returns the class name. For a callable
* array of object and method, a 'class::staticMethod' or a 'class->method',
* and for functions the name.
*
*
* echo (string) Txp::get('\Textpattern\Type\TypeCallable', function () {return 'Hello world!';});
*
*
* Returns 'Closure'.
*
*
* echo (string) Txp::get('\Textpattern\Type\TypeCallable', array('DateTimeZone', 'listAbbreviations'));
*
*
* Returns 'DateTimeZone::listAbbreviations'.
*
*
* echo (string) Txp::get('\Textpattern\Type\TypeCallable', array(new DateTime(), 'setTime'));
*
*
* Returns 'DateTime->setTime'.
*
*
* echo (string) Txp::get('\Textpattern\Type\TypeCallable', 'date');
*
*
* Returns 'date'.
*
*
* echo (string) Txp::get('\Textpattern\Type\TypeCallable', 1);
*
*
* Returns ''.
*
* @return string The callable as a human-readable string
*/
public function toString()
{
$callable = $this->callable;
if (is_object($callable)) {
return get_class($callable);
}
if (is_array($callable)) {
$class = array_shift($callable);
$separator = '::';
if (is_object($class)) {
$class = get_class($class);
$separator = '->';
}
array_unshift($callable, $class);
return implode($separator, array_filter($callable, 'is_scalar'));
}
if (!is_string($callable)) {
return '';
}
return $callable;
}
}