]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Helper/HttpClientFactory.php
Merge pull request #4151 from ldidry/fix-4060
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Helper / HttpClientFactory.php
1 <?php
2
3 namespace Wallabag\CoreBundle\Helper;
4
5 use GuzzleHttp\Client as GuzzleClient;
6 use GuzzleHttp\Cookie\CookieJar;
7 use GuzzleHttp\Event\SubscriberInterface;
8 use Http\Adapter\Guzzle5\Client as GuzzleAdapter;
9 use Http\Client\HttpClient;
10 use Http\HttplugBundle\ClientFactory\ClientFactory;
11 use Psr\Log\LoggerInterface;
12
13 /**
14 * Builds and configures the HTTP client.
15 */
16 class HttpClientFactory implements ClientFactory
17 {
18 /** @var [\GuzzleHttp\Event\SubscriberInterface] */
19 private $subscribers = [];
20
21 /** @var \GuzzleHttp\Cookie\CookieJar */
22 private $cookieJar;
23
24 private $restrictedAccess;
25 private $logger;
26
27 /**
28 * HttpClientFactory constructor.
29 *
30 * @param string $restrictedAccess This param is a kind of boolean. Values: 0 or 1
31 */
32 public function __construct(CookieJar $cookieJar, $restrictedAccess, LoggerInterface $logger)
33 {
34 $this->cookieJar = $cookieJar;
35 $this->restrictedAccess = $restrictedAccess;
36 $this->logger = $logger;
37 }
38
39 /**
40 * Adds a subscriber to the HTTP client.
41 */
42 public function addSubscriber(SubscriberInterface $subscriber)
43 {
44 $this->subscribers[] = $subscriber;
45 }
46
47 /**
48 * Input an array of configuration to be able to create a HttpClient.
49 *
50 * @return HttpClient
51 */
52 public function createClient(array $config = [])
53 {
54 $this->logger->log('debug', 'Restricted access config enabled?', ['enabled' => (int) $this->restrictedAccess]);
55
56 if (0 === (int) $this->restrictedAccess) {
57 return new GuzzleAdapter(new GuzzleClient($config));
58 }
59
60 // we clear the cookie to avoid websites who use cookies for analytics
61 $this->cookieJar->clear();
62 if (!isset($config['defaults']['cookies'])) {
63 // need to set the (shared) cookie jar
64 $config['defaults']['cookies'] = $this->cookieJar;
65 }
66
67 $guzzle = new GuzzleClient($config);
68 foreach ($this->subscribers as $subscriber) {
69 $guzzle->getEmitter()->attach($subscriber);
70 }
71
72 return new GuzzleAdapter($guzzle);
73 }
74 }