wallabag/src/Wallabag/CoreBundle/Helper/HttpClientFactory.php

75 lines
2.1 KiB
PHP
Raw Normal View History

<?php
namespace Wallabag\CoreBundle\Helper;
2017-10-24 20:55:40 +00:00
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Event\SubscriberInterface;
2017-10-24 20:55:40 +00:00
use Http\Adapter\Guzzle5\Client as GuzzleAdapter;
use Http\Client\HttpClient;
use Http\HttplugBundle\ClientFactory\ClientFactory;
2019-01-28 05:10:26 +00:00
use Psr\Log\LoggerInterface;
/**
2017-10-24 20:55:40 +00:00
* Builds and configures the HTTP client.
*/
2017-10-24 20:55:40 +00:00
class HttpClientFactory implements ClientFactory
{
2022-11-23 14:51:33 +00:00
/** @var SubscriberInterface[] */
private $subscribers = [];
2022-08-28 14:59:43 +00:00
/** @var CookieJar */
private $cookieJar;
private $restrictedAccess;
private $logger;
/**
* HttpClientFactory constructor.
*
* @param string $restrictedAccess This param is a kind of boolean. Values: 0 or 1
*/
public function __construct(CookieJar $cookieJar, $restrictedAccess, LoggerInterface $logger)
{
$this->cookieJar = $cookieJar;
$this->restrictedAccess = $restrictedAccess;
$this->logger = $logger;
}
/**
2017-10-24 20:55:40 +00:00
* Adds a subscriber to the HTTP client.
*/
public function addSubscriber(SubscriberInterface $subscriber)
{
$this->subscribers[] = $subscriber;
}
/**
* Input an array of configuration to be able to create a HttpClient.
*
* @return HttpClient
*/
2017-10-24 20:55:40 +00:00
public function createClient(array $config = [])
{
2017-07-01 07:52:38 +00:00
$this->logger->log('debug', 'Restricted access config enabled?', ['enabled' => (int) $this->restrictedAccess]);
if (0 === (int) $this->restrictedAccess) {
2017-11-12 11:15:02 +00:00
return new GuzzleAdapter(new GuzzleClient($config));
}
// we clear the cookie to avoid websites who use cookies for analytics
$this->cookieJar->clear();
2017-11-12 11:15:02 +00:00
if (!isset($config['defaults']['cookies'])) {
// need to set the (shared) cookie jar
$config['defaults']['cookies'] = $this->cookieJar;
}
$guzzle = new GuzzleClient($config);
foreach ($this->subscribers as $subscriber) {
2017-10-24 20:55:40 +00:00
$guzzle->getEmitter()->attach($subscriber);
}
2017-10-24 20:55:40 +00:00
return new GuzzleAdapter($guzzle);
}
}