Completed
Push — master ( 390e4e...b0ec12 )
by Taosikai
12:57
created

HttpTunnelServer::handlePublicConnection()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 23
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 23
rs 9.0856
cc 3
eloc 18
nc 1
nop 1
1
<?php
2
/**
3
 * Spike library
4
 * @author Tao <[email protected]>
5
 */
6
namespace Spike\Server\TunnelServer;
7
8
use GuzzleHttp\Psr7\Response;
9
use GuzzleHttp\Psr7;
10
use Spike\Parser\HttpHeaderParser;
11
12
class HttpTunnelServer extends TunnelServer
13
{
14
    /**
15
     * {@inheritdoc}
16
     */
17
    public function handlePublicConnection(PublicConnection $publicConnection)
18
    {
19
        $parser = new HttpHeaderParser();
20
        $publicConnection->getConnection()->on('data', function($data) use ($parser, $publicConnection){
21
            $parser->pushIncoming($data);
22
            $message = $parser->parseFirst();
23
            echo $message;
24
            if ($message) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $message of type null|string is loosely compared to true; this is ambiguous if the string can be empty. 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 string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
25
                $psrRequest = Psr7\parse_request($message);
26
                $host = $psrRequest->getUri()->getHost();
27
                if ($this->tunnel->supportProxyHost($host)) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Spike\Tunnel\TunnelInterface as the method supportProxyHost() does only exist in the following implementations of said interface: Spike\Tunnel\HttpTunnel.

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...
28
                    $this->tunnel->setProxyHost($host);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Spike\Tunnel\TunnelInterface as the method setProxyHost() does only exist in the following implementations of said interface: Spike\Tunnel\HttpTunnel.

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...
29
                    $httpMessage = $message . $parser->getRestData();
30
                    $publicConnection->setInitBuffer($httpMessage);
31
                    parent::handlePublicConnection($publicConnection);
32
                } else {
33
                    $body = sprintf('The host "%s" was not bound.', $host);
34
                    $response = $this->makeErrorResponse(404, $body);
35
                    $publicConnection->end(Psr7\str($response));
36
                }
37
            }
38
        });
39
    }
40
41
    /**
42
     * Make an error psr7 response
43
     * @param int $code
44
     * @param string $message
45
     * @return Response
46
     */
47
    protected function makeErrorResponse($code, $message)
48
    {
49
        $message = $message ?: 'Proxy error';
50
        return new Response($code, [
51
            'Content-Length' => strlen($message)
52
        ], $message);
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function closePublicConnection(PublicConnection $publicConnection, $message = null)
59
    {
60
        $publicConnection->end(Psr7\str($this->makeErrorResponse(500, $message ?: 'Timeout')));
61
    }
62
}