|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Sajya\Server; |
| 6 | + |
| 7 | +use Closure; |
| 8 | +use Illuminate\Container\Container; |
| 9 | +use Illuminate\Routing\RouteBinding; |
| 10 | +use Illuminate\Support\Arr; |
| 11 | +use Illuminate\Support\Str; |
| 12 | +use Sajya\Server\Http\Request; |
| 13 | + |
| 14 | +class Binding |
| 15 | +{ |
| 16 | + /** |
| 17 | + * The IoC container instance. |
| 18 | + * |
| 19 | + * @var \Illuminate\Container\Container |
| 20 | + */ |
| 21 | + protected $container; |
| 22 | + |
| 23 | + /** |
| 24 | + * The registered route value binders. |
| 25 | + * |
| 26 | + * @var array |
| 27 | + */ |
| 28 | + protected $binders = []; |
| 29 | + |
| 30 | + /** |
| 31 | + * Application constructor. |
| 32 | + * |
| 33 | + * @param Container $container |
| 34 | + */ |
| 35 | + public function __construct(Container $container) |
| 36 | + { |
| 37 | + $this->container = $container; |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Register a model binder for a wildcard. |
| 42 | + * |
| 43 | + * @param string $key |
| 44 | + * @param string $class |
| 45 | + * @param \Closure|null $callback |
| 46 | + * |
| 47 | + * @return void |
| 48 | + */ |
| 49 | + public function model(string $key, string $class, Closure $callback = null) |
| 50 | + { |
| 51 | + $this->bind($key, RouteBinding::forModel($this->container, $class, $callback)); |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * Add a new route parameter binder. |
| 56 | + * |
| 57 | + * @param string $key |
| 58 | + * @param Closure|string $binder |
| 59 | + * |
| 60 | + * @return void |
| 61 | + */ |
| 62 | + public function bind(string $key, $binder) |
| 63 | + { |
| 64 | + $this->binders[$key] = RouteBinding::forCallback( |
| 65 | + $this->container, $binder |
| 66 | + ); |
| 67 | + } |
| 68 | + |
| 69 | + /** |
| 70 | + * @param Request $request |
| 71 | + * |
| 72 | + * @return array |
| 73 | + */ |
| 74 | + public function bindResolve(Request $request): array |
| 75 | + { |
| 76 | + $possibleBindings = Arr::dot($request->getParams()); |
| 77 | + |
| 78 | + return collect($possibleBindings) |
| 79 | + ->map(fn($value, string $key) => with($value, $this->binders[$key] ?? null)) |
| 80 | + ->mapWithKeys(function ($value, string $key) { |
| 81 | + $nameForArgument = (string)Str::of($key)->replace('.', '_')->camel(); |
| 82 | + |
| 83 | + return [$nameForArgument => $value]; |
| 84 | + }) |
| 85 | + ->toArray(); |
| 86 | + } |
| 87 | + |
| 88 | +} |
0 commit comments