RebindRouterContainer::handle()   A
last analyzed

Complexity

Conditions 6
Paths 3

Size

Total Lines 34
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 19
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 34
rs 9.0111
1
<?php
2
3
namespace SwooleTW\Http\Server\Resetters;
4
5
use Illuminate\Contracts\Container\Container;
6
use SwooleTW\Http\Server\Sandbox;
7
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
8
9
class RebindRouterContainer implements ResetterContract
10
{
11
    /**
12
     * @var \Illuminate\Contracts\Container\Container
13
     */
14
    protected $container;
15
16
    /**
17
     * @var mixed
18
     */
19
    protected $routes;
20
21
    /**
22
     * "handle" function for resetting app.
23
     *
24
     * @param \Illuminate\Contracts\Container\Container $app
25
     * @param \SwooleTW\Http\Server\Sandbox $sandbox
26
     *
27
     * @return \Illuminate\Contracts\Container\Container
28
     */
29
    public function handle(Container $app, Sandbox $sandbox)
30
    {
31
        if ($sandbox->isLaravel()) {
32
            $router = $app->make('router');
33
            $request = $sandbox->getRequest();
34
            $closure = function () use ($app, $request) {
35
                $this->container = $app;
36
                if (is_null($request)) {
37
                    return;
38
                }
39
                try {
40
                    /** @var mixed $route */
41
                    $route = $this->routes->match($request);
42
                    // clear resolved controller
43
                    if (property_exists($route, 'container')) {
44
                        $route->controller = null;
45
                    }
46
                    // rebind matched route's container
47
                    $route->setContainer($app);
48
                } catch (NotFoundHttpException $e) {
49
                    // do nothing
50
                }
51
            };
52
53
            $resetRouter = $closure->bindTo($router, $router);
54
            $resetRouter();
55
        } else {
56
            // lumen router only exists after lumen 5.5
57
            if (property_exists($app, 'router')) {
58
                $app->router->app = $app;
59
            }
60
        }
61
62
        return $app;
63
    }
64
}
65