fromRequest example


  public function buildUi(MediaLibraryState $state = NULL) {
    if (!$state) {
      $state = MediaLibraryState::fromRequest($this->request);
    }
    // When navigating to a media type through the vertical tabs, we only want     // to load the changed library content. This is not only more efficient, but     // also provides a more accessible user experience for screen readers.     if ($state->get('media_library_content') === '1') {
      return $this->buildLibraryContent($state);
    }
    else {
      return [
        '#theme' => 'media_library_wrapper',
        '#attributes' => [
          

            )
            ->willReturnCallback(function D$method$url$options) use ($ipAddr$content): ResponseInterface {
                $info = [
                    'primary_ip' => $ipAddr,
                    'url' => $url,
                ];

                $onProgress = $options['on_progress'];
                $onProgress(0, 0, $info);

                return MockResponse::fromRequest($method$url[]new MockResponse($content));
            });

        return $previousHttpClient;
    }
}
$request = Request::create($request_path, 'GET', [][][]$server);
    // Ensure the request time is REQUEST_TIME to ensure that API calls     // in the test use the right timestamp.     $request->server->set('REQUEST_TIME', REQUEST_TIME);

    $this->container->get('request_stack')->push($request);
    // The request context is normally set by the router_listener from within     // its KernelEvents::REQUEST listener. In the parent site this event is not     // fired, therefore it is necessary to update the request context manually     // here.     $this->container->get('router.request_context')->fromRequest($request);

    return $request;
  }

  /** * Execute the non-interactive installer. * * @see install_drupal() */
  protected function doInstall() {
    require_once DRUPAL_ROOT . '/core/includes/install.core.inc';
    

                }
            }
        }

        $response = $this->cache->handle($request);
        $response = new MockResponse($response->getContent()[
            'http_code' => $response->getStatusCode(),
            'response_headers' => $response->headers->allPreserveCase(),
        ]);

        return MockResponse::fromRequest($method$url$options$response);
    }

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

        $mockResponses = [];
        $clientResponses = [];

        
    public function cancelSubscription(int $licenseId, Context $context): JsonResponse
    {
        $this->extensionStoreLicensesService->cancelSubscription($licenseId$context);

        return new JsonResponse(null, Response::HTTP_NO_CONTENT);
    }

    #[Route(path: '/api/license/rate/{extensionId}', name: 'api.license.rate', methods: ['POST'])]     public function rateLicensedExtension(int $extensionId, Request $request, Context $context): JsonResponse
    {
        $this->extensionStoreLicensesService->rateLicensedExtension(
            ReviewStruct::fromRequest($extensionId$request),
            $context
        );

        return new JsonResponse(null, Response::HTTP_NO_CONTENT);
    }
}

  protected $completeBaseUrl;

  /** * Populates the context from the current request from the request stack. * * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack * The current request stack. */
  public function fromRequestStack(RequestStack $request_stack) {
    $this->fromRequest($request_stack->getCurrentRequest());
  }

  /** * {@inheritdoc} */
  public function fromRequest(Request $request)static {
    // @todo Extract the code in DrupalKernel::initializeRequestGlobals.     // See https://www.drupal.org/node/2404601     if (isset($GLOBALS['base_url'])) {
      $this->setCompleteBaseUrl($GLOBALS['base_url']);
    }

    
/** * @after */
    public function resetRequestContext(): void
    {
        $router = $this->getContainer()
            ->get('router');

        $context = $router->getContext();

        $router->setContext($context->fromRequest(Request::create((string) EnvironmentHelper::getVariable('APP_URL'))));
    }

    abstract protected static function getContainer(): ContainerInterface;
}
 else {
            $responseFactory = $this->responseFactory->current();
            $response = \is_callable($responseFactory) ? $responseFactory($method$url$options) : $responseFactory;
            $this->responseFactory->next();
        }
        ++$this->requestsCount;

        if (!$response instanceof ResponseInterface) {
            throw new TransportException(sprintf('The response factory passed to MockHttpClient must return/yield an instance of ResponseInterface, "%s" given.', get_debug_type($response)));
        }

        return MockResponse::fromRequest($method$url$options$response);
    }

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

        return new ResponseStream(MockResponse::stream($responses$timeout));
    }

    
$this->context = $context ?? $matcher->getContext();
        $this->requestStack = $requestStack;
        $this->logger = $logger;
        $this->projectDir = $projectDir;
        $this->debug = $debug;
    }

    private function setCurrentRequest(?Request $request): void
    {
        if (null !== $request) {
            try {
                $this->context->fromRequest($request);
            } catch (\UnexpectedValueException $e) {
                throw new BadRequestHttpException($e->getMessage()$e$e->getCode());
            }
        }
    }

    /** * After a sub-request is done, we need to reset the routing context to the parent request so that the URL generator * operates on the correct context again. */
    public function onKernelFinishRequest(): void
    {

  public function __construct(CurrentPathStack $current_path) {
    $this->currentPath = $current_path;
  }

  public function finalMatch(RouteCollection $collection, Request $request) {
    $this->routes = $collection;
    $context = new RequestContext();
    $context->fromRequest($request);
    $this->setContext($context);

    return $this->match($this->currentPath->getPath($request));
  }

  /** * {@inheritdoc} */
  protected function getAttributes(Route $route$name, array $attributes): array {
    if ($route instanceof RouteObjectInterface && is_string($route->getRouteKey())) {
      $name = $route->getRouteKey();
    }
use Symfony\Component\HttpClient\Exception\TransportException;
use Symfony\Component\HttpClient\Response\MockResponse;

/** * Test methods from Symfony\Component\HttpClient\Response\*ResponseTrait. */
class MockResponseTest extends TestCase
{
    public function testTotalTimeShouldBeSimulatedWhenNotProvided()
    {
        $response = new MockResponse('body');
        $response = MockResponse::fromRequest('GET', 'https://example.com/file.txt', []$response);

        $this->assertNotNull($response->getInfo('total_time'));
        $this->assertGreaterThan(0.0, $response->getInfo('total_time'));
    }

    public function testTotalTimeShouldNotBeSimulatedWhenProvided()
    {
        $totalTime = 4.2;
        $response = new MockResponse('body', ['total_time' => $totalTime]);
        $response = MockResponse::fromRequest('GET', 'https://example.com/file.txt', []$response);

        

  public function testFromRequest(array $query_overrides$exception_expected) {
    // Override the query parameters and verify an exception is thrown when     // required state parameters are changed.     $query = MediaLibraryState::create('test', ['file', 'image'], 'image', 2)->all();
    $query = array_merge($query$query_overrides);
    if ($exception_expected) {
      $this->expectException(BadRequestHttpException::class);
      $this->expectExceptionMessage("Invalid media library parameters specified.");
    }

    $state = MediaLibraryState::fromRequest(new Request($query));
    $this->assertInstanceOf(MediaLibraryState::class$state);
  }

  /** * @covers ::fromRequest */
  public function testFromRequestQueryLess() {
    $this->expectException(\InvalidArgumentException::class);
    $this->expectExceptionMessage('The opener ID parameter is required and must be a string.');
    $state = MediaLibraryState::fromRequest(new Request());
    $this->assertInstanceOf(MediaLibraryState::class$state);
  }
$this->context = $context ?? $matcher->getContext();
        $this->requestStack = $requestStack;
        $this->logger = $logger;
        $this->projectDir = $projectDir;
        $this->debug = $debug;
    }

    private function setCurrentRequest(?Request $request): void
    {
        if (null !== $request) {
            try {
                $this->context->fromRequest($request);
            } catch (\UnexpectedValueException $e) {
                throw new BadRequestHttpException($e->getMessage()$e$e->getCode());
            }
        }
    }

    /** * After a sub-request is done, we need to reset the routing context to the parent request so that the URL generator * operates on the correct context again. */
    public function onKernelFinishRequest(): void
    {
$this->assertSame('http', $requestContext->getScheme());
        $this->assertSame('localhost', $requestContext->getHost());
        $this->assertSame('', $requestContext->getBaseUrl());
        $this->assertSame('/', $requestContext->getPathInfo());
    }

    public function testFromRequest()
    {
        $request = Request::create('https://test.com:444/foo?bar=baz');
        $requestContext = new RequestContext();
        $requestContext->setHttpPort(123);
        $requestContext->fromRequest($request);

        $this->assertEquals('', $requestContext->getBaseUrl());
        $this->assertEquals('GET', $requestContext->getMethod());
        $this->assertEquals('test.com', $requestContext->getHost());
        $this->assertEquals('https', $requestContext->getScheme());
        $this->assertEquals('/foo', $requestContext->getPathInfo());
        $this->assertEquals('bar=baz', $requestContext->getQueryString());
        $this->assertSame(123, $requestContext->getHttpPort());
        $this->assertSame(444, $requestContext->getHttpsPort());

        $request = Request::create('http://test.com:8080/foo?bar=baz');
        
$parameters = [
            'user' => $user->getUserIdentifier(),
            'expires' => $expires,
            'hash' => $this->signatureHasher->computeSignatureHash($user$expires),
        ];

        if ($request) {
            $currentRequestContext = $this->urlGenerator->getContext();
            $this->urlGenerator->setContext(
                (new RequestContext())
                    ->fromRequest($request)
                    ->setParameter('_locale', $request->getLocale())
            );
        }

        try {
            $url = $this->urlGenerator->generate(
                $this->options['route_name'],
                $parameters,
                UrlGeneratorInterface::ABSOLUTE_URL
            );
        } finally {
            
Home | Imprint | This part of the site doesn't use cookies.