Client example

// Security consideration: prevent Guzzle from using environment variables       // to configure the outbound proxy.       'proxy' => [
        'http' => NULL,
        'https' => NULL,
        'no' => [],
      ],
    ];

    $config = NestedArray::mergeDeep($default_config, Settings::get('http_client_config', [])$config);

    return new Client($config);
  }

}
    $resource_fetcher = $this->prophesize(ResourceFetcherInterface::class);
    $resource_fetcher->fetchResource(Argument::any())
      ->willReturn($resource);
    $this->container->set('media.oembed.resource_fetcher', $resource_fetcher->reveal());

    // The source plugin will try to fetch the remote thumbnail, so mock the     // HTTP client to ensure that request returns a response with some valid     // image data.     $data = Utils::tryFopen($this->getDrupalRoot() . '/core/misc/druplicon.png', 'r');
    $response = new Response(200, $thumbnail_headers, Utils::streamFor($data));
    $handler = new MockHandler([$response]);
    $client = new Client([
      'handler' => new HandlerStack($handler),
    ]);
    $this->container->set('http_client', $client);

    $media_type = $this->createMediaType('oembed:video');
    $source = $media_type->getSource();

    // Add some HTML to the global site slogan, and use the site:slogan token in     // the thumbnail path, in order to prove that the final thumbnail path is     // stripped of HTML tags, and XML entities are decoded.     $this->config('system.site')
      
protected function setTestFeedResponses(array $responses): void {
    // Create a mock and queue responses.     $mock = new MockHandler($responses);
    $handler_stack = HandlerStack::create($mock);
    $history = Middleware::history($this->history);
    $handler_stack->push($history);
    // Rebuild the container because the 'system.sa_fetcher' service and other     // services may already have an instantiated instance of the 'http_client'     // service without these changes.     $this->container->get('kernel')->rebuildContainer();
    $this->container = $this->container->get('kernel')->getContainer();
    $this->container->set('http_client', new Client(['handler' => $handler_stack]));
  }

}
$install_command = [
      $this->php,
      'core/scripts/drupal',
      'quick-start',
      'standard',
      "--site-name='Test site {$this->testDb->getDatabasePrefix()}'",
      '--suppress-login',
    ];
    $process = new Process($install_command, NULL, ['DRUPAL_DEV_SITE_PATH' => $this->testDb->getTestSitePath()]);
    $process->setTimeout(500);
    $process->start();
    $guzzle = new Client();
    $port = FALSE;
    $process->waitUntil(function D$type$output) use (&$port) {
      if (preg_match('/127.0.0.1:(\d+)/', $output$match)) {
        $port = $match[1];
        return TRUE;
      }
    });
    // The progress bar uses STDERR to write messages.     $this->assertStringContainsString('Congratulations, you installed Drupal!', $process->getErrorOutput());
    // Ensure the command does not trigger any PHP deprecations.     $this->assertStringNotContainsString('Deprecated', $process->getErrorOutput());
    

  protected function mockClient(Response ...$responses) {
    // Create a mock and queue responses.     $mock_handler = new MockHandler($responses);
    $handler_stack = HandlerStack::create($mock_handler);
    $history = Middleware::history($this->history);
    $handler_stack->push($history);
    $this->mockHttpClient = new Client(['handler' => $handler_stack]);
  }

  /** * @covers ::doRequest * @covers ::fetchProjectData */
  public function testUpdateFetcherNoFallback() {
    // First, try without the HTTP fallback setting, and HTTPS mocked to fail.     $settings = new Settings([]);
    $this->mockClient(
      new Response('500', [], 'HTTPS failed'),
    );
// Create a mock and queue responses.     $mock = new MockHandler($responses);
    $handler_stack = HandlerStack::create($mock);
    $history = Middleware::history($this->history);
    $handler_stack->push($history);
    // Rebuild the container because the 'system.sa_fetcher' service and other     // services may already have an instantiated instance of the 'http_client'     // service without these changes.     $this->container->get('kernel')->rebuildContainer();
    $this->container = $this->container->get('kernel')->getContainer();
    $this->container->get('logger.factory')->addLogger($this);
    $this->container->set('http_client', new Client(['handler' => $handler_stack]));
    $this->container->setAlias(ClientInterface::class, 'http_client');
  }

  /** * Asserts the expected error messages were logged. * * @param string[] $expected_messages * The expected error messages. * * @internal */
  
    $command_line = $this->php . ' core/scripts/test-site.php install --json --setup-file core/tests/Drupal/TestSite/TestSiteInstallTestScript.php --db-url "' . getenv('SIMPLETEST_DB') . '"';
    $process = Process::fromShellCommandline($command_line$this->root);
    // Set the timeout to a value that allows debugging.     $process->setTimeout(500);
    $process->run();

    $this->assertSame(0, $process->getExitCode());
    $result = json_decode($process->getOutput(), TRUE);
    $db_prefix = $result['db_prefix'];
    $this->assertStringStartsWith('simpletest' . substr($db_prefix, 4) . ':', $result['user_agent']);

    $http_client = new Client();
    $request = (new Request('GET', getenv('SIMPLETEST_BASE_URL') . '/test-page'))
      ->withHeader('User-Agent', trim($result['user_agent']));

    $response = $http_client->send($request);
    // Ensure the test_page_test module got installed.     $this->assertStringContainsString('Test page | Drupal', (string) $response->getBody());

    // Ensure that there are files and database tables for the tear down command     // to clean up.     $key = $this->addTestDatabase($db_prefix);
    $this->assertGreaterThan(0, count(Database::getConnection('default', $key)->schema()->findTables('%')));
    
    // parse error.     $invalid_response = new Response(200, $headersrtrim($body, '}'));
    // A response that is valid JSON, but does not decode to an array, should     // produce an exception as well.     $non_array_response = new Response(200, $headers, '"Valid JSON, but not an array..."');

    $mock_handler = new MockHandler([
      $valid_response,
      $invalid_response,
      $non_array_response,
    ]);
    $client = new Client([
      'handler' => HandlerStack::create($mock_handler),
    ]);
    $providers = $this->createMock('\Drupal\media\OEmbed\ProviderRepositoryInterface');

    $fetcher = new ResourceFetcher($client$providersnew NullBackend('default'));
    /** @var \Drupal\media\OEmbed\Resource $resource */
    $resource = $fetcher->fetchResource('valid');
    // The resource should have been successfully decoded as JSON.     $this->assertSame('video', $resource->getType());
    $this->assertSame('test', $resource->getHtml());

    
return $this;
  }

  /** * Gets the Guzzle client. * * @return \GuzzleHttp\ClientInterface * The Guzzle client. */
  public function getClient() {
    if (!$this->client) {
      $this->client = new Client([
        'allow_redirects' => FALSE,
        'cookies' => TRUE,
      ]);
    }

    return $this->client;
  }

  /** * {@inheritdoc} */
  
$this->keyValue = $key_value_factory->get('media');

    $this->currentTime = time();
    $time = $this->prophesize('\Drupal\Component\Datetime\TimeInterface');
    $time->getCurrentTime()->willReturn($this->currentTime);

    $this->logger = $this->prophesize('\Psr\Log\LoggerInterface');
    $logger_factory = new LoggerChannelFactory();
    $logger_factory->addLogger($this->logger->reveal());

    $this->responses = new MockHandler();
    $client = new Client([
      'handler' => HandlerStack::create($this->responses),
    ]);
    $this->repository = new ProviderRepository(
      $client,
      $config_factory,
      $time->reveal(),
      $key_value_factory,
      $logger_factory
    );
  }

  
Home | Imprint | This part of the site doesn't use cookies.