Passed
Push — main ( 0a94ad...30f64e )
by smiley
09:47
created

URLExtractor::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 3
rs 10
1
<?php
2
/**
3
 * Class URLExtractor
4
 *
5
 * @created      15.08.2019
6
 * @author       smiley <[email protected]>
7
 * @copyright    2019 smiley
8
 * @license      MIT
9
 */
10
11
namespace chillerlan\HTTP\Psr18;
12
13
use chillerlan\HTTP\Psr17\RequestFactory;
14
use chillerlan\HTTP\Psr7\Request;
15
use Psr\Http\Client\ClientInterface;
16
use Psr\Http\Message\{RequestFactoryInterface, RequestInterface, ResponseInterface};
17
18
use function in_array;
19
20
/**
21
 * A client that follows redirects until it reaches a non-30x response, e.g. to extract shortened URLs
22
 *
23
 * The given HTTP client needs to be set up accordingly:
24
 *
25
 *   - CURLOPT_FOLLOWLOCATION  must be set to false so that we can intercept the 30x responses
26
 *   - CURLOPT_MAXREDIRS       should be set to a value > 1
27
 */
28
class URLExtractor implements ClientInterface{
29
30
	/** @var \Psr\Http\Message\ResponseInterface[] */
31
	protected array $responses = [];
32
33
	protected ClientInterface $http;
34
35
	protected RequestFactoryInterface $requestFactory;
36
37
	/**
38
	 * URLExtractor constructor.
39
	 */
40
	public function __construct(ClientInterface $http, RequestFactoryInterface $requestFactory = null){
41
		$this->http           = $http;
42
		$this->requestFactory = $requestFactory ?? new RequestFactory;
43
	}
44
45
	/**
46
	 * @inheritDoc
47
	 */
48
	public function sendRequest(RequestInterface $request):ResponseInterface{
49
50
		do{
51
			// fetch the response for the current request
52
			$response          = $this->http->sendRequest($request);
53
			$this->responses[] = $response;
54
			// set up a new request to the location header of the last response
55
			$request           = $this->requestFactory->createRequest($request->getMethod(), $response->getHeaderLine('location'));
56
		}
57
		while(in_array($response->getStatusCode(), [301, 302, 303, 307, 308], true));
58
59
		return $response;
60
	}
61
62
	/**
63
	 * @return \Psr\Http\Message\ResponseInterface[]
64
	 */
65
	public function getResponses():array{
66
		return $this->responses;
67
	}
68
69
}
70