public function run(Config $config) { $client = RestClient::create(['base_url' => $this->baseUrl, 'defaults' => ['headers' => UserFunction::build($this->headers, ['attr' => $config->getAttributes()])]], JuicerRest::convertRetry($this->retryConfig)); if (!empty($this->defaultRequestOptions)) { $client->setDefaultRequestOptions($this->defaultRequestOptions); } $this->auth->authenticateClient($client); // Verbose Logging of all requests $client->getClient()->getEmitter()->attach(new LogRequest()); if ($this->cache) { CacheSubscriber::attach($client->getClient(), ['storage' => $this->cache, 'validate' => false, 'can_cache' => function (RequestInterface $requestInterface) { return true; }]); } $this->initParser($config); $builder = new Builder(); foreach ($config->getJobs() as $jobConfig) { $this->runJob($jobConfig, $client, $config, $builder); } if ($this->parser instanceof Json) { // FIXME fallback from JsonMap $this->metadata = array_replace_recursive($this->metadata, $this->parser->getMetadata()); } // return $this->parser->getResults(); }
public function __construct() { $this->city = new City(); $this->helper = new QuestionHelper(); $this->client = new \GuzzleHttp\Client(); CacheSubscriber::attach($this->client); }
function __construct($baseUri, $apiKey, $options) { $this->_client = new Client(array('base_url' => $baseUri, 'defaults' => array('headers' => array('Authorization' => "api_key {$apiKey}", 'Content-Type' => 'application/json', 'User-Agent' => 'PHPClient/' . LDClient::VERSION), 'debug' => false, 'timeout' => $options['timeout'], 'connect_timeout' => $options['connect_timeout']))); if (!isset($options['cache_storage'])) { $csOptions = array('validate' => false); } else { $csOptions = array('storage' => $options['cache_storage'], 'validate' => false); } CacheSubscriber::attach($this->_client, $csOptions); }
/** * Register the Guzzle driver. * * @return void */ protected function registerGuzzle() { $this->app->singleton('http', function ($app) { $client = new Client(['base_url' => "https://{$app['school']}.magister.net/api/"]); $client->setDefaultOption('exceptions', false); $client->setDefaultOption('cookies', new SessionCookieJar($app['cookie'])); CacheSubscriber::attach($client); return $client; }); }
public function testCreatesAndAttachedDefaultSubscriber() { $client = new Client(); $cache = CacheSubscriber::attach($client); $this->assertArrayHasKey('subscriber', $cache); $this->assertArrayHasKey('storage', $cache); $this->assertInstanceOf('GuzzleHttp\\Subscriber\\Cache\\CacheStorage', $cache['storage']); $this->assertInstanceOf('GuzzleHttp\\Subscriber\\Cache\\CacheSubscriber', $cache['subscriber']); $this->assertTrue($client->getEmitter()->hasListeners('error')); }
public function testCachesResponses() { Server::enqueue([new Response(200, ['Vary' => 'Accept-Encoding,Cookie,X-Use-HHVM', 'Date' => 'Wed, 29 Oct 2014 20:52:15 GMT', 'Cache-Control' => 'private, s-maxage=0, max-age=0, must-revalidate', 'Last-Modified' => 'Wed, 29 Oct 2014 20:30:57 GMT', 'Age' => '1277']), new Response(304, ['Content-Type' => 'text/html; charset=UTF-8', 'Vary' => 'Accept-Encoding,Cookie,X-Use-HHVM', 'Date' => 'Wed, 29 Oct 2014 20:52:16 GMT', 'Cache-Control' => 'private, s-maxage=0, max-age=0, must-revalidate', 'Last-Modified' => 'Wed, 29 Oct 2014 20:30:57 GMT', 'Age' => '1278'])]); $client = new Client(['base_url' => Server::$url]); CacheSubscriber::attach($client); $history = new History(); $client->getEmitter()->attach($history); $response1 = $client->get('/foo'); $this->assertEquals(200, $response1->getStatusCode()); $response2 = $client->get('/foo'); $this->assertEquals(200, $response2->getStatusCode()); $this->assertCount(2, Server::received()); $last = $history->getLastResponse(); $this->assertEquals('HIT from GuzzleCache', $last->getHeader('X-Cache-Lookup')); $this->assertEquals('HIT from GuzzleCache', $last->getHeader('X-Cache')); }
public function getGeo($address) { try { CacheSubscriber::attach($this->geoClient); $geoResponse = $this->geoClient->get('', ['query' => ['address' => $address]]); if ($geoResponse->getStatusCode() != 200) { return false; } $resp = $geoResponse->json(); if ($resp['status'] != 'OK' || !count($resp['results'])) { return false; } return $resp['results'][0]['geometry']['location']; } catch (RequestException $e) { $this->logger->error('Problem reading a spreadsheet', ['exception' => $e]); } return false; }
/** * @param array $options * @param ClientInterface $httpClient * @param TokenStorageInterface $tokenStorage * @param CacheStorageInterface $cacheStorage */ public function __construct(array $options, ClientInterface $httpClient = null, TokenStorageInterface $tokenStorage = null, CacheStorageInterface $cacheStorage = null) { $this->validateOptions($options); $this->clientId = $options['client_id']; $this->clientSecret = $options['client_secret']; $this->grantType = array_key_exists('grant_type', $options) ? $options['grant_type'] : self::GRANT_TYPE_CLIENT_CREDENTIALS; $this->username = $options['username']; $this->password = $options['password']; $this->endpoint = $options['endpoint']; $this->tokenUrl = $options['token_url']; $this->client = $httpClient ?: new GuzzleClient(['base_url' => $this->endpoint]); $cacheDriver = new ArrayCache(); if (isset($options['cache_driver']) && $options['cache_driver'] instanceof Cache) { $cacheDriver = $options['cache_driver']; } $ttl = array_key_exists('cache_ttl', $options) ? (int) $options['cache_ttl'] : 300; $this->cacheStorage = $cacheStorage ?: new CacheStorage($cacheDriver, sprintf('api_client_%', $this->clientId), $ttl); // enable cache proxy CacheSubscriber::attach($this->client, ['storage' => $this->cacheStorage, 'validate' => false]); $this->tokenStorage = $tokenStorage ?: new InMemoryStorage(); }
protected function getGithubReleases() { try { $url = "https://api.github.com/repos/roadiz/roadiz/releases"; $client = new \GuzzleHttp\Client(['defaults' => ['debug' => false]]); // needs a composer require guzzlehttp/cache-subscriber CacheSubscriber::attach($client, array('storage' => new CacheStorage($this->getService('em')->getConfiguration()->getResultCacheImpl(), "rozier_github", 3600), 'validate' => false)); $response = $client->get($url); if (Response::HTTP_OK == $response->getStatusCode()) { return json_decode($response->getBody()); } else { return false; } } catch (\GuzzleHttp\Exception\RequestException $e) { return false; } }
<?php include "bootstrap.php"; //enable in-memory cache \GuzzleHttp\Subscriber\Cache\CacheSubscriber::attach($guzzle); //enable debug mode to see outgoing requests $exchange->debug(); //request is only executed once, promised $exchange->latest(); $exchange->latest();
<?php use GuzzleHttp\Subscriber\Cache\CacheSubscriber; require __DIR__ . '/vendor/autoload.php'; $results = array(); $versionFactory = new \Drupal\ParseComposer\VersionFactory(); $versionParser = new \Composer\Package\Version\VersionParser(); $client = new \GuzzleHttp\Client(); $storage = new \GuzzleHttp\Subscriber\Cache\CacheStorage(new \Doctrine\Common\Cache\FilesystemCache(__DIR__ . '/cache')); CacheSubscriber::attach($client, ['storage' => $storage]); $data = json_decode($client->get('https://www.drupal.org/api-d7/node.json?type=project_release&taxonomy_vocabulary_7=100&field_release_build_type=static')->getBody()); $projects = []; $conflict = []; class UrlHelper { public static function prepareUrl($url) { return str_replace('https://www.drupal.org/api-d7/node', 'https://www.drupal.org/api-d7/node.json', $url); } } while (isset($data) && isset($data->list)) { $results = array_merge($results, $data->list); if (isset($data->next)) { $data = json_decode($client->get(UrlHelper::prepareUrl($data->next))->getBody()); } else { $data = NULL; } } foreach ($results as $result) { $nid = $result->field_release_project->id; $core = (int) substr($result->field_release_version, 0, 1);
/** * Set up caching on a Guzzle client. * * @param ClientInterface $client */ protected function setUpCache(ClientInterface $client) { if ($this->config['cache'] === false) { return; } $options = is_array($this->config['cache']) ? $this->config['cache'] : []; CacheSubscriber::attach($client, $options); }
/** * Setup a Guzzle client for testing. * * @param History $history (optional) parameter of a History to track * requests in. * * @return Client A client ready to run test requests against. */ private function setupClient(History $history = null) { $client = new Client(['base_url' => Server::$url]); CacheSubscriber::attach($client); if ($history) { $client->getEmitter()->attach($history); } return $client; }
/** * Sets the browser driver depending on the javascript select parameter or injected browser driver * @param Session $driver */ private function setBrowser(Session $driver = null) { if ($driver != null) { $this->browser = new Mink(['custom' => $driver]); $this->browser->setDefaultSessionName('custom'); return; } $client = new Client(); $guzzle = $client->getClient(); CacheSubscriber::attach($guzzle, []); $client->setClient($guzzle); // init Mink and register sessions $this->browser = new Mink(['goutte' => new Session(new GoutteDriver($client)), 'selenium2' => new Session(new Selenium2Driver('firefox', ["permissions.default.image" => 2]))]); if (!$this->javaScriptRequired) { $this->browser->setDefaultSessionName('goutte'); return; } $this->browser->setDefaultSessionName('selenium2'); }
* An example sandbox client is given below with a client_full_access scoped token. */ //$config['client_id'] = 'client_39KFJ83nyeDAQxxxLPCb'; //$config['client_secret'] = 'H5QUsuHMjRmcV2LvZIMpRgPyHgZj1tqCs6sNuZrD'; //$config['refresh_token'] = 'ce245fbc1d955ed320dfa27ccbfce90a5c2d8e07'; /** * If you happen to store the current access_token and time it has left before needing to be refreshed, you can pass that in also. */ //$config['access_token'] = '818ea84b63a8873c9169ed62e88b6e8e6c200024'; //$config['access_token_expires'] = '1428097039'; $guzzle_config = array('defaults' => array('debug' => false, 'exceptions' => false)); /** * Set up our Guzzle Client */ $guzzle = new Client($guzzle_config); CacheSubscriber::attach($guzzle); /** * Get our FoxyClient */ $fc = new FoxyClient($guzzle, $config); /** * Get some Cross Site Request Forgery protection love goin' on. */ $csrf = new \Riimu\Kit\CSRF\CSRFHandler(false); try { $csrf->validateRequest(true); } catch (\Riimu\Kit\CSRF\InvalidCSRFTokenException $ex) { header('HTTP/1.0 400 Bad Request'); exit('Bad CSRF Token!'); } $token = $csrf->getToken();
/** * {@inheritdoc} */ public function setHttpClient($client) { CacheSubscriber::attach($client); parent::setHttpClient($client); return $this; }
/** * Add an subscriber to enable caching. * * @param array $parameters * @throws \RuntimeException * @return $this */ public function setDefaultCaching(array $parameters) { if ($parameters['enabled']) { if (!class_exists('Doctrine\\Common\\Cache\\CacheProvider')) { //@codeCoverageIgnoreStart throw new \RuntimeException('Could not find the doctrine cache library, have you added doctrine-cache to your composer.json?'); //@codeCoverageIgnoreEnd } CacheSubscriber::attach($this->getAdapter()->getClient(), ['storage' => new CacheStorage($parameters['handler'])]); } return $this; }