From e592b7bdea5eeb48a3bf7ae18bc6d3e622e54cf3 Mon Sep 17 00:00:00 2001 From: Eldad Fux Date: Tue, 30 Jun 2020 12:43:41 +0300 Subject: [PATCH] Added new request methods --- src/Request.php | 38 ++++++++++++++++++++++++++++++++ tests/RequestTest.php | 50 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+) diff --git a/src/Request.php b/src/Request.php index 8a04e97b..ad51e97d 100755 --- a/src/Request.php +++ b/src/Request.php @@ -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 * diff --git a/tests/RequestTest.php b/tests/RequestTest.php index cefd8702..523d569e 100755 --- a/tests/RequestTest.php +++ b/tests/RequestTest.php @@ -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