Completed
Push — master ( 1b2d0a...89ea1a )
by Oscar
03:00
created

FormTrait::autoInsert()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
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 manipulate forms.
10
 */
11
trait FormTrait
12
{
13
    private $autoInsert = false;
14
15
    /**
16
     * Configure if autoinsert or not the inputs automatically
17
     * 
18
     * @param bool $autoInsert
19
     * 
20
     * @return self
21
     */
22
    public function autoInsert($autoInsert = true)
23
    {
24
        $this->autoInsert = $autoInsert;
25
26
        return $this;
27
    }
28
29
    /**
30
     * Insert content into all POST forms.
31
     * 
32
     * @param ResponseInterface $response
33
     * @param callable          $replace
34
     * 
35
     * @return ResponseInterface
36
     */
37
    private function insertIntoPostForms(ResponseInterface $response, callable $replace)
38
    {
39
        $html = (string) $response->getBody();
40
        $html = preg_replace_callback('/(<form\s[^>]*method=["\']?POST["\']?[^>]*>)/i', $replace, $html, -1, $count);
41
42
        if (!empty($count)) {
43
            $body = Middleware::createStream();
44
            $body->write($html);
45
46
            return $response->withBody($body);
47
        }
48
49
        return $response;
50
    }
51
}
52