77use GuzzleHttp \Client ;
88use GuzzleHttp \Cookie \CookieJar ;
99use GuzzleHttp \TransferStats ;
10+ use GuzzleHttp \Exception \ConnectException ;
1011
1112/**
1213 * Class HttpReader
@@ -18,6 +19,49 @@ class HttpReader implements ReaderInterface
1819 */
1920 private $ client ;
2021
22+ /**
23+ * @var array $config
24+ */
25+ private $ config ;
26+
27+ /**
28+ * @var CookieJar $jar
29+ */
30+ private $ jar ;
31+
32+ /**
33+ * HttpReader constructor.
34+ * @param array|null $config
35+ */
36+ public function __construct ($ config = null )
37+ {
38+ $ this ->jar = new CookieJar ();
39+
40+ $ this ->config = $ config ?: [
41+ 'allow_redirects ' => ['max ' => 10 ],
42+ 'cookies ' => $ this ->jar ,
43+ 'connect_timeout ' => 5
44+ ];
45+ }
46+
47+ /**
48+ * @param int $timeout
49+ */
50+ public function setTimeout ($ timeout )
51+ {
52+ $ this ->config (['connect_timeout ' => $ timeout ]);
53+ }
54+
55+ /**
56+ * @param array $parameters
57+ */
58+ public function config (array $ parameters )
59+ {
60+ foreach ($ parameters as $ key => $ value ) {
61+ $ this ->config [$ key ] = $ value ;
62+ }
63+ }
64+
2165 /**
2266 * @return Client
2367 */
@@ -44,18 +88,19 @@ public function setClient($client)
4488 public function readLink (LinkInterface $ link )
4589 {
4690 $ client = $ this ->getClient ();
47- $ jar = new CookieJar ();
4891
49- $ response = $ client ->request ('GET ' , $ link ->getUrl (), [
50- 'allow_redirects ' => ['max ' => 10 ],
51- 'cookies ' => $ jar ,
52- 'on_stats ' => function (TransferStats $ stats ) use (&$ link ) {
53- $ link ->setEffectiveUrl ($ stats ->getEffectiveUri ());
54- }
55- ]);
56-
57- $ link ->setContent ($ response ->getBody ())
58- ->setContentType ($ response ->getHeader ('Content-Type ' )[0 ]);
92+ try {
93+ $ response = $ client ->request ('GET ' , $ link ->getUrl (), array_merge ($ this ->config , [
94+ 'on_stats ' => function (TransferStats $ stats ) use (&$ link ) {
95+ $ link ->setEffectiveUrl ($ stats ->getEffectiveUri ());
96+ }
97+ ]));
98+
99+ $ link ->setContent ($ response ->getBody ())
100+ ->setContentType ($ response ->getHeader ('Content-Type ' )[0 ]);
101+ } catch (ConnectException $ e ) {
102+ $ link ->setContent (false )->setContentType (false );
103+ }
59104
60105 return $ link ;
61106 }
0 commit comments