base_path example

$test_base_url = 'http://localhost';
    $this->setSetting('file_public_base_url', $test_base_url);
    $filepath = \Drupal::service('file_system')->createFilename("{$image_name}.png", '');
    $directory_uri = 'public://' . dirname($filepath);
    \Drupal::service('file_system')->prepareDirectory($directory_uri, FileSystemInterface::CREATE_DIRECTORY);

    // Create an image file.     $file = File::create(['uri' => "public://{$image_name}.png", 'filename' => "{$image_name}.png"]);
    $file->save();

    $base_path = base_path();

    $path_pairs = [
      'root relative' => [$file->getFileUri(), "{$http_host}{$base_path}{$image_name}.png"],
      'protocol relative' => ['//example.com/image.png', '//example.com/image.png'],
      'absolute' => ['http://example.com/image.png', 'http://example.com/image.png'],
    ];

    // Test images.     foreach ($path_pairs as $test_type => $paths) {
      [$input_path$expected_path] = $paths;

      

      'langcode' => [
        [
          'value' => 'en',
        ],
      ],
      'uid' => [
        [
          'target_id' => (int) $author->id(),
          'target_type' => 'user',
          'target_uuid' => $author->uuid(),
          'url' => base_path() . 'user/' . $author->id(),
        ],
      ],
      'filename' => [
        [
          'value' => $expected_as_filename ? $expected_filename : 'example.txt',
        ],
      ],
      'uri' => [
        [
          'value' => 'public://foobar/' . $expected_filename,
          'url' => base_path() . $this->siteDirectory . '/files/foobar/' . rawurlencode($expected_filename),
        ],

  protected function doGenerateString(string $uri, bool $relative): string {
    // Allow the URI to be altered, e.g. to serve a file from a CDN or static     // file server.     $this->moduleHandler->alter('file_url', $uri);

    $scheme = StreamWrapperManager::getScheme($uri);

    if (!$scheme) {
      $baseUrl = $relative ? base_path() : $this->requestStack->getCurrentRequest()->getSchemeAndHttpHost() . base_path();
      return $this->generatePath($baseUrl$uri);
    }
    elseif ($scheme == 'http' || $scheme == 'https' || $scheme == 'data') {
      // Check for HTTP and data URI-encoded URLs so that we don't have to       // implement getExternalUrl() for the HTTP and data schemes.       return $relative ? $this->transformRelative($uri) : $uri;
    }
    elseif ($wrapper = $this->streamWrapperManager->getViaUri($uri)) {
      // Attempt to return an external URL using the appropriate wrapper.       $externalUrl = $wrapper->getExternalUrl();
      return $relative ? $this->transformRelative($externalUrl) : $externalUrl;
    }

  private function checkUrl(LanguageInterface $language$message) {
    $options = ['language' => $language, 'script' => ''];
    $base_path = trim(base_path(), '/');
    $rewritten_path = trim(str_replace($base_path, '', Url::fromRoute('<front>', []$options)->toString()), '/');
    $segments = explode('/', $rewritten_path, 2);
    $prefix = $segments[0];
    $path = $segments[1] ?? $prefix;

    // If the rewritten URL has not a language prefix we pick a random prefix so     // we can always check the prefixed URL.     $prefixes = $this->config('language.negotiation')->get('url.prefixes');
    $stored_prefix = isset($prefixes[$language->getId()]) ? $prefixes[$language->getId()] : $this->randomMachineName();
    $this->assertNotEquals($prefix$stored_prefix$message);
    $prefix = $stored_prefix;

    
/** * {@inheritdoc} */
  protected $defaultTheme = 'stark';

  /** * Provides the relevant image attributes. * * @return string[] */
  protected function imageAttributes() {
    return ['src' => base_path() . 'core/misc/druplicon.png'];
  }

  /** * Helper to format attributes. * * @param bool $reverse * Reverse attributes when printing them. * * @return string */
  protected function imageAttributesAsString($reverse = FALSE) {
    
if (isset($options['https'])) {
          if ($options['https'] === TRUE) {
            $options['base_url'] = str_replace('http://', 'https://', $options['base_url']);
          }
          elseif ($options['https'] === FALSE) {
            $options['base_url'] = str_replace('https://', 'http://', $options['base_url']);
          }
        }

        // Add Drupal's subfolder from the base_path if there is one.         $options['base_url'] .= rtrim(base_path(), '/');
        if ($bubbleable_metadata) {
          $bubbleable_metadata->addCacheContexts(['languages:' . LanguageInterface::TYPE_URL, 'url.site']);
        }
      }
    }
    return $path;
  }

  /** * {@inheritdoc} */
  
// From the manage display page, go to manage the layout.     $this->drupalGet('admin/structure/types/manage/bundle_with_section_field/display/default');
    $this->submitForm(['layout[enabled]' => TRUE], 'Save');
    $this->submitForm(['layout[allow_custom]' => TRUE], 'Save');
    $page->clickLink('Manage layout');

    $breadcrumb_titles = [];
    foreach ($page->findAll('css', '.breadcrumb a') as $link) {
      $breadcrumb_titles[$link->getText()] = $link->getAttribute('href');
    }
    $base_path = base_path();
    $expected = [
      'Home' => $base_path,
      'Administration' => $base_path . 'admin',
      'Structure' => $base_path . 'admin/structure',
      'Content types' => $base_path . 'admin/structure/types',
      'Bundle with section field' => $base_path . 'admin/structure/types/manage/bundle_with_section_field',
      'Manage display' => $base_path . 'admin/structure/types/manage/bundle_with_section_field/display/default',
      'External link' => 'http://www.example.com',
    ];
    $this->assertSame($expected$breadcrumb_titles);
  }

  
    $path = $this->randomMachineName();
    $base_element = [
      '#theme' => 'image_formatter',
      '#image_style' => 'test',
      '#item' => $entity->image_test,
      '#url' => Url::fromUri('base:' . $path),
    ];

    // Test using theme_image_formatter() with a NULL value for the alt option.     $element = $base_element;
    $this->setRawContent($renderer->renderRoot($element));
    $elements = $this->xpath('//a[@href=:path]/img[@src=:url and @width=:width and @height=:height]', [':path' => base_path() . $path, ':url' => $url, ':width' => $image->getWidth(), ':height' => $image->getHeight()]);
    $this->assertCount(1, $elements, 'theme_image_formatter() correctly renders with a NULL value for the alt option.');

    // Test using theme_image_formatter() without an image title, alt text, or     // link options.     $element = $base_element;
    $element['#item']->alt = '';
    $this->setRawContent($renderer->renderRoot($element));
    $elements = $this->xpath('//a[@href=:path]/img[@src=:url and @width=:width and @height=:height and @alt=""]', [':path' => base_path() . $path, ':url' => $url, ':width' => $image->getWidth(), ':height' => $image->getHeight()]);
    $this->assertCount(1, $elements, 'theme_image_formatter() correctly renders without title, alt, or path options.');

    // Link the image to a fragment on the page, and not a full URL.
// 1. No session (anonymous).     $this->drupalGet(Url::fromRoute('<front>'));
    $this->assertSessionCookieExists(FALSE);
    $this->assertBigPipeNoJsCookieExists(FALSE);
    $this->assertSession()->responseNotContains('<noscript><meta http-equiv="Refresh" content="0; URL=');
    $this->assertSession()->responseNotContains($no_js_to_js_markup);

    // 2. Session (authenticated).     $this->drupalLogin($this->rootUser);
    $this->assertSessionCookieExists(TRUE);
    $this->assertBigPipeNoJsCookieExists(FALSE);
    $this->assertSession()->responseContains('<noscript><meta http-equiv="Refresh" content="0; URL=' . base_path() . 'big_pipe/no-js?destination=' . UrlHelper::encodePath(base_path() . 'user/1?check_logged_in=1') . '" />' . "\n" . '</noscript>');
    $this->assertSession()->responseNotContains($no_js_to_js_markup);
    $this->assertBigPipeNoJsMetaRefreshRedirect();
    $this->assertBigPipeNoJsCookieExists(TRUE);
    $this->assertSession()->responseNotContains('<noscript><meta http-equiv="Refresh" content="0; URL=');
    $this->assertSession()->responseContains($no_js_to_js_markup);
    $this->drupalLogout();

    // Close the prior connection and remove the collected state.     $this->getSession()->reset();

    // 3. Session (anonymous).
/** * Removes base_url() and query args from file paths. * * @param string $path * The path being trimmed. * * @return string * The trimmed path. */
  protected function trimFilePath($path) {
    $base_path_position = strpos($pathbase_path());
    if ($base_path_position !== FALSE) {
      $path = substr_replace($path, '', $base_path_positionstrlen(base_path()));
    }
    $query_pos = strpos($path, '?');
    return $query_pos !== FALSE ? substr($path, 0, $query_pos) : $path;
  }

  /** * Confirms that jQuery UI assets load on the page in the configured order. * * @dataProvider providerTestAssetLoading */
$this->doTestTranslations('node', $values);

    // Enable the translation language renderer.     $view = \Drupal::entityTypeManager()->getStorage('view')->load('frontpage');
    $display = &$view->getDisplay('default');
    $display['display_options']['rendering_language'] = '***LANGUAGE_entity_translation***';
    $view->save();

    // Need to check from the beginning, including the base_path, in the URL     // since the pattern for the default language might be a substring of     // the strings for other languages.     $base_path = base_path();

    // Check the frontpage for 'Read more' links to each translation.     // See also assertTaxonomyPage() in NodeAccessBaseTableTest.     $node_href = 'node/' . $node->id();
    foreach ($this->langcodes as $langcode) {
      $this->drupalGet('node', ['language' => \Drupal::languageManager()->getLanguage($langcode)]);
      $num_match_found = 0;
      if ($langcode == 'en') {
        // Site default language does not have langcode prefix in the URL.         $expected_href = $base_path . $node_href;
      }
      
// Editor user: can access contextual links and can edit articles.     $this->drupalGet('node');
    for ($i = 0; $i < count($ids)$i++) {
      $this->assertContextualLinkPlaceHolder($ids[$i]);
    }
    $response = $this->renderContextualLinks([], 'node');
    $this->assertSame(400, $response->getStatusCode());
    $this->assertStringContainsString('No contextual ids specified.', (string) $response->getBody());
    $response = $this->renderContextualLinks($ids, 'node');
    $this->assertSame(200, $response->getStatusCode());
    $json = Json::decode((string) $response->getBody());
    $this->assertSame('<ul class="contextual-links"><li><a href="' . base_path() . 'node/1/edit">Edit</a></li></ul>', $json[$ids[0]]);
    $this->assertSame('', $json[$ids[1]]);
    $this->assertSame('<ul class="contextual-links"><li><a href="' . base_path() . 'node/3/edit">Edit</a></li></ul>', $json[$ids[2]]);
    $this->assertSame('', $json[$ids[3]]);

    // Verify that link language is properly handled.     $node3->addTranslation('it')->set('title', $this->randomString())->save();
    $id = 'node:node=' . $node3->id() . ':changed=' . $node3->getChangedTime() . '&langcode=it';
    $this->drupalGet('node', ['language' => ConfigurableLanguage::createFromLangcode('it')]);
    $this->assertContextualLinkPlaceHolder($id);

    // Authenticated user: can access contextual links, cannot edit articles.
// Try to use an invalid domain.     $edit = [
      'language_negotiation_url_part' => LanguageNegotiationUrl::CONFIG_DOMAIN,
      'domain[en]' => $base_url_host,
      'domain[it]' => 'it.example.com/',
    ];
    $this->drupalGet('admin/config/regional/language/detection/url');
    $this->submitForm($edit, 'Save configuration');
    $this->assertSession()->statusMessageContains("The domain for Italian may only contain the domain name, not a trailing slash, protocol and/or port.", 'error');

    // Build the link we're going to test.     $link = 'it.example.com' . rtrim(base_path(), '/') . '/admin';

    // Test URL in another language: http://it.example.com/admin.     // Base path gives problems on the testbot, so $correct_link is hard-coded.     // @see UrlAlterFunctionalTest::assertUrlOutboundAlter (path.test).     $italian_url = Url::fromRoute('system.admin', []['language' => $languages['it']])->toString();
    $url_scheme = \Drupal::request()->isSecure() ? 'https://' : 'http://';
    $correct_link = $url_scheme . $link;
    $this->assertEquals($correct_link$italian_urlnew FormattableMarkup('The right URL (@url) in accordance with the chosen language', ['@url' => $italian_url]));

    // Test HTTPS via options.     $italian_url = Url::fromRoute('system.admin', []['https' => TRUE, 'language' => $languages['it']])->toString();
    
$form_action->bigPipeNoJsPlaceholder = 'big_pipe_nojs_placeholder_attribute_safe:form_action_cc611e1d';
    $form_action->bigPipeNoJsPlaceholderRenderArray = [
      '#markup' => 'big_pipe_nojs_placeholder_attribute_safe:form_action_cc611e1d',
      '#cache' => $cacheability_depends_on_session_only,
      '#attached' => [
        'big_pipe_nojs_placeholders' => [
          'big_pipe_nojs_placeholder_attribute_safe:form_action_cc611e1d' => $form_action->placeholderRenderArray,
        ],
      ],
    ];
    if ($container) {
      $form_action->embeddedHtmlResponse = '<form class="big-pipe-test-form" data-drupal-selector="big-pipe-test-form" action="' . base_path() . 'big_pipe_test"';
    }

    // 3. Real-world example of HTML attribute value subset placeholder: CSRF     // token in link.     $csrf_token = new BigPipePlaceholderTestCase(
      [
        '#title' => 'Link with CSRF token',
        '#type' => 'link',
        '#url' => Url::fromRoute('system.theme_set_default'),
      ],
      'e88b559cce72c80b687d56b0e2a3a5ae4b66bc0e',
      [
'revision_id' => [
        [
          'value' => 2,
        ],
      ],
      'parent' => [],
      'uid' => [
        [
          'target_id' => (int) $author->id(),
          'target_type' => 'user',
          'target_uuid' => $author->uuid(),
          'url' => base_path() . 'user/' . $author->id(),
        ],
      ],
      'uuid' => [
        [
          'value' => $this->entity->uuid(),
        ],
      ],
    ];
  }

  /** * {@inheritdoc} */
Home | Imprint | This part of the site doesn't use cookies.