Completed
Push — director-middleware ( 408832...334a87 )
by Sam
08:23
created

HTTPApplication::getMiddlewares()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\Control;
4
5
use SilverStripe\Core\Application;
6
use SilverStripe\Core\Injector\Injector;
7
use SilverStripe\Control\HTTPMiddleware;
8
use SilverStripe\Core\Kernel;
9
10
/**
11
 * Invokes the HTTP application within an ErrorControlChain
12
 */
13
class HTTPApplication implements Application
14
{
15
16
    use HTTPMiddlewareAware;
17
18
    /**
19
     * @var Kernel
20
     */
21
    protected $kernel;
22
23
    public function __construct(Kernel $kernel)
24
    {
25
        $this->kernel = $kernel;
26
    }
27
28
    /**
29
     * Get the kernel for this application
30
     *
31
     * @return Kernel
32
     */
33
    public function getKernel()
34
    {
35
        return $this->kernel;
36
    }
37
38
    /**
39
     * Handle the given HTTP request
40
     *
41
     * @param HTTPRequest $request
42
     * @return HTTPResponse
43
     */
44
    public function handle(HTTPRequest $request)
45
    {
46
        $flush = $request->getVar('flush') || strpos($request->getURL(), 'dev/build') === 0;
47
48
        // Ensure boot is invoked
49
        return $this->execute($request, function (HTTPRequest $request) {
50
            return Injector::inst()->get(Director::class)->handleRequest($request);
51
        }, $flush);
52
    }
53
54
    /**
55
     * Safely boot the application and execute the given main action
56
     *
57
     * @param HTTPRequest $request
58
     * @param callable $callback
59
     * @param bool $flush
60
     * @return HTTPResponse
61
     */
62
    public function execute(HTTPRequest $request, callable $callback, $flush = false)
63
    {
64
        try {
65
            return $this->callMiddleware($request, function ($request) use ($callback, $flush) {
66
                // Pre-request boot
67
                $this->getKernel()->boot($flush);
68
                return call_user_func($callback, $request);
69
            });
70
        } catch (HTTPResponse_Exception $ex) {
71
            return $ex->getResponse();
72
        } finally {
73
            $this->getKernel()->shutdown();
74
        }
75
    }
76
}
77