Completed
Push — master ( 95a87e...ea825e )
by Colin
10:28 queued 08:49
created

CloudToButtMiddleware   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
lcom 0
cbo 3
dl 0
loc 37
ccs 20
cts 20
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
C __invoke() 0 29 7
A changeCloudToButt() 0 4 1
1
<?php
2
3
namespace ColinODell\CloudToButt;
4
5
use function GuzzleHttp\Psr7\stream_for;
6
use Psr\Http\Message\ResponseInterface;
7
use Psr\Http\Message\ServerRequestInterface;
8
9
class CloudToButtMiddleware
10
{
11 2
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
12
    {
13
        /** @var ResponseInterface $response */
14 2
        $response = $next($request);
15 2
        $body = $response->getBody();
16
17 2
        if ($body->isSeekable()) {
18 1
            $body->rewind();
19 1
        }
20
21 2
        if (!$body->isSeekable() || $body->tell() !== 0) {
22 1
            $content = $this->changeCloudToButt($body);
23
24 1
            return $response->withBody(stream_for($content));
25
        }
26
27 1
        $newBody = stream_for(null);
28
29 1
        while (!$body->eof()) {
30 1
            $content = $body->read(4096);
31 1
            while (!$body->eof() && substr($content, -1) !== ' ') {
32 1
                $content .= $body->read(1);
33 1
            }
34
35 1
            $newBody->write($this->changeCloudToButt($content));
36 1
        }
37
38 1
        return $response->withBody($newBody);
39
    }
40
41 2
    private function changeCloudToButt($originalContent)
42
    {
43 2
        return strtr((string) $originalContent, ['Cloud' => 'Butt', 'cloud' => 'butt']);
44
    }
45
}
46