Completed
Push — master ( c2f224...2bc1cd )
by Oscar
03:33
created

HtmlInjectorTrait::isInjectable()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 18
rs 9.2
cc 4
eloc 8
nc 4
nop 1
1
<?php
2
3
namespace Psr7Middlewares\Utils;
4
5
use Psr\Http\Message\ResponseInterface;
6
use Psr7Middlewares\Middleware;
7
8
/**
9
 * Utilities used by middlewares that inject html code in the responses.
10
 */
11
trait HtmlInjectorTrait
12
{
13
    /**
14
     * Inject some code just before any tag.
15
     * 
16
     * @param ResponseInterface $response
17
     * @param string            $code
18
     * @param string            $tag
19
     * 
20
     * @return ResponseInterface
21
     */
22
    private function inject(ResponseInterface $response, $code, $tag = 'body')
23
    {
24
        $html = (string) $response->getBody();
25
        $pos = strripos($html, "</{$tag}>");
26
27
        if ($pos === false) {
28
            $response->getBody()->write($code);
29
30
            return $response;
31
        }
32
33
        $body = Middleware::createStream();
34
        $body->write(substr($html, 0, $pos).$code.substr($html, $pos));
35
36
        return $response->withBody($body);
37
    }
38
}
39