HtmlInjectorTrait   A
last analyzed

Complexity

Total Complexity 2

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 0
Metric Value
wmc 2
lcom 0
cbo 3
dl 0
loc 30
rs 10
c 0
b 0
f 0

1 Method

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