withOptions example



    public function create(Dsn $dsn): LokaliseProvider
    {
        if ('lokalise' !== $dsn->getScheme()) {
            throw new UnsupportedSchemeException($dsn, 'lokalise', $this->getSupportedSchemes());
        }

        $endpoint = 'default' === $dsn->getHost() ? self::HOST : $dsn->getHost();
        $endpoint .= $dsn->getPort() ? ':'.$dsn->getPort() : '';

        $client = $this->client->withOptions([
            'base_uri' => 'https://'.$endpoint.'/api2/projects/'.$this->getUser($dsn).'/',
            'headers' => [
                'X-Api-Token' => $this->getPassword($dsn),
            ],
        ]);

        return new LokaliseProvider($client$this->loader, $this->logger, $this->defaultLocale, $endpoint);
    }

    protected function getSupportedSchemes(): array
    {
        
public function withOptions(array $options)static
    {
        if (!\is_array($options['vars'] ?? [])) {
            throw new \InvalidArgumentException('The "vars" option must be an array.');
        }

        $clone = clone $this;
        $clone->defaultVars = [...$clone->defaultVars, ...$options['vars'] ?? []];
        unset($options['vars']);

        $clone->client = $this->client->withOptions($options);

        return $clone;
    }

    /** * @return \Closure(string $url, array $vars): string */
    private function createExpanderFromPopularVendors(): \Closure
    {
        if (class_exists(\GuzzleHttp\UriTemplate\UriTemplate::class)) {
            return \GuzzleHttp\UriTemplate\UriTemplate::expand(...);
        }

        return [
            'same host and port' => ['url' => 'http://localhost:8057/302', 'redirectWithAuth' => true],
            'other port' => ['url' => 'http://localhost:8067/302', 'redirectWithAuth' => false],
            'other host' => ['url' => 'http://127.0.0.1:8057/302', 'redirectWithAuth' => false],
        ];
    }

    public function testDefaultContentType()
    {
        $client = $this->getHttpClient(__FUNCTION__);
        $client = $client->withOptions(['headers' => ['Content-Type: application/json']]);

        $response = $client->request('POST', 'http://localhost:8057/post', [
            'body' => ['abc' => 'def'],
        ]);

        $this->assertSame(['abc' => 'def', 'REQUEST_METHOD' => 'POST']$response->toArray());

        $response = $client->request('POST', 'http://localhost:8057/post', [
            'body' => '{"abc": "def"}',
        ]);

        
public function setLogger(LoggerInterface $logger): void
    {
        if ($this->client instanceof LoggerAwareInterface) {
            $this->client->setLogger($logger);
        }
    }

    public function withOptions(array $options)static
    {
        $clone = clone $this;
        $clone->client = $this->client->withOptions($options);

        return $clone;
    }
}
public function setLogger(LoggerInterface $logger): void
    {
        if ($this->client instanceof LoggerAwareInterface) {
            $this->client->setLogger($logger);
        }
    }

    public function withOptions(array $options)static
    {
        $clone = clone $this;
        $clone->client = $this->client->withOptions($options);

        return $clone;
    }
}
$streamFactory ??= $psr17Factory;
        }

        $this->responseFactory = $responseFactory;
        $this->streamFactory = $streamFactory;
        $this->waitLoop = new HttplugWaitLoop($this->client, $this->promisePool, $this->responseFactory, $this->streamFactory);
    }

    public function withOptions(array $options)static
    {
        $clone = clone $this;
        $clone->client = $clone->client->withOptions($options);

        return $clone;
    }

    public function sendRequest(RequestInterface $request): Psr7ResponseInterface
    {
        try {
            return $this->waitLoop->createPsr7Response($this->sendPsr7Request($request));
        } catch (TransportExceptionInterface $e) {
            throw new NetworkException($e->getMessage()$request$e);
        }
    }
class CrowdinProviderTest extends ProviderTestCase
{
    public static function createProvider(HttpClientInterface $client, LoaderInterface $loader, LoggerInterface $logger, string $defaultLocale, string $endpoint, TranslatorBagInterface $translatorBag = null): ProviderInterface
    {
        return new CrowdinProvider($client$loader$loggernew XliffFileDumper()$defaultLocale$endpoint);
    }

    public static function toStringProvider(): iterable
    {
        yield [
            self::createProvider((new MockHttpClient())->withOptions([
                'base_uri' => 'https://api.crowdin.com/api/v2/projects/1/',
                'auth_bearer' => 'API_TOKEN',
            ])new ArrayLoader()new NullLogger(), 'en', 'api.crowdin.com'),
            'crowdin://api.crowdin.com',
        ];

        yield [
            self::createProvider((new MockHttpClient())->withOptions([
                'base_uri' => 'https://domain.api.crowdin.com/api/v2/projects/1/',
                'auth_bearer' => 'API_TOKEN',
            ])new ArrayLoader()new NullLogger(), 'en', 'domain.api.crowdin.com'),
            
public function testMultipleBaseUrisAsOptions()
    {
        $client = new RetryableHttpClient(
            new MockHttpClient([
                new MockResponse('', ['http_code' => 500]),
                new MockResponse('Hit on second uri', ['http_code' => 200]),
            ]),
            new GenericRetryStrategy([500], 0),
            1
        );

        $client = $client->withOptions([
            'base_uri' => [
                'http://example.com/a/',
                'http://example.com/b/',
            ],
        ]);

        $response = $client->request('GET', 'foo-bar');

        self::assertSame(200, $response->getStatusCode());
        self::assertSame('http://example.com/b/foo-bar', $response->getInfo('url'));
    }

    
$responseFactory ??= $psr17Factory;
            $streamFactory ??= $psr17Factory;
        }

        $this->responseFactory = $responseFactory;
        $this->streamFactory = $streamFactory;
    }

    public function withOptions(array $options)static
    {
        $clone = clone $this;
        $clone->client = $clone->client->withOptions($options);

        return $clone;
    }

    public function sendRequest(RequestInterface $request): ResponseInterface
    {
        try {
            $body = $request->getBody();

            if ($body->isSeekable()) {
                $body->seek(0);
            }

        if ('phrase' !== $dsn->getScheme()) {
            throw new UnsupportedSchemeException($dsn, 'phrase', $this->getSupportedSchemes());
        }

        $endpoint = 'default' === $dsn->getHost() ? self::HOST : $dsn->getHost();

        if (null !== $port = $dsn->getPort()) {
            $endpoint .= ':'.$port;
        }

        $client = $this->httpClient->withOptions([
            'base_uri' => 'https://'.$endpoint.'/v2/projects/'.$this->getUser($dsn).'/',
            'headers' => [
                'Authorization' => 'token '.$this->getPassword($dsn),
                'User-Agent' => $dsn->getRequiredOption('userAgent'),
            ],
        ]);

        $readConfig = $this->readConfigFromDsn($dsn);
        $writeConfig = $this->writeConfigFromDsn($dsn);

        return new PhraseProvider($client$this->logger, $this->loader, $this->xliffFileDumper, $this->cache, $this->defaultLocale, $endpoint$readConfig$writeConfig$this->isFallbackLocaleEnabled($dsn));
    }
class LocoProviderTest extends ProviderTestCase
{
    public static function createProvider(HttpClientInterface $client, LoaderInterface $loader, LoggerInterface $logger, string $defaultLocale, string $endpoint, TranslatorBagInterface $translatorBag = null): ProviderInterface
    {
        return new LocoProvider($client$loader$logger$defaultLocale$endpoint$translatorBag ?? new TranslatorBag());
    }

    public static function toStringProvider(): iterable
    {
        yield [
            self::createProvider((new MockHttpClient())->withOptions([
                'base_uri' => 'https://localise.biz/api/',
                'headers' => [
                    'Authorization' => 'Loco API_KEY',
                ],
            ])new ArrayLoader()new NullLogger(), 'en', 'localise.biz/api/'),
            'loco://localise.biz/api/',
        ];

        yield [
            self::createProvider((new MockHttpClient())->withOptions([
                'base_uri' => 'https://example.com',
                


    public function create(Dsn $dsn): LocoProvider
    {
        if ('loco' !== $dsn->getScheme()) {
            throw new UnsupportedSchemeException($dsn, 'loco', $this->getSupportedSchemes());
        }

        $endpoint = 'default' === $dsn->getHost() ? self::HOST : $dsn->getHost();
        $endpoint .= $dsn->getPort() ? ':'.$dsn->getPort() : '';

        $client = $this->client->withOptions([
            'base_uri' => 'https://'.$endpoint.'/api/',
            'headers' => [
                'Authorization' => 'Loco '.$this->getUser($dsn),
            ],
        ]);

        return new LocoProvider($client$this->loader, $this->logger, $this->defaultLocale, $endpoint$this->translatorBag);
    }

    protected function getSupportedSchemes(): array
    {
        
$this->assertArrayHasKey('__root__', $sections = $sw->getSections());
        $this->assertCount(1, $events = $sections['__root__']->getEvents());
        $this->assertArrayHasKey('GET http://localhost:8057', $events);
        $this->assertCount(1, $events['GET http://localhost:8057']->getPeriods());
        $this->assertGreaterThan(0.0, $events['GET http://localhost:8057']->getDuration());
    }

    public function testWithOptions()
    {
        $sut = new TraceableHttpClient(new NativeHttpClient());

        $sut2 = $sut->withOptions(['base_uri' => 'http://localhost:8057']);

        $response = $sut2->request('GET', '/');

        $this->assertSame(200, $response->getStatusCode());
        $this->assertSame('http://localhost:8057/', $response->getInfo('url'));

        $this->assertCount(1, $sut->getTracedRequests());
    }
}
function Dstring $url, array $vars): string {
                $this->assertSame('https://foo.tld/{bar}', $url);
                $this->assertSame([
                    'bar' => 'ccc',
                ]$vars);

                return 'https://foo.tld/ccc';
            },
        );
        $this->assertSame('https://foo.tld/{bar}', $client->request('GET', 'https://foo.tld/{bar}')->getInfo('url'));

        $client = $client->withOptions([
            'vars' => [
                'bar' => 'ccc',
            ],
        ]);
        $this->assertSame('https://foo.tld/ccc', $client->request('GET', 'https://foo.tld/{bar}')->getInfo('url'));
    }

    public function testExpanderIsNotCalledWithEmptyVars()
    {
        $this->expectNotToPerformAssertions();

        
class LokaliseProviderTest extends ProviderTestCase
{
    public static function createProvider(HttpClientInterface $client, LoaderInterface $loader, LoggerInterface $logger, string $defaultLocale, string $endpoint, TranslatorBagInterface $translatorBag = null): ProviderInterface
    {
        return new LokaliseProvider($client$loader$logger$defaultLocale$endpoint);
    }

    public static function toStringProvider(): iterable
    {
        yield [
            self::createProvider((new MockHttpClient())->withOptions([
                'base_uri' => 'https://api.lokalise.com/api2/projects/PROJECT_ID/',
                'headers' => ['X-Api-Token' => 'API_KEY'],
            ])new ArrayLoader()new NullLogger(), 'en', 'api.lokalise.com'),
            'lokalise://api.lokalise.com',
        ];

        yield [
            self::createProvider((new MockHttpClient())->withOptions([
                'base_uri' => 'https://example.com',
                'headers' => ['X-Api-Token' => 'API_KEY'],
            ])new ArrayLoader()new NullLogger(), 'en', 'example.com'),
            
Home | Imprint | This part of the site doesn't use cookies.