-
-
Notifications
You must be signed in to change notification settings - Fork 76
WIP: status-codes (fixes #161) #164
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
spekulatius
wants to merge
17
commits into
spekulatius:master
Choose a base branch
from
eposjk:status-codes
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 6 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
fc815e6
Providing status codes (fixes #161)
spekulatius 5cb469c
Hardening call
spekulatius c17eeeb
Adding tests
spekulatius 5481b55
Adding further tests for status code
spekulatius 87d48c6
Simplifying methods for status codes
spekulatius 6d7fd5a
first try: helper functions for handling response status
eposjk 83ab28a
fixed coding style
eposjk 25a2379
remember request properties from last go() request
eposjk d67c26d
bugfix for retryAt()
eposjk fa1ca44
enhanced status code tests
eposjk 646871d
removed isClientError() / isServerError() / isForbidden() / isNotFound()
eposjk fd9006b
8bc4c11
moved demo.php to examples/CheckStatus.php
eposjk 2d7ce52
fixed retryAt() docblock
eposjk 6bee2d7
keep state in GoutteClient
eposjk d5d98bc
return status 499 for timeout and 0 for network errors instead of thr…
eposjk c881f73
define status 0 Network Error (e.g. caused by invalid domains) as per…
eposjk File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
<?php | ||
|
||
require __DIR__ . '/vendor/autoload.php'; | ||
|
||
// ENTER YOUR URL HERE: | ||
$url = 'http://github.com/spekulatius/PHPScraper'; | ||
echo 'requesting ', $url, "\n"; | ||
$web = new \Spekulatius\PHPScraper\PHPScraper; | ||
$web->go($url); | ||
//var_dump($web->client); | ||
|
||
if($web->currentUrl !== $url) | ||
echo 'redirected to ', $web->currentUrl, "\n"; | ||
echo 'status code ', $web->statusCode, "\n"; | ||
|
||
|
||
|
||
if($web->isGone) { | ||
echo "delete/deactivate record from database\n"; | ||
} else { | ||
if($web->permanentRedirectUrl !== '') { | ||
echo 'url changed - update url in database to ', $web->permanentRedirectUrl, "\n"; | ||
} | ||
|
||
$retryAt = $web->retryAt; | ||
if($web->isSuccess) { | ||
echo "got data successfully - process it now...\n"; | ||
} elseif($web->isTemporaryResult) { | ||
echo "temporary error\n"; | ||
if(!$retryAt) | ||
$retryAt = time() + 15*60; // FIXME: use longer times if we get the same status code multiple times | ||
} else { | ||
echo "might be a permanent error - but who knows if the server changes its mind (e.g. if the result is caused by some administrative work on the server) --> try several times before considering it final\n"; | ||
if(!$retryAt) | ||
$retryAt = time() + 24*60*60; // FIXME: use longer times if we get the same status code multiple times OR consider it somewhen really permanent and delete/deactivate record from database | ||
} | ||
if($retryAt) | ||
echo 'retry at ', date('Y-m-d H:i:s', $retryAt), "\n"; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
<?php | ||
|
||
namespace Spekulatius\PHPScraper; | ||
|
||
use Goutte\Client; | ||
use Symfony\Component\DomCrawler\Crawler; | ||
|
||
/** | ||
* Extended Goutte\Client with PHPScraper specific methods | ||
*/ | ||
|
||
class GoutteClient extends Client | ||
{ | ||
/** | ||
* Was a temporary redirect involved in loading this request? | ||
* | ||
* @var bool | ||
*/ | ||
public $usesTemporaryRedirect = false; | ||
|
||
/** | ||
* Should subsequent requests go to a different URL? | ||
* | ||
* @var string | ||
*/ | ||
public $permanentRedirectUrl = null; | ||
|
||
/** | ||
* Which is the earliest moment to retry the request because of an outdated redirect? (unix timestamp) | ||
* | ||
* @var int | ||
*/ | ||
protected $retryRedirectAt = PHP_INT_MAX; | ||
|
||
/** | ||
* Which is the earliest moment to retry the request because of a failed request? (unix timestamp) | ||
* | ||
* @var int | ||
*/ | ||
protected $retryFailureAt = 0; | ||
|
||
/** | ||
* Remember permanent redirect url and detect if the redirect chain contains temporary redirects | ||
* | ||
* @return Crawler | ||
*/ | ||
public function followRedirect(): Crawler | ||
spekulatius marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
$status = $this->internalResponse->getStatusCode(); | ||
if($status === 200 /* META REFRESH */ || $status === 301 /* Moved Permanently */ || $status === 308 /* Permanent Redirect */) { | ||
if(!$this->usesTemporaryRedirect && empty($this->internalResponse->getHeader('Retry-After'))) | ||
$this->permanentRedirectUrl = $this->redirect; | ||
} else { // $status === 300 /* Multiple Choices */ || $status === 302 /* Found */ || $status === 303 /* See Other */ || $status === 307 /* Temporary Redirect */ | ||
$this->usesTemporaryRedirect = true; | ||
} | ||
// 300 Multiple Choices might also be handled as permanent redirect | ||
spekulatius marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// META REFRESH might also be handled as temporary redirect if the delay is > 1s | ||
return parent::followRedirect(); | ||
} | ||
|
||
/** | ||
* Evaluate the Retry-After header | ||
* | ||
* see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After | ||
* | ||
* @return Response | ||
*/ | ||
protected function filterResponse(object $response) | ||
{ | ||
$retryAfterHeaders = $response->getHeader('Retry-After', false); | ||
if(!empty($retryAfterHeaders)) { | ||
$status = $this->internalResponse->getStatusCode(); | ||
foreach($retryAfterHeaders as $retryAfter) { | ||
if(is_numeric($retryAfter)) | ||
$retryAt = time() + $retryAfter; | ||
else | ||
$retryAt = strtotime($retryAfter); | ||
if($status >= 400) { // usually 429 Too Many Request or 503 Service Unavailable | ||
if($this->retryFailureAt < $retryAt) | ||
$this->retryFailureAt = $retryAt; | ||
} elseif($status >= 300) { | ||
if($this->retryRedirectAt > $retryAt) | ||
$this->retryRedirectAt = $retryAt; | ||
} | ||
} | ||
} | ||
return parent::filterResponse($response); | ||
} | ||
|
||
/** | ||
* Calculate the earliest moment to retry the request | ||
* | ||
* @return Response | ||
spekulatius marked this conversation as resolved.
Show resolved
Hide resolved
|
||
*/ | ||
public function retryAt(): int { | ||
spekulatius marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if($this->retryFailureAt) | ||
return $this->retryFailureAt; | ||
if($this->retryRedirectAt < PHP_INT_MAX) | ||
return $this->retryRedirectAt; | ||
return 0; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
<?php | ||
|
||
namespace Spekulatius\PHPScraper\Tests; | ||
|
||
class StatusCodeTest extends \PHPUnit\Framework\TestCase | ||
{ | ||
/** | ||
* @test | ||
*/ | ||
public function testAccessErrorBeforeNavigation() | ||
{ | ||
$web = new \Spekulatius\PHPScraper\PHPScraper; | ||
|
||
$this->expectException(\Exception::class); | ||
$this->expectExceptionMessage('You can not access the status code before your first navigation using `go`.'); | ||
|
||
$web->statusCode; | ||
} | ||
|
||
/** | ||
* @test | ||
*/ | ||
public function testOk() | ||
{ | ||
$web = new \Spekulatius\PHPScraper\PHPScraper; | ||
|
||
// Navigate to the test page: This redirects to phpscraper.de | ||
$web->go('https://phpscraper.de'); | ||
|
||
// Check the status itself. | ||
$this->assertSame(200, $web->statusCode); | ||
|
||
// Check the detailed states. | ||
$this->assertTrue($web->isSuccess); | ||
$this->assertFalse($web->isClientError); | ||
$this->assertFalse($web->isServerError); | ||
|
||
// Assert access-helpers | ||
$this->assertFalse($web->isForbidden); | ||
$this->assertFalse($web->isNotFound); | ||
} | ||
|
||
/** | ||
* @test | ||
*/ | ||
public function testNotFound() | ||
{ | ||
$web = new \Spekulatius\PHPScraper\PHPScraper; | ||
|
||
// Navigate to the test page which doesn't exist. | ||
$web->go('https://test-pages.phpscraper.de/page-does-not-exist.html'); | ||
|
||
// Check the status itself. | ||
$this->assertSame(404, $web->statusCode); | ||
|
||
// Check the detailed states. | ||
$this->assertFalse($web->isSuccess); | ||
$this->assertTrue($web->isClientError); | ||
$this->assertFalse($web->isServerError); | ||
|
||
// Assert access-helpers | ||
$this->assertFalse($web->isForbidden); | ||
$this->assertTrue($web->isNotFound); | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.