HttpRequestTest::testInputStream()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 18
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
namespace Vectorface\SnappyRouterTests\Request;
4
5
use PHPUnit\Framework\TestCase;
6
use Vectorface\SnappyRouter\Request\HttpRequest;
7
8
/**
9
 * Tests the HttpRequest class.
10
 * @copyright Copyright (c) 2014, VectorFace, Inc.
11
 * @author Dan Bruce <[email protected]>
12
 */
13
class HttpRequestTest extends TestCase
14
{
15
    /**
16
     * An overview of how to use the RPCRequest class.
17
     * @test
18
     */
19
    public function synopsis()
20
    {
21
        // instantiate the class
22
        $request = new HttpRequest('MyService', 'MyMethod', 'GET', 'php://memory');
23
24
        $this->assertEquals('GET', $request->getVerb());
25
        $this->assertEquals('POST', $request->setVerb('POST')->getVerb());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Vectorface\SnappyRouter\Request\RequestInterface as the method getVerb() does only exist in the following implementations of said interface: Vectorface\SnappyRouter\Request\HttpRequest, Vectorface\SnappyRouter\Request\JsonRpcRequest.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
26
27
        $queryData = array('id' => '1234');
28
        $this->assertSame(
29
            1234,
30
            $request->setQuery($queryData)->getQuery('id', 0, 'int')
0 ignored issues
show
Documentation introduced by
'int' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
31
        );
32
33
        $postData = array('username' => ' TEST_USER ');
34
        $this->assertEquals(
35
            'test_user',
36
            $request->setPost($postData)->getPost('username', '', array('trim', 'lower'))
37
        );
38
39
        $this->assertEquals(
40
            array('id' => '1234', 'username' => ' TEST_USER '),
41
            $request->getAllInput()
42
        );
43
    }
44
45
    /**
46
     * Tests successful input stream set and fetch cases
47
     */
48
    public function testInputStream()
49
    {
50
        $tempStream = fopen('php://memory', 'w');
51
        fwrite($tempStream, "test");
52
        rewind($tempStream);
53
54
        /* Mock a stream in memory */
55
        $request = new HttpRequest('TestService', 'TestMethod', 'GET', $tempStream);
56
        $this->assertEquals("test", $request->getBody());
57
        fclose($tempStream);
58
59
        /* Fetch previously stored value */
60
        $this->assertEquals("test", $request->getBody());
61
62
        /* Specify php://memory as a string */
63
        $request = new HttpRequest('TestService', 'TestMethod', 'GET', 'php://memory');
64
        $this->assertEquals("", $request->getBody());
65
    }
66
67
    /**
68
     * Tests the input stream functionality where the stream source is not a string or a stream
69
     * @expectedException Vectorface\SnappyRouter\Exception\InternalErrorException
70
     */
71
    public function testInputStreamIncorrectTypeFailure()
72
    {
73
        $request = new HttpRequest('TestService', 'TestMethod', 'GET', 1);
74
        $request->getBody();
75
    }
76
77
    /**
78
     * Tests the input stream functionality where the stream source does not exist
79
     * @expectedException Vectorface\SnappyRouter\Exception\InternalErrorException
80
     */
81
    public function testInputStreamIncorrectFileFailure()
82
    {
83
        $request = new HttpRequest('TestService', 'TestMethod', 'GET', 'file');
84
        $request->getBody();
85
    }
86
87
    /**
88
     * Tests the various filters.
89
     * @dataProvider filtersProvider
90
     */
91
    public function testInputFilters($expected, $value, $filters)
92
    {
93
        $request = new HttpRequest('TestService', 'TestMethod', 'GET', 'php://input');
94
        $request->setQuery(array('key' => $value));
95
        $this->assertSame($expected, $request->getQuery('key', null, $filters));
96
    }
97
98
    /**
99
     * The data provider for testInputFilters.
100
     */
101
    public function filtersProvider()
102
    {
103
        return array(
104
            array(
105
                1234,
106
                '1234',
107
                'int'
108
            ),
109
            array(
110
                1234.5,
111
                ' 1234.5   ',
112
                'float'
113
            ),
114
            array(
115
                'hello world',
116
                "\t".'hello world  '.PHP_EOL,
117
                'trim'
118
            ),
119
            array(
120
                'hello world',
121
                'HELLO WORLD',
122
                'lower'
123
            ),
124
            array(
125
                'HELLO WORLD',
126
                'hello world',
127
                'upper'
128
            ),
129
            array(
130
                'test'.PHP_EOL.'string',
131
                'test'.PHP_EOL.'  '.PHP_EOL.PHP_EOL.'string',
132
                'squeeze'
133
            ),
134
        );
135
    }
136
}
137