Completed
Push — dev ( b1013d...c10904 )
by Jonathan
11s queued 10s
created

HttpRequestTest::testInputStream()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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