Created
March 27, 2016 10:47
-
-
Save webkonstantin/bdc8285b61be5a8e064d 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 App\Http\Middleware; | |
use Closure; | |
use ReflectionMethod; | |
use ReflectionFunction; | |
use Illuminate\Database\Eloquent\Model; | |
class SubstituteImplicitBindings | |
{ | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next) | |
{ | |
$routeInfo = $request->route(); | |
$parameters = $routeInfo[2]; | |
$signatureParameters = $this->signatureParameters($routeInfo[1], Model::class); | |
foreach ($signatureParameters as $parameter) { | |
$class = $parameter->getClass(); | |
if (array_key_exists($parameter->name, $parameters)) { | |
$method = $parameter->isDefaultValueAvailable() ? 'first' : 'firstOrFail'; | |
$model = $class->newInstance(); | |
$routeInfo[2][$parameter->name] = $model->where( | |
$model->getRouteKeyName(), $parameters[$parameter->name] | |
)->{$method}(); | |
} | |
} | |
$request->setRouteResolver(function () use ($routeInfo) { | |
return $routeInfo; | |
}); | |
return $next($request); | |
} | |
private function signatureParameters($action, $subClass = null) | |
{ | |
if (isset($action['uses'])) { | |
list($class, $method) = explode('@', $action['uses']); | |
$parameters = (new ReflectionMethod($class, $method))->getParameters(); | |
} else { | |
$parameters = (new ReflectionFunction($action[0]))->getParameters(); | |
} | |
return is_null($subClass) ? $parameters : array_filter($parameters, function ($p) use ($subClass) { | |
return $p->getClass() && $p->getClass()->isSubclassOf($subClass); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Check out this package Lumen Route Binding
It requires :
It supports Explicit binding :
And Implicit binding :
And Composite binding : (bind more than one wildcard together, In situations like
posts\{post}\comments\{comment}
you will be able to bind it to a callable that will resolve thePost
and theComment
related to the post)Also can work with other classes like
Repositories
:Can use a custom method on the repository :
Where in the repository class you can do :