Skip to content

Commit a9db690

Browse files
authored
Merge pull request #102 from Sammyjo20/feature/dom-response-method
Feature | Added new dom() method for parsing HTML and XML
2 parents ab3797e + d13f618 commit a9db690

File tree

3 files changed

+33
-1
lines changed

3 files changed

+33
-1
lines changed

composer.json

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,11 @@
2828
"friendsofphp/php-cs-fixer": "^3.5",
2929
"league/flysystem": "^3.0",
3030
"pestphp/pest": "^1.21",
31-
"spatie/ray": "^1.33"
31+
"spatie/ray": "^1.33",
32+
"symfony/dom-crawler": "^6.0"
33+
},
34+
"suggest": {
35+
"symfony/dom-crawler": "Required for the SaloonResponse dom() method to parse HTML and XML."
3236
},
3337
"minimum-stability": "stable",
3438
"autoload": {

src/Http/SaloonResponse.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use Illuminate\Support\Collection;
99
use Psr\Http\Message\StreamInterface;
1010
use Illuminate\Support\Traits\Macroable;
11+
use Symfony\Component\DomCrawler\Crawler;
1112
use GuzzleHttp\Exception\RequestException;
1213
use Sammyjo20\Saloon\Exceptions\SaloonRequestException;
1314

@@ -200,6 +201,19 @@ public function dto(): mixed
200201
return $this->dto;
201202
}
202203

204+
/**
205+
* Parse the HTML or XML body into a Symfony DomCrawler instance.
206+
*
207+
* Requires Symfony Crawler (composer require symfony/dom-crawler)
208+
* @see https://symfony.com/doc/current/components/dom_crawler.html
209+
*
210+
* @return Crawler
211+
*/
212+
public function dom(): Crawler
213+
{
214+
return new Crawler($this->body());
215+
}
216+
203217
/**
204218
* Get a header from the response.
205219
*

tests/Unit/SaloonResponseTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
use Illuminate\Support\Collection;
55
use Sammyjo20\Saloon\Http\MockResponse;
66
use Sammyjo20\Saloon\Clients\MockClient;
7+
use Symfony\Component\DomCrawler\Crawler;
78
use Sammyjo20\Saloon\Exceptions\SaloonRequestException;
89
use Sammyjo20\Saloon\Tests\Fixtures\Requests\UserRequest;
910

@@ -197,3 +198,16 @@
197198

198199
expect($simpleXml)->toBeInstanceOf(SimpleXMLElement::class);
199200
});
201+
202+
test('the dom method will return a crawler instance', function () {
203+
$dom = '<p>Howdy <i>Partner</i></p>';
204+
205+
$mockClient = new MockClient([
206+
new MockResponse($dom, 200),
207+
]);
208+
209+
$response = (new UserRequest())->send($mockClient);
210+
211+
expect($response->dom())->toBeInstanceOf(Crawler::class);
212+
expect($response->dom())->toEqual(new Crawler($dom));
213+
});

0 commit comments

Comments
 (0)