diff --git a/src/UsesGoutte.php b/src/UsesGoutte.php index 5f9be19..8d73430 100644 --- a/src/UsesGoutte.php +++ b/src/UsesGoutte.php @@ -133,4 +133,38 @@ public function clickLink($titleOrUrl): self return $this; } + + public function statusCode(): int + { + if ($this->currentPage === null) { + throw new \Exception('You can not access the status code before your first navigation using `go`.'); + } + + return $this->client->getResponse()->getStatusCode(); + } + + public function isSuccess(): bool + { + return $this->statusCode() >= 200 && $this->statusCode() <= 299; + } + + public function isClientError(): bool + { + return $this->statusCode() >= 400 && $this->statusCode() <= 499; + } + + public function isServerError(): bool + { + return $this->statusCode() >= 500 && $this->statusCode() <= 599; + } + + public function isForbidden(): bool + { + return $this->statusCode() === 403; + } + + public function isNotFound(): bool + { + return $this->statusCode() === 404; + } } \ No newline at end of file diff --git a/tests/NotFoundTest.php b/tests/NotFoundTest.php deleted file mode 100644 index 1bd1ce1..0000000 --- a/tests/NotFoundTest.php +++ /dev/null @@ -1,22 +0,0 @@ -go('https://test-pages.phpscraper.de/page-does-not-exist.html'); - - // The built-in server returns this string. - $this->assertSame('Page Not Found', $web->title); - } -} diff --git a/tests/StatusCodeTest.php b/tests/StatusCodeTest.php new file mode 100644 index 0000000..4f09af8 --- /dev/null +++ b/tests/StatusCodeTest.php @@ -0,0 +1,65 @@ +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); + } +}