示例#1
1
 protected function emit($channel, $event, $message = null)
 {
     $client = new \Guzzle\Http\Client();
     $apiUrl = "{$this->container->getParameter('socketio_baseurl')}/{$channel}/emit";
     $request = $client->post($apiUrl, array('Content-Type' => 'application/json'), json_encode(array('event' => $event, 'message' => $message)));
     $client->send($request);
 }
示例#2
1
 /**
  * Creates a guzzle service client
  * @return \Guzzle\Http\Client the guzzle client
  */
 protected function createGuzzle()
 {
     $guzzle = new \Guzzle\Http\Client();
     $connectionConfig = $this->getClient()->getConnectionConfig();
     $guzzle->setBaseUrl('http://' . $connectionConfig['host'] . ':1' . $connectionConfig['port'] . '/');
     $authPlugin = new CurlAuthPlugin($connectionConfig['user'], $connectionConfig['password']);
     $guzzle->addSubscriber($authPlugin);
     return $guzzle;
 }
 /**
  * @inheritDoc ITask::runStep()
  *
  * @param int $step
  *
  * @return bool
  */
 public function runStep($step)
 {
     // NOTE: Perhaps much of this should be moved into a service
     $batch = \Guzzle\Batch\BatchBuilder::factory()->transferRequests(20)->bufferExceptions()->build();
     // Make the client
     $client = new \Guzzle\Http\Client();
     // Set the Accept header
     $client->setDefaultOption('headers/Accept', '*/*');
     // Loop the paths in this step
     foreach ($this->_paths[$step] as $path) {
         // Make the url, stripping 'site:' from the path if it exists
         $newPath = preg_replace('/site:/', '', $path, 1);
         $url = UrlHelper::getSiteUrl($newPath);
         // Create the GET request
         $request = $client->get($url);
         // Add it to the batch
         $batch->add($request);
     }
     // Flush the queue and retrieve the flushed items
     $requests = $batch->flush();
     // Log any exceptions
     foreach ($batch->getExceptions() as $e) {
         Craft::log('CacheMonster: an exception occurred: ' . $e->getMessage(), LogLevel::Error);
     }
     // Clear any exceptions
     $batch->clearExceptions();
     return true;
 }
示例#4
0
 public function getRecipientViewUrl($returnUrl)
 {
     $data = array("email" => $this->studentEmail, "returnUrl" => $returnUrl, "authenticationMethod" => "None", "userName" => $this->studentName, "clientUserId" => $this->clientUserId);
     //var_dump($data);
     //exit;
     $http = new \Guzzle\Http\Client();
     try {
         //$request = $http->createRequest('POST', $this->client->getBaseUrl() . $this->envelope->getUri() . '/views/recipient', ['body' => json_encode($data)]);
         $request = $http->createRequest('POST', $this->client->getBaseUrl() . $this->envelope->getUri() . '/views/recipient');
         $request->setBody(json_encode($data), 'application/json');
         $request->setHeader('Content-Type', 'application/json');
         $request->setHeader('Accept', 'application/json');
         $request->setHeader('X-DocuSign-Authentication', $this->client->getAuthHeader());
         $response = $http->send($request);
     } catch (\Guzzle\Http\Exception\RequestException $e) {
         //var_dump($e->getResponse()->json());
         //var_dump($e);
         //var_dump($e->getRequest());
         //exit;
         throw $e;
     }
     $result = $response->json();
     //var_dump($result);exit;
     return $result['url'];
 }
示例#5
0
 public function get($options)
 {
     $url = $options['url'];
     $limit = array_key_exists('limit', $options) ? NumberHelper::makeNumeric($options['limit']) : null;
     $offset = array_key_exists('offset', $options) ? NumberHelper::makeNumeric($options['offset']) : 0;
     // Check to see if the response is cached
     $cachedResponse = craft()->fileCache->get($url);
     if ($cachedResponse) {
         return $cachedResponse;
     }
     try {
         $client = new \Guzzle\Http\Client();
         $request = $client->get($url);
         $response = $request->send();
         if (!$response->isSuccessful()) {
             return;
         }
         $items = $response->json();
         // Cache the response
         craft()->fileCache->set($url, $items);
         // Apply the limit and offset
         $items = array_slice($items, $offset, $limit);
         return $items;
     } catch (\Exception $e) {
         return;
     }
 }
 public function updateProductsAction()
 {
     $user = Auth::user();
     $config = Config::get('providers.' . $user->provider);
     $client = new \Guzzle\Http\Client();
     $headers = $config['headers'];
     array_walk($headers, function (&$value, $key) use($user) {
         $value = str_replace('{token}', $user->access_token, $value);
     });
     $request = $client->get(str_replace('{blog_id}', $user->blog_id, $config['mediaUri']));
     $request->setHeaders($headers);
     $request->getHeaders()->toArray();
     $response = $request->send();
     $images = $response->json()['media'];
     $products = [];
     foreach ($images as $image) {
         if (!($product = Product::where('image_id', '=', $image['id'])->first())) {
             $product = new Product();
             $product->image_id = $image['id'];
             $product->image = $image['link'];
             $user->products()->save($product);
             $products[] = $product;
         }
     }
     return Redirect::route('products');
 }
 /**
  * Verify a reCAPTCHA submission.
  *
  * @return bool
  */
 public function verify()
 {
     // Get reCAPTCHA value
     $captcha = craft()->request->getPost('g-recaptcha-response');
     // Get reCAPTCHA secret key
     $secretKey = craft()->amForms_settings->getSettingsByHandleAndType('secretKey', AmFormsModel::SettingRecaptcha);
     if (!$secretKey) {
         return false;
     }
     // Google API parameters
     $params = array('secret' => $secretKey->value, 'response' => $captcha);
     // Set request
     $client = new \Guzzle\Http\Client();
     $request = $client->post('https://www.google.com/recaptcha/api/siteverify');
     $request->addPostFields($params);
     $result = $client->send($request);
     // Handle response
     if ($result->getStatusCode() == 200) {
         $json = $result->json();
         if ($json['success']) {
             return true;
         }
     }
     return false;
 }
 public function runStep($step)
 {
     VarnishpurgePlugin::log('Varnish purge task run step: ' . $step, LogLevel::Info, craft()->varnishpurge->getSetting('varnishLogAll'));
     $servers = craft()->varnishpurge->getSetting('varnishUrl');
     if (!is_array($servers)) {
         $servers = array($servers);
     }
     foreach ($servers as $server) {
         $batch = \Guzzle\Batch\BatchBuilder::factory()->transferRequests(20)->bufferExceptions()->build();
         $client = new \Guzzle\Http\Client();
         $client->setDefaultOption('headers/Accept', '*/*');
         foreach ($this->_urls[$step] as $url) {
             $urlComponents = parse_url($url);
             $targetUrl = preg_replace('{/$}', '', $server) . $urlComponents['path'];
             VarnishpurgePlugin::log('Adding url to purge: ' . $targetUrl . ' with Host: ' . $urlComponents['host'], LogLevel::Info, craft()->varnishpurge->getSetting('varnishLogAll'));
             $request = $client->createRequest('PURGE', $targetUrl);
             $request->addHeader('Host', $urlComponents['host']);
             $batch->add($request);
         }
         $requests = $batch->flush();
         foreach ($batch->getExceptions() as $e) {
             VarnishpurgePlugin::log('An exception occurred: ' . $e->getMessage(), LogLevel::Error);
         }
         $batch->clearExceptions();
     }
     return true;
 }
 private function updateAddon(ActiveRow $addon)
 {
     $this->writeln('Updating: ' . $addon->name);
     $github = $this->normalizeGithubUrl($addon->repository);
     if ($github) {
         $guzzle = new \Guzzle\Http\Client();
         try {
             $guzzle->get($github)->send();
             $this->db->table('addons_resources')->insert(array('addonId' => $addon->id, 'type' => 'github', 'resource' => $github));
         } catch (\Guzzle\Http\Exception\RequestException $e) {
             $this->writeln((string) $e);
         }
     }
     if ($addon->type === 'composer') {
         $version = $addon->related('versions')->order('id', 'DESC')->fetch();
         $composerData = Json::decode($version->composerJson);
         $packagist = $this->generatePackagistUrl($composerData->name);
         $guzzle = new \Guzzle\Http\Client();
         try {
             $guzzle->get($packagist . '.json')->send();
             $this->db->table('addons_resources')->insert(array('addonId' => $addon->id, 'type' => 'packagist', 'resource' => $packagist));
         } catch (\Guzzle\Http\Exception\RequestException $e) {
             $this->writeln((string) $e);
         }
     }
     if ($addon->demo) {
         $guzzle = new \Guzzle\Http\Client();
         try {
             $guzzle->get($addon->demo)->send();
             $this->db->table('addons_resources')->insert(array('addonId' => $addon->id, 'type' => 'demo', 'resource' => $addon->demo));
         } catch (\Guzzle\Http\Exception\RequestException $e) {
             $this->writeln((string) $e);
         }
     }
 }
 /**
  * 
  * @return \Guzzle\Http\Message\Request $request
  */
 public function getBaseRequest()
 {
     if (is_null($this->baseRequest)) {
         $client = new \Guzzle\Http\Client();
         $this->baseRequest = $client->get();
     }
     return $this->baseRequest;
 }
示例#11
0
 /**
  * 
  * @return \Guzzle\Http\Message\Request $request
  */
 public function getBaseRequest()
 {
     if (is_null($this->baseRequest)) {
         $client = new \Guzzle\Http\Client();
         $client->addSubscriber(new \Guzzle\Plugin\History\HistoryPlugin());
         $this->baseRequest = $client->get();
     }
     return $this->baseRequest;
 }
示例#12
0
 /**
  * Fetch the latest issue counts from Drupal.org and add them to the
  * database as a new sample.
  */
 public function fetchCounts(Application $app)
 {
     $guzzleClient = new \Guzzle\Http\Client();
     if (!empty($app['config']['guzzle']['userAgent'])) {
         $guzzleClient->setUserAgent($app['config']['guzzle']['userAgent'], true);
     }
     $this->repositoryUpdater->samples($guzzleClient, $app['config']['drupal_issues']);
     return '';
 }
示例#13
0
 public static function getMockResponseClient($responseCode, $fixtureFile)
 {
     $client = new \Guzzle\Http\Client();
     $plugin = new \Guzzle\Plugin\Mock\MockPlugin();
     $mockResponse = SpecHelper::getMockResponseFromFixture($responseCode, $fixtureFile);
     $plugin->addResponse($mockResponse);
     $client->addSubscriber($plugin);
     return $client;
 }
 private function createPackagistClient($data, $status = 200)
 {
     $packagistResponse = new \Guzzle\Http\Message\Response($status);
     $packagistResponse->setBody($data);
     $plugin = new \Guzzle\Plugin\Mock\MockPlugin();
     $plugin->addResponse($packagistResponse);
     $clientHttp = new \Guzzle\Http\Client();
     $clientHttp->addSubscriber($plugin);
     return new Client($clientHttp);
 }
 /**
  * Test a count request that cannot be satisfied with only the first page
  * of results.
  */
 public function testMultiPageCount()
 {
     $responses = array(MockPlugin::getMockFile(TEST_RESOURCE_PATH . '/http/drupal_org_major_bugs_0'), MockPlugin::getMockFile(TEST_RESOURCE_PATH . '/http/drupal_org_major_bugs_1'), MockPlugin::getMockFile(TEST_RESOURCE_PATH . '/http/drupal_org_major_bugs_2'), MockPlugin::getMockFile(TEST_RESOURCE_PATH . '/http/drupal_org_major_bugs_3'), MockPlugin::getMockFile(TEST_RESOURCE_PATH . '/http/drupal_org_major_bugs_4'), MockPlugin::getMockFile(TEST_RESOURCE_PATH . '/http/drupal_org_major_bugs_5'));
     $mockPlugin = new MockPlugin($responses);
     $client = new \Guzzle\Http\Client();
     $client->addSubscriber($mockPlugin);
     $issueCounter = new DrupalIssueCount($client);
     $issueCount = $issueCounter->getCounts(array('status' => array(1, 13, 8, 14, 15, 4)), array('major_bugs' => array('priorities' => array(300), 'categories' => array(1))));
     $this->assertEquals(271, $issueCount['major_bugs']);
 }
示例#16
0
 /**
  * @return \Guzzle\Http\Client
  */
 protected function buildHttpMockClient($body)
 {
     $plugin = new \Guzzle\Plugin\Mock\MockPlugin();
     $response = new \Guzzle\Http\Message\Response(200);
     $response->setBody($body);
     $plugin->addResponse($response);
     $mockedClient = new \Guzzle\Http\Client();
     $mockedClient->addSubscriber($plugin);
     return $mockedClient;
 }
示例#17
0
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $app = $this->getApplication()->getContainer();
     $repositoryUpdater = new Updater($app['db']);
     $guzzleClient = new \Guzzle\Http\Client();
     if (!empty($app['config']['guzzle']['userAgent'])) {
         $guzzleClient->setUserAgent($app['config']['guzzle']['userAgent'], true);
     }
     $repositoryUpdater->samples($guzzleClient, $app['config']['drupal_issues']);
     // TODO output success message.
 }
示例#18
0
 /**
  * Constructor.
  *
  * @param string $backend Backend type, currently 'mysql' or 'redshift' is accepted.
  * @param string $token Storage API token.
  * @param string $runId Storage API run Id.
  * @param string $url
  */
 public function __construct($backend, $token, $runId, $url = 'https://syrup.keboola.com/provisioning')
 {
     $this->setBackend($backend);
     $this->setToken($token);
     $this->setRunId($runId);
     $client = new \Guzzle\Http\Client($url);
     $client->getConfig()->set('curl.options', array(CURLOPT_TIMEOUT => $this->timeout));
     $maintenanceBackoff = new BackoffPlugin(new TruncatedBackoffStrategy(10, new MaintenanceBackoffStrategy(array(503), new CurlBackoffStrategy(CurlBackoffStrategy::getDefaultFailureCodes(), new ExponentialBackoffStrategy()))));
     $client->addSubscriber($maintenanceBackoff);
     $this->client = $client;
 }
示例#19
0
 /**
  * Prepares the HTTP client
  * @return \Guzzle\Http\Client
  */
 private function prepareHttpClient()
 {
     $guzzleOption = array('request.options' => array('verify' => !$this->options['turn_off_ssl_verification'], 'exceptions' => false));
     // Using api key
     if ($this->apiUser === null) {
         $guzzleOption['request.options']['headers'] = array('Authorization' => 'Bearer ' . $this->apiKey);
     }
     $client = new \Guzzle\Http\Client($this->url, $guzzleOption);
     $client->setUserAgent('sendgrid/' . $this->version . ';php');
     return $client;
 }
 public function handleSubmit()
 {
     $data = array_merge(Input::input(), $this->fileDetails('cover_letter'), $this->fileDetails('resume'));
     $client = new Guzzle\Http\Client(Config::get('remote.submit-domain'));
     $request = $client->post('submit', [], $data);
     $response = $request->send();
     if ($response->isSuccessful()) {
         return Redirect::route('app.submit')->withInfo('You have successfully submitted.');
     } else {
         return Redirect::route('app.submit')->withError('Your submission failed - try again, good luck.');
     }
 }
示例#21
0
 /**
  * Make the call to the endpoint and get the result
  *
  * @param string $url The URL to call
  * @param string $method The verb to use
  * @param array $params An array of parameters
  *
  * @return array The result in php array
  */
 private function call($url, $method, $params = null)
 {
     $request = $this->client->createRequest($method, $this->getEndpoint() . $url);
     $request->setHeader('Content-Type', 'application/' . $this->format);
     $request->setHeader('Accept', 'application/' . $this->format);
     $request->setHeader('Authorization', 'Basic ' . base64_encode($this->username . "/token:" . $this->api_key));
     if ($params) {
         $request->setBody(Stream::factory(json_encode($params)));
     }
     $response = $this->client->send($request);
     return json_decode($response->getBody());
 }
 public function setUp()
 {
     // see the config_test.yml, there's a parameters in order to not stream the output using FakeImageCreator.
     $data = '{"package":{"name":"pugx\\/badge-poser","description":"add badges on your readme, such as downloads number or latest version.","time":"2013-05-24T14:45:06+00:00","maintainers":[{"name":"liuggio","email":"*****@*****.**"}],"versions":{"dev-master":{"name":"pugx\\/badge-poser","description":"add badges on your readme, such as downloads number or latest version.","keywords":[],"homepage":"","version":"dev-master","version_normalized":"9999999-dev","license":[],"authors":[],"source":{"type":"git","url":"https:\\/\\/github.com\\/PUGX\\/badge-poser.git","reference":"024df1d420cd715aea3400bfea9b87ed0f3bb47e"},"dist":{"type":"zip","url":"https:\\/\\/api.github.com\\/repos\\/PUGX\\/badge-poser\\/zipball\\/024df1d420cd715aea3400bfea9b87ed0f3bb47e","reference":"024df1d420cd715aea3400bfea9b87ed0f3bb47e","shasum":""},"type":"library","time":"2013-05-24T19:19:25+00:00","autoload":{"psr-0":{"":"src\\/"}},"extra":{"symfony-app-dir":"app","symfony-web-dir":"web","branch-alias":{"dev-master":"0.1-dev"}},"require":{"php":">=5.3.3","symfony\\/symfony":"2.2.*","doctrine\\/orm":">=2.2,<3.0,>=2.2.3","doctrine\\/doctrine-bundle":"1.2.*","twig\\/extensions":"1.0.*","symfony\\/assetic-bundle":"2.1.*","symfony\\/swiftmailer-bundle":"2.2.*","symfony\\/monolog-bundle":"2.2.*","sensio\\/distribution-bundle":"2.2.*","sensio\\/framework-extra-bundle":"2.2.*","sensio\\/generator-bundle":"2.2.*","jms\\/security-extra-bundle":"1.4.*","jms\\/di-extra-bundle":"1.3.*","knplabs\\/packagist-api":"dev-master"},"require-dev":{"guzzle\\/plugin-mock":"*"}},"dev-develop":{"name":"pugx\\/badge-poser","description":"add badges on your readme, such as downloads number or latest version.","keywords":[],"homepage":"","version":"dev-develop","version_normalized":"dev-develop","license":[],"authors":[],"source":{"type":"git","url":"https:\\/\\/github.com\\/PUGX\\/badge-poser.git","reference":"024df1d420cd715aea3400bfea9b87ed0f3bb47e"},"dist":{"type":"zip","url":"https:\\/\\/api.github.com\\/repos\\/PUGX\\/badge-poser\\/zipball\\/024df1d420cd715aea3400bfea9b87ed0f3bb47e","reference":"024df1d420cd715aea3400bfea9b87ed0f3bb47e","shasum":""},"type":"library","time":"2013-05-24T19:19:25+00:00","autoload":{"psr-0":{"":"src\\/"}},"extra":{"symfony-app-dir":"app","symfony-web-dir":"web","branch-alias":{"dev-master":"0.1-dev"}},"require":{"php":">=5.3.3","symfony\\/symfony":"2.2.*","doctrine\\/orm":">=2.2,<3.0,>=2.2.3","doctrine\\/doctrine-bundle":"1.2.*","twig\\/extensions":"1.0.*","symfony\\/assetic-bundle":"2.1.*","symfony\\/swiftmailer-bundle":"2.2.*","symfony\\/monolog-bundle":"2.2.*","sensio\\/distribution-bundle":"2.2.*","sensio\\/framework-extra-bundle":"2.2.*","sensio\\/generator-bundle":"2.2.*","jms\\/security-extra-bundle":"1.4.*","jms\\/di-extra-bundle":"1.3.*","knplabs\\/packagist-api":"dev-master"},"require-dev":{"guzzle\\/plugin-mock":"*"}}},"type":"library","repository":"https:\\/\\/github.com\\/PUGX\\/badge-poser","downloads":{"total":99,"monthly":12,"daily":9},"favers":9}}';
     $packagistResponse = new \Guzzle\Http\Message\Response(200);
     $packagistResponse->setBody($data);
     $plugin = new \Guzzle\Plugin\Mock\MockPlugin();
     $plugin->addResponse($packagistResponse);
     $clientHttp = new \Guzzle\Http\Client();
     $clientHttp->addSubscriber($plugin);
     $this->packagistClient = new Client($clientHttp);
 }
示例#23
0
 private function getTelizeData($ip)
 {
     $url = "/geip/" . $ip;
     $telizeClient = new \Guzzle\Http\Client("http://www.telize.com");
     $response = $telizeClient->get($url)->send();
     if (!$response->isSuccessful()) {
         return array();
     }
     $data = json_decode($response->getBody(), true);
     $data = array("ip" => $data['ip'], "country_code" => $data['country_code'], "country_name" => $data['country'], "latitude" => $data['latitude'], "longitude" => $data['longitude'], "cached" => false);
     return $data;
 }
示例#24
0
 /**
  * Prepares the HTTP client
  *
  * @return \Guzzle\Http\Client
  */
 private function prepareHttpClient()
 {
     $guzzleOption = array('request.options' => array('verify' => !$this->options['turn_off_ssl_verification'], 'exceptions' => isset($this->options['enable_guzzle_exceptions']) && $this->options['enable_guzzle_exceptions'] == true));
     $guzzleOption['request.options']['headers'] = array('Authorization' => 'Bearer ' . $this->apiKey, 'Content-Type' => 'application/json', 'Accept' => '*/*');
     // Using http proxy
     if (isset($this->options['proxy'])) {
         $guzzleOption['request.options']['proxy'] = $this->options['proxy'];
     }
     $client = new \Guzzle\Http\Client($this->url, $guzzleOption);
     $client->setUserAgent('sendgrid/' . $this->version . ';php');
     return $client;
 }
示例#25
0
文件: Http.php 项目: pnomolos/phitly
 protected function _get($method, $opts = array())
 {
     $opts += array('query' => array(), 'timeout' => 0);
     $opts['query'] = array_merge($opts['query'], $this->default_query_opts);
     $url = ltrim($method, '/') . (!strpos($method, '?') ? '?' : '&') . http_build_query($opts['query']);
     $client = new \Guzzle\Http\Client($this->base_uri);
     $request = $client->get($url);
     if ($opts['timeout']) {
         $request->getCurlOptions()->set(CURLOPT_TIMEOUT, $opts['timeout']);
     }
     $response = $request->send();
     return json_decode(json_encode($response->json()));
 }
示例#26
0
 /**
  * Use Craft's included Guzzle library to make an API request
  * 
  * @param  string $url  The URL to query
  * 
  * @return void
  */
 private function _curlRequest($url = '')
 {
     try {
         $client = new \Guzzle\Http\Client($url);
         $request = $client->get($url, array('Accept' => 'application/rss+xml', 'Accept' => 'application/rdf+xml', 'Accept' => 'application/xml', 'Accept' => 'text/xml'));
         $response = $request->send();
         return $response->getBody(true);
     } catch (\Exception $e) {
         FeederPlugin::log($e->getResponse(), LogLevel::Error, true);
         $response = $e->getResponse();
         return $response;
     }
 }
 /**
  * @test
  */
 public function test()
 {
     $restClient = new \Guzzle\Http\Client('http://api.searchperience.com/');
     $mock = new \Guzzle\Plugin\Mock\MockPlugin();
     $mock->addResponse(new \Guzzle\Http\Message\Response(201, NULL, $this->getFixtureContent('Api/Client/System/Storage/Fixture/StopwordTags.xml')));
     $restClient->addSubscriber($mock);
     $this->stopwordTagBackend->injectRestClient($restClient);
     $synonymTags = $this->stopwordTagBackend->getAll();
     $this->assertEquals(3, $synonymTags->getTotalCount(), 'Could not reconstitute synonym collection');
     $this->assertEquals(3, $synonymTags->getCount(), 'Could not get count from synonyms');
     $secondSynonymTag = $synonymTags->offsetGet(1);
     $this->assertSame("de", $secondSynonymTag->getTagName(), 'Could not restore synonym tag');
 }
 /**
  *
  * @test
  */
 public function canPostDocument()
 {
     $this->urlQueueItemBackend = $this->getMock('\\Searchperience\\Api\\Client\\System\\Storage\\RestUrlQueueItemBackend', array('executePostRequest'));
     $this->urlQueueItemBackend->injectDateTimeService(new \Searchperience\Api\Client\System\DateTime\DateTimeService());
     $restClient = new \Guzzle\Http\Client('http://api.searchperience.com/');
     $mock = new \Guzzle\Plugin\Mock\MockPlugin();
     $mock->addResponse(new \Guzzle\Http\Message\Response(201));
     $restClient->addSubscriber($mock);
     $this->urlQueueItemBackend->injectRestClient($restClient);
     $expectsArgumentsArray = array('deleted' => 0, 'documentId' => '111', 'priority' => 3, 'url' => 'http://aoe.com');
     $this->urlQueueItemBackend->expects($this->once())->method('executePostRequest')->with($expectsArgumentsArray)->will($this->returnValue($this->getMock('\\Guzzle\\Http\\Message\\Response', array(), array(), '', false)));
     $this->urlQueueItemBackend->post($this->getTestUrlQueueItem());
 }
示例#29
0
 /**
  * Reads data from a file or URL data can be parsed as PHP
  * 
  * <code>
  * // possible resource examples
  * $resource = 'http://path/to/resource'; // URL that points to the resource
  * $resource = 'path/to/file';            // File that contains the resource
  * $resource = 'some string';             // string in the expected format
  * $resource = ['some' => 'array'];       // array
  * $resource = ?                          // some other format as long there is a suitable plugin
  * 
  * // In the cases of URLs, files and strings the resource can also be be parsed, see options below
  * 
  * $options = [
  *   'parse_file'      => true,     // accept files as parameter
  *   'parse_php'       => false,    // evaluate PHP code in a file, means also to
  *                                  // parse code treated with serialize() to an array.
  *                                  // Code serialized with json_encode() are always allowed
  *                                  // NOTE: Use this with only when you are sure about the source!
  *   'expected_format' => null,     // string|array by default computed from the name of the calling function 
  *                                  // triggered within the restrictions above
  *   'parse_url'       => true,     // accept URLs as parameter
  *   'use_cache'       => true,     // URL resources are cached for a short while by default to avoid HTTP requests
  *   'cache_dir'       => null,     // default: rtrim(sys_get_temp_dir(), '/') . '/PHP_Jig/Converter/' . session_id()
  * ];
  * 
  * // $options will be merged with those in the constructor and those sent to the function
  * </code>
  * 
  * @param mixed $resource
  * @param array $options
  * @return mixed
  * @todo garbage collection for cached resources
  */
 protected static function getRealResource($resource, $options = [])
 {
     $options = array_merge(['parse_php' => false, 'parse_file' => true, 'parse_url' => true, 'use_cache' => true, 'expected_format' => null, 'cache_dir' => rtrim(sys_get_temp_dir(), '/') . '/PHP_Jig/Converter/' . session_id()], $options);
     // compute expected format
     if (is_null($options['expected_format'])) {
         $matches = [];
         preg_match('~^from(?<expected_format>[\\w]+)$~', strtolower(debug_backtrace()[1]['function']), $matches);
         if (empty($matches['expected_format']) || !in_array($matches['expected_format'], ['string', 'array'])) {
             $options['expected_format'] = 'string';
         } else {
             $options['expected_format'] = $matches['expected_format'];
         }
     }
     // - Resource cannot be a file or a URL or they are both disallowed
     if (!is_string($resource) || !$options['parse_url'] && !$options['parse_file']) {
         return $resource;
     }
     $cacheFile = $options['cache_dir'] . '/' . session_id() . '/' . md5($resource);
     // - Resource might be cached
     if ($options['use_cache'] && is_readable($cacheFile)) {
         return FileCache::read($cacheFile);
     }
     // - Resource might be an URL
     if ($options['parse_url'] && false === strpos($resource, "\n") && false !== strpos($resource, '://')) {
         $client = new \Guzzle\Http\Client($resource);
         $request = $client->get();
         $response = $request->send();
         $resource = (string) $response->getBody();
         if ($options['expected_format'] === 'array') {
             $resource = self::unserializeResource($resource, $options['parse_php']);
         }
         if ($options['use_cache']) {
             FileCache::write($cacheFile, $resource, '+1minute');
         }
         return $resource;
     }
     // - Resource might be a file
     if ($options['parse_file'] && false === strpos($resource, "\n") && is_readable($resource)) {
         if ($options['parse_php']) {
             ob_start();
             require $resource;
             $resource = ob_get_contents();
             ob_end_flush();
         }
         $resource = file_get_contents($resource);
         return $options['expected_format'] === 'array' ? self::unserializeResource($resource) : $resource;
     }
     // - Resource is neither file nor URL
     return $resource;
 }
 public function testExcludeSourceUrlFromHistoryComparison()
 {
     $httpClient = new \Guzzle\Http\Client();
     $mockPlugin = new \Guzzle\Plugin\Mock\MockPlugin();
     $mockPlugin->addResponse(\Guzzle\Http\Message\Response::fromMessage('HTTP/1.1 301' . "\n" . 'Location: http://example.com/'));
     $mockPlugin->addResponse(\Guzzle\Http\Message\Response::fromMessage('HTTP/1.1 301' . "\n" . 'Location: http://example.com/2/'));
     $mockPlugin->addResponse(\Guzzle\Http\Message\Response::fromMessage('HTTP/1.1 301' . "\n" . 'Location: http://example.com/3/'));
     $mockPlugin->addResponse(\Guzzle\Http\Message\Response::fromMessage('HTTP/1.1 301' . "\n" . 'Location: http://example.com/4/'));
     $mockPlugin->addResponse(\Guzzle\Http\Message\Response::fromMessage('HTTP/1.1 301' . "\n" . 'Location: http://example.com/5/'));
     $httpClient->addSubscriber($mockPlugin);
     $detector = new \webignition\HttpRedirectLoopDetector\HttpRedirectLoopDetector();
     $detector->setHttpClient($httpClient);
     $detector->setUrl('https://example.com/');
     $this->assertFalse($detector->test());
 }