Completed
Push — master ( b2e200...1332b8 )
by Oscar
04:48
created

HtmlInjectorTrait   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
c 1
b 0
f 0
lcom 0
cbo 5
dl 0
loc 54
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A inject() 0 16 2
A isInjectable() 0 18 4
1
<?php
2
3
namespace Psr7Middlewares\Utils;
4
5
use Psr\Http\Message\ServerRequestInterface;
6
use Psr\Http\Message\ResponseInterface;
7
use Psr7Middlewares\Middleware\FormatNegotiator;
8
use Psr7Middlewares\Middleware;
9
10
/**
11
 * Utilities used by middlewares that inject html code in the responses.
12
 */
13
trait HtmlInjectorTrait
14
{
15
    /**
16
     * Inject some code just before any tag.
17
     * 
18
     * @param ResponseInterface $response
19
     * @param string            $code
20
     * @param string            $tag
21
     * 
22
     * @return ResponseInterface
23
     */
24
    private function inject(ResponseInterface $response, $code, $tag = 'body')
25
    {
26
        $html = (string) $response->getBody();
27
        $pos = strripos($html, "</{$tag}>");
28
29
        if ($pos === false) {
30
            $response->getBody()->write($code);
31
32
            return $response;
33
        }
34
35
        $body = Middleware::createStream();
36
        $body->write(substr($html, 0, $pos).$code.substr($html, $pos + 1));
37
38
        return $response->withBody($body);
39
    }
40
41
    /**
42
     * Check whether the request is valid to insert html in the response.
43
     * 
44
     * @param ServerRequestInterface $request
45
     * 
46
     * @return bool
47
     */
48
    private function isInjectable(ServerRequestInterface $request)
49
    {
50
        if (!Middleware::hasAttribute($request, FormatNegotiator::KEY)) {
51
            throw new RuntimeException('This middleware needs FormatNegotiator executed before');
52
        }
53
54
        //Must be html
55
        if (FormatNegotiator::getFormat($request) !== 'html') {
56
            return false;
57
        }
58
59
        //And not ajax
60
        if (strtolower($request->getHeaderLine('X-Requested-With')) === 'xmlhttprequest') {
61
            return false;
62
        }
63
64
        return true;
65
    }
66
}
67