Completed
Push — master ( 7dba56...6875ae )
by Oscar
10:21
created

FormTrait   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 8
c 2
b 0
f 0
lcom 0
cbo 4
dl 0
loc 55
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A insertIntoPostForms() 0 23 2
B isPost() 0 13 6
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
    private 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
    private 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