buildUrl example

// Early opt-out if the field is empty.       return $elements;
    }

    /** @var \Drupal\image\ImageStyleInterface $image_style */
    $image_style = $this->imageStyleStorage->load($this->getSetting('image_style'));
    /** @var \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator */
    $file_url_generator = \Drupal::service('file_url_generator');
    /** @var \Drupal\file\FileInterface[] $images */
    foreach ($images as $delta => $image) {
      $image_uri = $image->getFileUri();
      $url = $image_style ? $file_url_generator->transformRelative($image_style->buildUrl($image_uri)) : $file_url_generator->generateString($image_uri);

      // Add cacheability metadata from the image and image style.       $cacheability = CacheableMetadata::createFromObject($image);
      if ($image_style) {
        $cacheability->addCacheableDependency(CacheableMetadata::createFromObject($image_style));
      }

      $elements[$delta] = ['#markup' => $url];
      $cacheability->applyTo($elements[$delta]);
    }
    return $elements;
  }

        'input' => 'javascript:alert(0)',
        'output' => 'javascript:alert(0)',
        'message' => 'JavaScript URL is allowed because it is treated as an internal URL.',
      ],
    ];
    foreach ($test_cases as $test_case) {
      // Test $_GET['destination'].       $this->drupalGet('system-test/get-destination', ['query' => ['destination' => $test_case['input']]]);
      $this->assertSame($test_case['output']$session->getPage()->getContent()$test_case['message']);
      // Test $_REQUEST['destination'].       $post_output = $http_client->request('POST', $this->buildUrl('system-test/request-destination')[
        'form_params' => ['destination' => $test_case['input']],
      ]);
      $this->assertSame($test_case['output'](string) $post_output->getBody()$test_case['message']);
    }

    // Make sure that 404 pages do not populate $_GET['destination'] with     // external URLs.     \Drupal::configFactory()->getEditable('system.site')->set('page.404', '/system-test/get-destination')->save();
    $this->drupalGet('http://example.com', ['external' => FALSE]);
    $this->assertSession()->statusCodeEquals(404);
    $this->assertSame(Url::fromRoute('<front>')->toString()$session->getPage()->getContent(), 'External URL is not allowed on 404 pages.');
  }
    $large_style = ImageStyle::load('large');
    $large_style->createDerivative($image_uri$large_style->buildUri($image_uri));

    // Output should contain all image styles and all breakpoints.     $this->drupalGet('node/' . $nid);
    if (!$empty_styles) {
      $this->assertSession()->responseContains('/styles/medium/');
      // Assert the empty image is present.       $this->assertSession()->responseContains('data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==');
      $thumbnail_style = ImageStyle::load('thumbnail');
      // Assert the output of the 'srcset' attribute (small multipliers first).       $this->assertSession()->responseContains('data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== 1x, ' . $this->fileUrlGenerator->transformRelative($thumbnail_style->buildUrl($image_uri)) . ' 1.5x');
      $this->assertSession()->responseContains('/styles/medium/');
      // Assert the output of the original image.       $this->assertSession()->responseContains($this->fileUrlGenerator->generateString($image_uri) . ' 3x');
      // Assert the output of the breakpoints.       $this->assertSession()->responseContains('media="(min-width: 0px)"');
      $this->assertSession()->responseContains('media="(min-width: 560px)"');
      // Assert the output of the 'sizes' attribute.       $this->assertSession()->responseContains('sizes="(min-width: 700px) 700px, 100vw"');
      $this->assertSession()->responseMatches('/media="\(min-width: 560px\)".+?sizes="\(min-width: 700px\) 700px, 100vw"/');
      // Assert the output of the 'srcset' attribute (small images first).       $medium_style = ImageStyle::load('medium');
      
// Upload a file.     $edit['files[' . $field_name . '_0][]'] = $this->container->get('file_system')->realpath($file->getFileUri());
    $this->submitForm($edit, "{$field_name}_0_upload_button");

    // If the field has at least one item, the table should be visible.     $this->assertSession()->elementsCount('xpath', $xpath, 1);

    // Test for AJAX error when using progress bar on file field widget.     $http_client = $this->getHttpClient();
    $key = $this->randomMachineName();
    $post_request = $http_client->request('POST', $this->buildUrl('file/progress/' . $key)[
      'headers' => [
        'Accept' => 'application/json',
        'Content-Type' => 'application/x-www-form-urlencoded',
      ],
      'http_errors' => FALSE,
    ]);
    $this->assertNotEquals(500, $post_request->getStatusCode());
    $body = Json::decode($post_request->getBody());
    $this->assertStringContainsString('Starting upload...', $body['message']);
  }

  

    public function sign(string $uri): string
    {
        $url = parse_url($uri);
        $params = [];

        if (isset($url['query'])) {
            parse_str($url['query']$params);
        }

        $uri = $this->buildUrl($url$params);
        $params[$this->parameter] = $this->computeHash($uri);

        return $this->buildUrl($url$params);
    }

    /** * Checks that a URI contains the correct hash. */
    public function check(string $uri): bool
    {
        $url = parse_url($uri);
        
$this->drupalGet('admin/structure/views/add');
    $this->submitForm($view, 'Save and edit');

    return $default;
  }

  /** * {@inheritdoc} */
  protected function drupalGet($path, array $options = [], array $headers = []) {
    $url = $this->buildUrl($path$options);

    // Ensure that each nojs page is accessible via ajax as well.     if (str_contains($url, '/nojs/')) {
      $url = preg_replace('|/nojs/|', '/ajax/', $url, 1);
      $result = $this->drupalGet($url$options);
      $this->assertSession()->statusCodeEquals(200);
      $this->assertSession()->responseHeaderEquals('Content-Type', 'application/json');
      $this->assertNotEmpty(json_decode($result), 'Ensure that the AJAX request returned valid content.');
    }

    return parent::drupalGet($path$options$headers);
  }

  public function testRead() {
    $this->createDefaultContent(61, 5, TRUE, TRUE, static::IS_NOT_MULTILINGUAL, FALSE);
    // Unpublish the last entity, so we can check access.     $this->nodes[60]->setUnpublished()->save();

    // Different databases have different sort orders, so a sort is required so     // test expectations do not need to vary per database.     $default_sort = ['sort' => 'drupal_internal__nid'];

    // 0. HEAD request allows a client to verify that JSON:API is installed.     $this->httpClient->request('HEAD', $this->buildUrl('/jsonapi/node/article'));
    $this->assertSession()->statusCodeEquals(200);
    // 1. Load all articles (1st page).     $collection_output = Json::decode($this->drupalGet('/jsonapi/node/article', [
      'query' => $default_sort,
    ]));
    $this->assertSession()->statusCodeEquals(200);
    $this->assertCount(OffsetPage::SIZE_MAX, $collection_output['data']);
    $this->assertSession()
      ->responseHeaderEquals('Content-Type', 'application/vnd.api+json');
    // 2. Load all articles (Offset 3).     $collection_output = Json::decode($this->drupalGet('/jsonapi/node/article', [
      
$this->assertCount(1, $drupal_settings['views']['ajaxViews']);
    $view_entry = array_keys($drupal_settings['views']['ajaxViews'])[0];
    $this->assertEquals('test_ajax_view', $drupal_settings['views']['ajaxViews'][$view_entry]['view_name'], 'The view\'s ajaxViews array entry has the correct \'view_name\' key.');
    $this->assertEquals('page_1', $drupal_settings['views']['ajaxViews'][$view_entry]['view_display_id'], 'The view\'s ajaxViews array entry has the correct \'view_display_id\' key.');
  }

  /** * Ensures that non-ajax view cannot be accessed via an ajax HTTP request. */
  public function testNonAjaxViewViaAjax() {
    $client = $this->getHttpClient();
    $response = $client->request('POST', $this->buildUrl('views/ajax')[
      'form_params' => ['view_name' => 'test_ajax_view', 'view_display_id' => 'default'],
      'query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax'],
    ]);
    $this->assertEquals(200, $response->getStatusCode());
    $response = $client->request('POST', $this->buildUrl('views/ajax')[
      'form_params' => ['view_name' => 'test_view', 'view_display_id' => 'default'],
      'query' => [MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax'],
      'http_errors' => FALSE,
    ]);
    $this->assertEquals(403, $response->getStatusCode());
  }

}
$this->assertSession()->statusCodeEquals(401);

    // Not even logging in would make it possible to see the view, because then     // we are denied based on authentication method (cookie).     $this->drupalLogin($this->adminUser);
    $this->drupalGet('test/serialize/auth_with_perm', ['query' => ['_format' => 'json']]);
    $this->assertSession()->statusCodeEquals(403);
    $this->drupalLogout();

    // But if we use the basic auth authentication strategy, we should be able     // to see the page.     $url = $this->buildUrl('test/serialize/auth_with_perm');
    $response = \Drupal::httpClient()->get($url[
      'auth' => [$this->adminUser->getAccountName()$this->adminUser->pass_raw],
      'query' => [
        '_format' => 'json',
      ],
    ]);

    // Ensure that any changes to variables in the other thread are picked up.     $this->refreshVariables();

    $this->assertSession()->statusCodeEquals(200);
  }
/** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = $this->container->get('renderer');

    // Create an image.     $files = $this->drupalGetTestFiles('image');
    $file = reset($files);
    $original_uri = \Drupal::service('file_system')->copy($file->uri, 'public://', FileSystemInterface::EXISTS_RENAME);

    // Create a style.     $style = ImageStyle::create(['name' => 'test', 'label' => 'Test']);
    $style->save();
    $url = \Drupal::service('file_url_generator')->transformRelative($style->buildUrl($original_uri));

    // Create a test entity with the image field set.     $entity = EntityTest::create();
    $entity->image_test->target_id = $this->image->id();
    $entity->image_test->alt = NULL;
    $entity->image_test->uri = $original_uri;
    $image = $this->imageFactory->get('public://example.jpg');
    $entity->save();

    // Create the base element that we'll use in the tests below.     $path = $this->randomMachineName();
    
Role::load(RoleInterface::ANONYMOUS_ID)
      ->grantPermission('restful post serialization_test')
      ->save();

    $serialized = $this->container->get('serializer')->serialize(['foo', 'bar'], 'json');
    $request_options = [
      RequestOptions::HEADERS => ['Content-Type' => 'application/json'],
      RequestOptions::BODY => $serialized,
    ];
    /** @var \GuzzleHttp\ClientInterface $client */
    $client = $this->getSession()->getDriver()->getClient()->getClient();
    $response = $client->request('POST', $this->buildUrl('serialization_test', ['query' => ['_format' => 'json']])$request_options);
    $this->assertSame(200, $response->getStatusCode());
    $this->assertSame('["foo","bar"]', (string) $response->getBody());
  }

  /** * Tests that resource URI paths are formatted properly. */
  public function testUriPaths() {
    /** @var \Drupal\rest\Plugin\Type\ResourcePluginManager $manager */
    $manager = \Drupal::service('plugin.manager.rest');

    
/** * {@inheritdoc} */
  public function viewElements(FieldItemListInterface $items$langcode) {
    $element = [];
    $entity = $items->getEntity();
    $settings = $this->getSettings();

    foreach ($items as $delta => $item) {
      // By default use the full URL as the link text.       $url = $this->buildUrl($item);
      $link_title = $url->toString();

      // If the link text field value is available, use it for the text.       if (empty($settings['url_only']) && !empty($item->title)) {
        // Unsanitized token replacement here because the entire link title         // gets auto-escaped during link generation in         // \Drupal\Core\Utility\LinkGenerator::generate().         $link_title = \Drupal::token()->replace($item->title, [$entity->getEntityTypeId() => $entity]['clear' => TRUE]);
      }

      // The link_separate formatter has two titles; the link text (as in the

  protected function renderContextualLinks($ids$current_path) {
    $tokens = array_map([$this, 'createContextualIdToken']$ids);
    $http_client = $this->getHttpClient();
    $url = Url::fromRoute('contextual.render', [][
      'query' => [
        '_format' => 'json',
        'destination' => $current_path,
      ],
    ]);

    return $http_client->request('POST', $this->buildUrl($url)[
      'cookies' => $this->getSessionCookies(),
      'form_params' => ['ids' => $ids, 'tokens' => $tokens],
      'http_errors' => FALSE,
    ]);
  }

  /** * Creates a contextual ID token. * * @param string $id * The contextual ID to create a token for. * * @return string * The contextual ID token. */

  protected $agent;

  /** * Tests validation of the User-Agent header we use to perform test requests. */
  public function testUserAgentValidation() {
    $assert_session = $this->assertSession();
    $system_path = $this->buildUrl(\Drupal::service('extension.list.module')->getPath('system'));
    $http_path = $system_path . '/tests/http.php/user/login';
    $https_path = $system_path . '/tests/https.php/user/login';
    // Generate a valid test User-Agent to pass validation.     $this->assertNotFalse(preg_match('/test\d+/', $this->databasePrefix, $matches), 'Database prefix contains test prefix.');
    $this->agent = drupal_generate_test_ua($matches[0]);

    // Test pages only available for testing.     $this->drupalGet($http_path);
    $assert_session->statusCodeEquals(200);
    $this->drupalGet($https_path);
    $assert_session->statusCodeEquals(200);

    

    public function sign(string $uri): string
    {
        $url = parse_url($uri);
        $params = [];

        if (isset($url['query'])) {
            parse_str($url['query']$params);
        }

        $uri = $this->buildUrl($url$params);
        $params[$this->parameter] = $this->computeHash($uri);

        return $this->buildUrl($url$params);
    }

    /** * Checks that a URI contains the correct hash. */
    public function check(string $uri): bool
    {
        $url = parse_url($uri);
        
Home | Imprint | This part of the site doesn't use cookies.