]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Helper/HttpClientFactory.php
Merge pull request #4151 from ldidry/fix-4060
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Helper / HttpClientFactory.php
CommitLineData
7aab0ecf
BD
1<?php
2
3namespace Wallabag\CoreBundle\Helper;
4
bf9ace06 5use GuzzleHttp\Client as GuzzleClient;
7aab0ecf
BD
6use GuzzleHttp\Cookie\CookieJar;
7use GuzzleHttp\Event\SubscriberInterface;
bf9ace06 8use Http\Adapter\Guzzle5\Client as GuzzleAdapter;
bf9ace06 9use Http\Client\HttpClient;
10use Http\HttplugBundle\ClientFactory\ClientFactory;
448d99f8 11use Psr\Log\LoggerInterface;
7aab0ecf
BD
12
13/**
bf9ace06 14 * Builds and configures the HTTP client.
7aab0ecf 15 */
bf9ace06 16class HttpClientFactory implements ClientFactory
7aab0ecf 17{
5b914b04
BD
18 /** @var [\GuzzleHttp\Event\SubscriberInterface] */
19 private $subscribers = [];
7aab0ecf
BD
20
21 /** @var \GuzzleHttp\Cookie\CookieJar */
22 private $cookieJar;
23
d64bf795 24 private $restrictedAccess;
7bf6b555 25 private $logger;
d64bf795 26
7aab0ecf
BD
27 /**
28 * HttpClientFactory constructor.
29 *
8d4ed0df 30 * @param string $restrictedAccess This param is a kind of boolean. Values: 0 or 1
7aab0ecf 31 */
5b914b04 32 public function __construct(CookieJar $cookieJar, $restrictedAccess, LoggerInterface $logger)
7aab0ecf 33 {
7aab0ecf 34 $this->cookieJar = $cookieJar;
d64bf795 35 $this->restrictedAccess = $restrictedAccess;
7bf6b555 36 $this->logger = $logger;
7aab0ecf
BD
37 }
38
39 /**
bf9ace06 40 * Adds a subscriber to the HTTP client.
bf9ace06 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 *
bf9ace06 50 * @return HttpClient
7aab0ecf 51 */
bf9ace06 52 public function createClient(array $config = [])
7aab0ecf 53 {
f808b016 54 $this->logger->log('debug', 'Restricted access config enabled?', ['enabled' => (int) $this->restrictedAccess]);
7bf6b555 55
d64bf795 56 if (0 === (int) $this->restrictedAccess) {
1048c9c4 57 return new GuzzleAdapter(new GuzzleClient($config));
d64bf795
NL
58 }
59
40f3ea57
NL
60 // we clear the cookie to avoid websites who use cookies for analytics
61 $this->cookieJar->clear();
1048c9c4 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);
5b914b04 68 foreach ($this->subscribers as $subscriber) {
bf9ace06 69 $guzzle->getEmitter()->attach($subscriber);
5b914b04 70 }
7aab0ecf 71
bf9ace06 72 return new GuzzleAdapter($guzzle);
5b914b04 73 }
7aab0ecf 74}