Passed
Pull Request — master (#8)
by Robbie
03:27
created

CrazyEggMiddleware::setTagProvider()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\CrazyEgg;
4
5
use SilverStripe\Control\HTTPRequest;
6
use SilverStripe\Control\HTTPResponse;
7
use SilverStripe\Control\Middleware\HTTPMiddleware;
8
use SilverStripe\View\ViewableData;
9
10
class CrazyEggMiddleware implements HTTPMiddleware
11
{
12
    /**
13
     * @var bool
14
     */
15
    protected static $installed = false;
16
17
    /**
18
     * @var ViewableData
19
     */
20
    protected $tagProvider;
21
22
    /**
23
     * @param ViewableData $tagProvider
24
     */
25
    public function setTagProvider(ViewableData $tagProvider)
26
    {
27
        $this->tagProvider = $tagProvider;
28
    }
29
30
    public function process(HTTPRequest $request, callable $delegate)
31
    {
32
        /** @var HTTPResponse $response */
33
        $response = $delegate($request);
34
35
        $mime = $response->getHeader('Content-Type');
36
37
        if (!$mime || strpos($mime, 'text/html') !== false) {
38
            $tags = $this->tagProvider->forTemplate();
39
40
            if ($tags && !static::$installed) {
41
                $content = $response->getBody();
42
                $content = preg_replace("/(<\\/head[^>]*>)/i", $tags . "\\1", $content);
43
                $response->setBody($content);
44
45
                static::$installed = true;
46
            }
47
        }
48
49
        return $response;
50
    }
51
}
52