Completed
Push — master ( daed8c...cf758d )
by Damian
08:03
created

HTTPApplication::callMiddleware()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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