Skip to content

Commit

Permalink
Added new request methods
Browse files Browse the repository at this point in the history
  • Loading branch information
eldadfux committed Jun 30, 2020
1 parent 3810789 commit e592b7b
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,44 @@ public function getIP(): string
return $this->getServer('HTTP_X_FORWARDED_FOR', $this->getServer('REMOTE_ADDR', '0.0.0.0'));
}

/**
* Get Protocol
*
* Returns request protocol.
* Support HTTP_X_FORWARDED_PROTO header usually return
* from different proxy servers or PHP default REQUEST_SCHEME
*
* @return string
*/
public function getProtocol(): string
{
return $this->getServer('HTTP_X_FORWARDED_PROTO', $this->getServer('REQUEST_SCHEME', 'https'));
}

/**
* Get Port
*
* Returns request port.
*
* @return string
*/
public function getPort(): string
{
return (string) \parse_url($this->getProtocol().'://'.$this->getServer('HTTP_HOST', ''), PHP_URL_PORT);
}

/**
* Get Hostname
*
* Returns request hostname.
*
* @return string
*/
public function getHostname(): string
{
return (string) \parse_url($this->getProtocol().'://'.$this->getServer('HTTP_HOST', ''), PHP_URL_HOST);
}

/**
* Get Method
*
Expand Down
50 changes: 50 additions & 0 deletions tests/RequestTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,56 @@ public function testGetCookie()
$this->assertEquals($this->request->getCookie('unknown', 'test'), 'test');
}

public function testGetProtocol()
{
// Mock
$_SERVER['HTTP_X_FORWARDED_PROTO'] = 'https';
$_SERVER['REQUEST_SCHEME'] = 'http';

// Assertions
$this->assertEquals('https', $this->request->getProtocol());

$_SERVER['HTTP_X_FORWARDED_PROTO'] = null;
$_SERVER['REQUEST_SCHEME'] = 'http';

// Assertions
$this->assertEquals('http', $this->request->getProtocol());
}

public function testGetPort()
{
// Mock
$_SERVER['HTTP_X_FORWARDED_PROTO'] = 'https';
$_SERVER['HTTP_HOST'] = 'localhost:8080';

// Assertions
$this->assertEquals('8080', $this->request->getPort());

// Mock
$_SERVER['HTTP_X_FORWARDED_PROTO'] = 'https';
$_SERVER['HTTP_HOST'] = 'localhost';

// Assertions
$this->assertEquals('', $this->request->getPort());
}

public function testGetHostname()
{
// Mock
$_SERVER['HTTP_X_FORWARDED_PROTO'] = 'https';
$_SERVER['HTTP_HOST'] = 'localhost:8080';

// Assertions
$this->assertEquals('localhost', $this->request->getHostname());

// Mock
$_SERVER['HTTP_X_FORWARDED_PROTO'] = 'https';
$_SERVER['HTTP_HOST'] = 'localhost';

// Assertions
$this->assertEquals('localhost', $this->request->getHostname());
}

/* public function testGetHeader()
{
// Assertions
Expand Down

0 comments on commit e592b7b

Please sign in to comment.