Skip to content

Commit

Permalink
:octocat: +URLExtractor::extract()
Browse files Browse the repository at this point in the history
  • Loading branch information
codemasher committed Dec 9, 2022
1 parent 9250208 commit e6a0946
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
32 changes: 31 additions & 1 deletion src/Psr18/URLExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,11 @@

use chillerlan\HTTP\Psr17\RequestFactory;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\{RequestFactoryInterface, RequestInterface, ResponseInterface};
use Psr\Http\Message\{RequestFactoryInterface, RequestInterface, ResponseInterface, UriInterface};

use function array_key_last;
use function array_pop;
use function count;
use function in_array;

/**
Expand Down Expand Up @@ -58,6 +61,33 @@ public function sendRequest(RequestInterface $request):ResponseInterface{
return $response;
}

/**
* extract the given URL and return the last valid location header
*/
public function extract(UriInterface|string $shortURL):?string{
$request = $this->requestFactory->createRequest('GET', $shortURL);
$response = $this->sendRequest($request);

if($response->getStatusCode() !== 200 || empty($this->responses)){
return null;
}

$count = count($this->responses) - 2;

while($count >= 0){

$url = $this->responses[$count]?->getHeaderLine('location');

if(!empty($url)){
return $url;
}

$count--;
}

return null;
}

/**
* @return \Psr\Http\Message\ResponseInterface[]
*/
Expand Down
6 changes: 6 additions & 0 deletions tests/Psr18/URLExtractorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,10 @@ public function testSendRequest():void{

}

public function testExtract():void{
$url = $this->http->extract('https://t.co/ZSS6nVOcVp');

$this::assertSame('https://api.guildwars2.com/v2/build', $url);
}

}

0 comments on commit e6a0946

Please sign in to comment.