-
-
Notifications
You must be signed in to change notification settings - Fork 310
/
Embed.php
89 lines (68 loc) · 2.32 KB
/
Embed.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
declare(strict_types = 1);
namespace Embed;
use Embed\Http\Crawler;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
class Embed
{
private Crawler $crawler;
private ExtractorFactory $extractorFactory;
public function __construct(Crawler $crawler = null, ExtractorFactory $extractorFactory = null)
{
$this->crawler = $crawler ?: new Crawler();
$this->extractorFactory = $extractorFactory ?: new ExtractorFactory();
}
public function get(string $url): Extractor
{
$request = $this->crawler->createRequest('GET', $url);
$response = $this->crawler->sendRequest($request);
return $this->extract($request, $response);
}
/**
* @return Extractor[]
*/
public function getMulti(string ...$urls): array
{
$requests = array_map(
fn ($url) => $this->crawler->createRequest('GET', $url),
$urls
);
$responses = $this->crawler->sendRequests(...$requests);
$return = [];
foreach ($responses as $k => $response) {
$return[] = $this->extract($requests[$k], $responses[$k]);
}
return $return;
}
public function getCrawler(): Crawler
{
return $this->crawler;
}
public function getExtractorFactory(): ExtractorFactory
{
return $this->extractorFactory;
}
public function setSettings(array $settings): void
{
$this->extractorFactory->setSettings($settings);
}
private function extract(RequestInterface $request, ResponseInterface $response, bool $redirect = true): Extractor
{
$uri = $this->crawler->getResponseUri($response) ?: $request->getUri();
$extractor = $this->extractorFactory->createExtractor($uri, $request, $response, $this->crawler);
if (!$redirect || !$this->mustRedirect($extractor)) {
return $extractor;
}
$request = $this->crawler->createRequest('GET', $extractor->redirect);
$response = $this->crawler->sendRequest($request);
return $this->extract($request, $response, false);
}
private function mustRedirect(Extractor $extractor): bool
{
if (!empty($extractor->getOembed()->all())) {
return false;
}
return $extractor->redirect !== null;
}
}