From 4e30aba81829f4f0e1f9d44ae4484ac7f3358097 Mon Sep 17 00:00:00 2001 From: Arnaud Le Blanc Date: Tue, 2 Jun 2015 16:04:16 +0200 Subject: [PATCH] Added support for using auth informations from URL --- src/RequestData.php | 25 +++++++++++++++++++++++++ tests/RequestDataTest.php | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 tests/RequestDataTest.php diff --git a/src/RequestData.php b/src/RequestData.php index 7073ce5..d2a3e1f 100644 --- a/src/RequestData.php +++ b/src/RequestData.php @@ -21,6 +21,7 @@ private function mergeDefaultheaders(array $headers) { $port = ($this->getDefaultPort() === $this->getPort()) ? '' : ":{$this->getPort()}"; $connectionHeaders = ('1.1' === $this->protocolVersion) ? array('Connection' => 'close') : array(); + $authHeaders = $this->getAuthHeaders(); return array_merge( array( @@ -28,6 +29,7 @@ private function mergeDefaultheaders(array $headers) 'User-Agent' => 'React/alpha', ), $connectionHeaders, + $authHeaders, $headers ); } @@ -78,4 +80,27 @@ public function __toString() return $data; } + + private function getUrlUserPass() + { + $components = parse_url($this->url); + + if (isset($components['user'])) { + return array( + 'user' => $components['user'], + 'pass' => isset($components['pass']) ? $components['pass'] : null, + ); + } + } + + private function getAuthHeaders() + { + if (null !== $auth = $this->getUrlUserPass()) { + return array( + 'Authorization' => 'Basic ' . base64_encode($auth['user'].':'.$auth['pass']), + ); + } + + return array(); + } } diff --git a/tests/RequestDataTest.php b/tests/RequestDataTest.php new file mode 100644 index 0000000..c6a3e58 --- /dev/null +++ b/tests/RequestDataTest.php @@ -0,0 +1,37 @@ +assertSame($expected, $requestData->__toString()); + } + + /** @test */ + public function toStringUsesUserPassFromURL() + { + $requestData = new RequestData('GET', 'http://john:dummy@www.example.com'); + + $expected = "GET / HTTP/1.1\r\n" . + "Host: www.example.com\r\n" . + "User-Agent: React/alpha\r\n" . + "Connection: close\r\n" . + "Authorization: Basic am9objpkdW1teQ==\r\n" . + "\r\n"; + + $this->assertSame($expected, $requestData->__toString()); + } +}