Completed
Push — master ( 206c33...9e77c2 )
by Oscar
05:44
created

FormTrait::isPost()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
rs 8.8571
cc 6
eloc 9
nc 6
nop 1
1
<?php
2
3
namespace Psr7Middlewares\Utils;
4
5
use Psr\Http\Message\RequestInterface;
6
use Psr\Http\Message\ResponseInterface;
7
use Psr7Middlewares\Middleware;
8
9
/**
10
 * Utilities used by middlewares that manipulates forms.
11
 */
12
trait FormTrait
13
{
14
    /**
15
     * Insert content into all POST forms.
16
     * 
17
     * @param ResponseInterface $response
18
     * @param string            $input
19
     * 
20
     * @return ResponseInterface
21
     */
22
    protected function insertIntoPostForms(ResponseInterface $response, $input)
23
    {
24
        $html = (string) $response->getBody();
25
26
        $html = preg_replace_callback(
27
            '/(<form\s[^>]*method="?POST"?[^>]*>)/i',
28
            function ($match) use ($input) {
29
                return $match[0].$input;
30
            },
31
            $html,
32
            -1,
33
            $count
34
        );
35
36
        if ($count) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $count of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
37
            $body = Middleware::createStream();
38
            $body->write($html);
39
40
            return $response->withBody($body);
41
        }
42
43
        return $response;
44
    }
45
46
    /**
47
     * Check whether the request is post (or any similar method).
48
     * 
49
     * @param RequestInterface $request
50
     * 
51
     * @return bool
52
     */
53
    protected function isPost(RequestInterface $request)
54
    {
55
        switch (strtoupper($request->getMethod())) {
56
            case 'GET':
57
            case 'HEAD':
58
            case 'CONNECT':
59
            case 'TRACE':
60
            case 'OPTIONS':
61
                return false;
62
        }
63
64
        return true;
65
    }
66
}
67