Created
February 16, 2017 12:40
-
-
Save victorknust/9c0adfaff91dda842d8c69c1d64b68c6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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