Skip to content
This repository has been archived by the owner on Dec 16, 2024. It is now read-only.

Commit

Permalink
handle file_get_content errors
Browse files Browse the repository at this point in the history
close #15
  • Loading branch information
giansalex committed May 18, 2019
1 parent f1e033c commit 6ff9239
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 7 deletions.
21 changes: 14 additions & 7 deletions src/Peru/Http/ContextClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,8 @@ class ContextClient implements ClientInterface
public function get(string $url, array $headers = [])
{
$ctx = $this->getContext('GET', null, $headers);
$response = file_get_contents($url, false, $ctx);
$this->saveCookies($http_response_header);

return $response;
return $this->getResponseAndSaveCookies($url, $ctx);
}

/**
Expand All @@ -63,10 +61,8 @@ public function post(string $url, $data, array $headers = [])
}

$ctx = $this->getContext('POST', $data, $headers);
$response = file_get_contents($url, false, $ctx);
$this->saveCookies($http_response_header);

return $response;
return $this->getResponseAndSaveCookies($url, $ctx);
}

/**
Expand All @@ -82,7 +78,7 @@ private function getContext(string $method, $data, array $headers)
'http' => [
'header' => $this->join(': ', $headers),
'method' => $method,
'content' => $this->getRawData($data),
'content' => $this->getRawData($data)
],
];

Expand Down Expand Up @@ -128,4 +124,15 @@ private function join(string $glue, array $items, string $end = "\r\n"): ?string

return $append;
}

private function getResponseAndSaveCookies(string $url, $ctx)
{
$response = @file_get_contents($url, false, $ctx);

if (isset($http_response_header)) {
$this->saveCookies($http_response_header);
}

return $response;
}
}
20 changes: 20 additions & 0 deletions tests/Peru/Http/ContextClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,24 @@ public function testPost()

$this->assertTrue(isset($obj->form->value));
}

public function testNotFoundUrl()
{
$client = new ContextClient();
$result = $client->get('http://httpbin.org/get33');
$error = error_get_last();

$this->assertFalse($result);
$this->assertStringContainsString('404 NOT FOUND', $error['message']);
}

public function testNotResolveDomain()
{
$client = new ContextClient();
$result = $client->get('http://http323bin.org');
$error = error_get_last();

$this->assertFalse($result);
$this->assertStringContainsString('php_network_getaddresses', $error['message']);
}
}

0 comments on commit 6ff9239

Please sign in to comment.