Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
namespace Slim;
use Pimple\Container;
trait ResolveCallable
{
protected $container;
protected function resolveCallable($callable)
{
if (is_string($callable) && strpos($callable, ':') !== false && preg_match('!^([^\:]+)\:([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)$!', $callable, $matches)) {
// $callable is a class:method string, so wrap it into a closure, retriving the class from Pimple if registered there
if ((! $this instanceof Container) && (! $this->container instanceof Container)) {
throw new \RuntimeException('Cannot resolve callable string');
}
$class = $matches[1];
$method = $matches[2];
$callable = function() use ($class, $method) {
static $obj = null;
if ($obj === null) {
if (isset($this[$class])) {
$obj = $this[$class];
} else {
if (!class_exists($class)) {
throw new \RuntimeException('Route callable class does not exist');
}
$obj = new $class;
}
if (!is_callable([$obj, $method])) {
throw new \RuntimeException('Route callable method does not exist');
}
}
return call_user_func_array(array($obj, $method), func_get_args());
};
}
return $callable;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment