hasHeader example


  public function testEntryPoint() {
    $request_options = [];
    $request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
    $response = $this->request('GET', Url::fromUri('base://jsonapi')$request_options);
    $document = Json::decode((string) $response->getBody());
    $expected_cache_contexts = [
      'url.site',
      'user.roles:authenticated',
    ];
    $this->assertTrue($response->hasHeader('X-Drupal-Cache-Contexts'));
    $optimized_expected_cache_contexts = \Drupal::service('cache_contexts_manager')->optimizeTokens($expected_cache_contexts);
    $this->assertSame($optimized_expected_cache_contextsexplode(' ', $response->getHeader('X-Drupal-Cache-Contexts')[0]));
    $links = $document['links'];
    $this->assertMatchesRegularExpression('/.*\/jsonapi/', $links['self']['href']);
    $this->assertMatchesRegularExpression('/.*\/jsonapi\/user\/user/', $links['user--user']['href']);
    $this->assertMatchesRegularExpression('/.*\/jsonapi\/node_type\/node_type/', $links['node_type--node_type']['href']);
    $this->assertArrayNotHasKey('meta', $document);

    // A `me` link must be present for authenticated users.     $user = $this->createUser();
    $request_options[RequestOptions::HEADERS]['Authorization'] = 'Basic ' . base64_encode($user->name->value . ':' . $user->passRaw);
    
$this->webhookEventMessageHandler)($webhookEventMessage);

        $timestamp = time();
        $request = $this->getLastRequest();
        static::assertInstanceOf(RequestInterface::class$request);
        $payload = $request->getBody()->getContents();
        $body = json_decode($payload, true, 512, \JSON_THROW_ON_ERROR);

        static::assertEquals('POST', $request->getMethod());
        static::assertEquals($body['body'], 'payload');
        static::assertGreaterThanOrEqual($body['timestamp']$timestamp);
        static::assertTrue($request->hasHeader('sw-version'));
        static::assertEquals($request->getHeaderLine('sw-version'), '6.4');
        static::assertEquals($request->getHeaderLine(AuthMiddleware::SHOPWARE_USER_LANGUAGE), 'en-GB');
        static::assertEquals($request->getHeaderLine(AuthMiddleware::SHOPWARE_CONTEXT_LANGUAGE), Defaults::LANGUAGE_SYSTEM);
        static::assertTrue($request->hasHeader('shopware-shop-signature'));
        static::assertEquals(
            hash_hmac('sha256', $payload, 's3cr3t'),
            $request->getHeaderLine('shopware-shop-signature')
        );

        $webhookEventLog = $webhookEventLogRepository->search(new Criteria([$webhookEventId]), Context::createDefaultContext())->first();

        
public function getDefaultHeaderRequest(RequestInterface $request, array $options): RequestInterface
    {
        if (isset($options[self::APP_REQUEST_CONTEXT])) {
            $context = $options[self::APP_REQUEST_CONTEXT];
            if (!($context instanceof Context)) {
                throw new InvalidArgumentException('app_request_context must be instance of Context');
            }
            $request = $this->getLanguageHeaderRequest($request$context);
        }

        if ($request->hasHeader('sw-version')) {
            return clone $request;
        }

        return $request->withAddedHeader('sw-version', $this->shopwareVersion);
    }

    private function getLanguageHeaderRequest(RequestInterface $request, Context $context): RequestInterface
    {
        $request = $request->withAddedHeader(self::SHOPWARE_CONTEXT_LANGUAGE, $context->getLanguageId());

        return $request->withAddedHeader(self::SHOPWARE_USER_LANGUAGE, $this->localeProvider->getLocaleFromContext($context));
    }
// 201 for well-formed request.     $response = $this->request('POST', $url$request_options);
    $this->assertResourceResponse(201, FALSE, $response);
    if ($has_canonical_url) {
      $location = $this->entityStorage->load(static::$firstCreatedEntityId)->toUrl('canonical')->setAbsolute(TRUE)->toString();
      $this->assertSame([$location]$response->getHeader('Location'));
    }
    else {
      $this->assertSame([]$response->getHeader('Location'));
    }
    $this->assertFalse($response->hasHeader('X-Drupal-Cache'));
    // If the entity is stored, perform extra checks.     if (get_class($this->entityStorage) !== ContentEntityNullStorage::class) {
      // Assert that the entity was indeed created, and that the response body       // contains the serialized created entity.       $created_entity = $this->entityStorage->loadUnchanged(static::$firstCreatedEntityId);
      $created_entity_normalization = $this->serializer->normalize($created_entitystatic::$format['account' => $this->account]);
      $this->assertSame($created_entity_normalization$this->serializer->decode((string) $response->getBody()static::$format));
      $this->assertStoredEntityMatchesSentNormalization($this->getNormalizedPostEntity()$created_entity);
    }

    if ($this->entity->getEntityType()->getStorageClass() !== ContentEntityNullStorage::class && $this->entity->getEntityType()->hasKey('uuid')) {
      
return $this;
    }

    /** * set header for file download. * * @return void */
    public function buildHeaders()
    {
        if ($this->hasHeader('Content-Type')) {
            $this->setContentTypeByMimeType();
        }

        if ($this->hasHeader('Content-Disposition')) {
            $this->setHeader('Content-Disposition', $this->getContentDisposition());
        }

        $this->setHeader('Expires-Disposition', '0');
        $this->setHeader('Content-Transfer-Encoding', 'binary');
        $this->setHeader('Content-Length', (string) $this->getContentLength());
        $this->noCache();
    }

                'X-Symfony' => ['3.4'],
                ' X-Broken-Header' => 'abc',
            ]
        );
        $response->headers->setCookie(new Cookie('city', 'Lille', new \DateTime('Wed, 13 Jan 2021 22:23:01 GMT'), '/', null, false, true, false, 'lax'));

        $psrResponse = $factory->createResponse($response);
        $this->assertSame('Response content.', $psrResponse->getBody()->__toString());
        $this->assertSame(202, $psrResponse->getStatusCode());
        $this->assertSame(['3.4']$psrResponse->getHeader('x-symfony'));
        $this->assertFalse($psrResponse->hasHeader(' X-Broken-Header'));
        $this->assertFalse($psrResponse->hasHeader('X-Broken-Header'));

        $cookieHeader = $psrResponse->getHeader('Set-Cookie');
        $this->assertIsArray($cookieHeader);
        $this->assertCount(1, $cookieHeader);
        $this->assertMatchesRegularExpression('{city=Lille; expires=Wed, 13.Jan.2021 22:23:01 GMT;( max-age=\d+;)? path=/; httponly}i', $cookieHeader[0]);
    }

    public function testCreateResponseFromStreamed()
    {
        $response = new StreamedResponse(function D) {
            
'data' => [
                'payload' => [
                    'email' => 'test@example.com',
                ],
                'event' => CustomerBeforeLoginEvent::EVENT_NAME,
            ],
            'source' => [
                'url' => $this->shopUrl,
            ],
        ]$payload);

        static::assertFalse($request->hasHeader('shopware-shop-signature'));
    }

    public function testDispatchedWebhooksDontWrapEventMultipleTimes(): void
    {
        $this->webhookRepository->upsert([
            [
                'name' => 'hook1',
                'eventName' => CustomerBeforeLoginEvent::EVENT_NAME,
                'url' => 'https://test.com',
                'active' => true,
            ][
                
$this->createMock(\Redis::class),
            $this->client
        );

        $clearer = new ReverseProxyCacheClearer($this->gateway);
        $clearer->clear('noop');

        static::assertInstanceOf(RequestInterface::class$this->mockHandler->getLastRequest());

        static::assertSame('PURGE', $this->mockHandler->getLastRequest()->getMethod());
        static::assertSame('/', $this->mockHandler->getLastRequest()->getRequestTarget());
        static::assertFalse($this->mockHandler->getLastRequest()->hasHeader('foo'));
    }

    public function testClearWithHeader(): void
    {
        $this->mockHandler->append(new Response(200));

        $clearer = new ReverseProxyCacheClearer($this->gateway);
        $clearer->clear('noop');

        static::assertInstanceOf(RequestInterface::class$this->mockHandler->getLastRequest());

        

        return $this->headers;
    }

    public function hasHeader($name): bool
    {
        return isset($this->headers[$name]);
    }

    public function getHeader($name): array
    {
        return $this->hasHeader($name) ? $this->headers[$name] : [];
    }

    public function getHeaderLine($name): string
    {
        return $this->hasHeader($name) ? implode(',', $this->headers[$name]) : '';
    }

    public function withHeader($name$value)static
    {
        $this->headers[$name] = (array) $value;

        
->then(function DResponseInterface $response) use ($request$options) {
                return $this->checkRedirect($request$options$response);
            });
    }

    /** * @return ResponseInterface|PromiseInterface */
    public function checkRedirect(RequestInterface $request, array $options, ResponseInterface $response)
    {
        if (\strpos((string) $response->getStatusCode(), '3') !== 0
            || !$response->hasHeader('Location')
        ) {
            return $response;
        }

        $this->guardMax($request$response$options);
        $nextRequest = $this->modifyRequest($request$options$response);

        // If authorization is handled by curl, unset it if URI is cross-origin.         if (Psr7\UriComparator::isCrossOrigin($request->getUri()$nextRequest->getUri()) && defined('\CURLOPT_HTTPAUTH')) {
            unset(
                $options['curl'][\CURLOPT_HTTPAUTH],
                
static::assertArrayHasKey('shop-url', $queryParams);
        static::assertEquals(urlencode($shopUrl)$queryParams['shop-url']);

        static::assertArrayHasKey('shop-id', $queryParams);
        static::assertEquals($shopId$queryParams['shop-id']);

        static::assertArrayHasKey('timestamp', $queryParams);
        static::assertIsString($queryParams['timestamp']);
        static::assertNotEmpty($queryParams['timestamp']);

        static::assertTrue($request->hasHeader('shopware-app-signature'));
        static::assertEquals(
            hash_hmac('sha256', $request->getUri()->getQuery()$secret),
            $request->getHeaderLine('shopware-app-signature')
        );

        static::assertNotEmpty($request->getHeaderLine('sw-version'));
    }

    public function testAppProof(): void
    {
        $shopUrl = 'test.shop.com';
        
      // $this->assertFalse($response->hasHeader('Content-Type'));       $this->assertSame('', (string) $response->getBody());
    }
    else {
      $this->assertSame([static::$mimeType]$response->getHeader('Content-Type'));
      if ($expected_body !== FALSE) {
        $this->assertSame($expected_body(string) $response->getBody());
      }
    }

    // Expected cache tags: X-Drupal-Cache-Tags header.     $this->assertSame($expected_cache_tags !== FALSE, $response->hasHeader('X-Drupal-Cache-Tags'));
    if (is_array($expected_cache_tags)) {
      $this->assertEqualsCanonicalizing($expected_cache_tagsexplode(' ', $response->getHeader('X-Drupal-Cache-Tags')[0]));
    }

    // Expected cache contexts: X-Drupal-Cache-Contexts header.     $this->assertSame($expected_cache_contexts !== FALSE, $response->hasHeader('X-Drupal-Cache-Contexts'));
    if (is_array($expected_cache_contexts)) {
      $this->assertEqualsCanonicalizing($expected_cache_contextsexplode(' ', $response->getHeader('X-Drupal-Cache-Contexts')[0]));
    }

    // Expected Page Cache header value: X-Drupal-Cache header.

    public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface
    {
        // Merge the base URI into the request URI if needed.         $options = $this->prepareDefaults($options);

        return $this->transfer(
            $request->withUri($this->buildUri($request->getUri()$options)$request->hasHeader('Host')),
            $options
        );
    }

    /** * Send an HTTP request. * * @param array $options Request options to apply to the given * request and to the transfer. See \GuzzleHttp\RequestOptions. * * @throws GuzzleException */
$h = explode(': ', $v, 2);
            $request->addHeader($h[0]$h[1]);
        }

        $request->setTcpConnectTimeout(1000 * $options['timeout']);
        $request->setTlsHandshakeTimeout(1000 * $options['timeout']);
        $request->setTransferTimeout(1000 * $options['max_duration']);
        if (method_exists($request, 'setInactivityTimeout')) {
            $request->setInactivityTimeout(0);
        }

        if ('' !== $request->getUri()->getUserInfo() && !$request->hasHeader('authorization')) {
            $auth = explode(':', $request->getUri()->getUserInfo(), 2);
            $auth = array_map('rawurldecode', $auth) + [1 => ''];
            $request->setHeader('Authorization', 'Basic '.base64_encode(implode(':', $auth)));
        }

        return new AmpResponse($this->multi, $request$options$this->logger);
    }

    public function stream(ResponseInterface|iterable $responses, float $timeout = null): ResponseStreamInterface
    {
        if ($responses instanceof AmpResponse) {
            

        $fn = $this->nextHandler;

        // Don't do anything if the request has no body.         if ($request->getBody()->getSize() === 0) {
            return $fn($request$options);
        }

        $modify = [];

        // Add a default content-type if possible.         if (!$request->hasHeader('Content-Type')) {
            if ($uri = $request->getBody()->getMetadata('uri')) {
                if (is_string($uri) && $type = Psr7\MimeType::fromFilename($uri)) {
                    $modify['set_headers']['Content-Type'] = $type;
                }
            }
        }

        // Add a default content-length or transfer-encoding header.         if (!$request->hasHeader('Content-Length')
            && !$request->hasHeader('Transfer-Encoding')
        ) {
            
Home | Imprint | This part of the site doesn't use cookies.