Commit 0fb9bb54 authored by webchick's avatar webchick

Issue #2364157 by mpdonadio, dawehner, martin107, Berdir, pcambra,...

Issue #2364157 by mpdonadio, dawehner, martin107, Berdir, pcambra, naveenvalecha, tim.plunkett: Replace most existing _url calls with Url objects
parent 0e914b24
......@@ -153,10 +153,12 @@ function _batch_progress_page() {
// Merge required query parameters for batch processing into those provided by
// batch_set() or hook_batch_alter().
$batch['url_options']['query']['id'] = $batch['id'];
$batch['url_options']['query']['op'] = $new_op;
$query_options = $batch['url']->getOption('query');
$query_options['id'] = $batch['id'];
$query_options['op'] = $new_op;
$batch['url']->setOption('query', $query_options);
$url = _url($batch['url'], $batch['url_options']);
$url = $batch['url']->toString();
$build = array(
'#theme' => 'progress_bar',
......
......@@ -745,9 +745,10 @@ function batch_set($batch_definition) {
* This function is generally not needed in form submit handlers;
* Form API takes care of batches that were set during form submission.
*
* @param $redirect
* (optional) Path to redirect to when the batch has finished processing.
* @param $url
* @param \Drupal\Core\Url|string $redirect
* (optional) Either path or Url object to redirect to when the batch has
* finished processing.
* @param \Drupal\Core\Url $url
* (optional - should only be used for separate scripts like update.php)
* URL of the batch processing page.
* @param $redirect_callback
......@@ -757,7 +758,7 @@ function batch_set($batch_definition) {
* @return \Symfony\Component\HttpFoundation\RedirectResponse|null
* A redirect response if the batch is progressive. No return value otherwise.
*/
function batch_process($redirect = NULL, $url = 'batch', $redirect_callback = NULL) {
function batch_process($redirect = NULL, Url $url = NULL, $redirect_callback = NULL) {
$batch =& batch_get();
if (isset($batch)) {
......@@ -765,8 +766,7 @@ function batch_process($redirect = NULL, $url = 'batch', $redirect_callback = NU
$process_info = array(
'current_set' => 0,
'progressive' => TRUE,
'url' => $url,
'url_options' => array(),
'url' => isset($url) ? $url : Url::fromRoute('system.batch_page.html'),
'source_url' => Url::fromRouteMatch(\Drupal::routeMatch()),
'batch_redirect' => $redirect,
'theme' => \Drupal::theme()->getActiveTheme()->getName(),
......@@ -793,7 +793,16 @@ function batch_process($redirect = NULL, $url = 'batch', $redirect_callback = NU
if ($batch['progressive']) {
// Now that we have a batch id, we can generate the redirection link in
// the generic error message.
$batch['error_message'] = t('Please continue to <a href="@error_url">the error page</a>', array('@error_url' => _url($url, array('query' => array('id' => $batch['id'], 'op' => 'finished')))));
/** @var \Drupal\Core\Url $batch_url */
$batch_url = $batch['url'];
/** @var \Drupal\Core\Url $error_url */
$error_url = clone $batch_url;
$query_options = $error_url->getOption('query');
$query_options['id'] = $batch['id'];
$query_options['op'] = 'finished';
$error_url->setOption('query', $query_options);
$batch['error_message'] = t('Please continue to <a href="@error_url">the error page</a>', array('@error_url' => $error_url->toString()));
// Clear the way for the redirection to the batch processing page, by
// saving and unsetting the 'destination', if there is any.
......@@ -815,13 +824,15 @@ function batch_process($redirect = NULL, $url = 'batch', $redirect_callback = NU
$_SESSION['batches'][$batch['id']] = TRUE;
// Redirect for processing.
$options = array('query' => array('op' => 'start', 'id' => $batch['id']));
$query_options = $error_url->getOption('query');
$query_options['op'] = 'start';
$query_options['id'] = $batch['id'];
$batch_url->setOption('query', $query_options);
if (($function = $batch['redirect_callback']) && function_exists($function)) {
$function($batch['url'], $options);
$function($batch_url->toString(), ['query' => $query_options]);
}
else {
$options['absolute'] = TRUE;
return new RedirectResponse(_url($batch['url'], $options));
return new RedirectResponse($batch_url->setAbsolute()->toString());
}
}
else {
......
......@@ -18,6 +18,7 @@
use Drupal\Core\StringTranslation\Translator\FileTranslation;
use Drupal\Core\Extension\ExtensionDiscovery;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Url;
use Drupal\language\Entity\ConfigurableLanguage;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpFoundation\Request;
......@@ -581,10 +582,10 @@ function install_run_task($task, &$install_state) {
}
// Process the batch. For progressive batches, this will redirect.
// Otherwise, the batch will complete.
// install_redirect_url() returns core/install.php, so let's ensure to
// drop it from it and use base:// as batch_process() is using the
// unrouted URL assembler, which requires base://.
$response = batch_process(preg_replace('@^core/@', 'base://', install_redirect_url($install_state)), install_full_redirect_url($install_state));
// Disable the default script for the URL and clone the object, as
// batch_process() will add additional options to the batch URL.
$url = Url::fromUri('base://install.php', ['query' => $install_state['parameters'], 'script' => '']);
$response = batch_process($url, clone $url);
if ($response instanceof Response) {
// Save $_SESSION data from batch.
\Drupal::service('session_manager')->save();
......
......@@ -134,7 +134,6 @@ public static function filterQueryParameters(array $query, array $exclude = arra
* - fragment: The fragment component from $url, if it exists.
*
* @see \Drupal\Core\Utility\LinkGenerator
* @see _url()
* @see http://tools.ietf.org/html/rfc3986
*
* @ingroup php_wrappers
......
......@@ -28,7 +28,7 @@ class RedirectCommand implements CommandInterface {
*
* @param string $url
* The URL that will be loaded into window.location. This should be a full
* URL, one that has already been run through the _url() function.
* URL.
*/
public function __construct($url) {
$this->url = $url;
......
......@@ -119,7 +119,7 @@ public function loadFile($file, $optimize = NULL, $reset_basepath = TRUE) {
* Loads stylesheets recursively and returns contents with corrected paths.
*
* This function is used for recursive loading of stylesheets and
* returns the stylesheet content with all _url() paths corrected.
* returns the stylesheet content with all url() paths corrected.
*
* @param array $matches
* An array of matches by a preg_replace_callback() call that scans for
......@@ -138,10 +138,10 @@ protected function loadNestedFile($matches) {
// Determine the file's directory.
$directory = dirname($filename);
// If the file is in the current directory, make sure '.' doesn't appear in
// the _url() path.
// the url() path.
$directory = $directory == '.' ? '' : $directory .'/';
// Alter all internal _url() paths. Leave external paths alone. We don't need
// Alter all internal url() paths. Leave external paths alone. We don't need
// to normalize absolute paths here (i.e. remove folder/... segments)
// because that will be done later.
return preg_replace('/url\(\s*([\'"]?)(?![a-z]+:|\/+)([^\'")]+)([\'"]?)\s*\)/i', 'url(\1' . $directory . '\2\3)', $file);
......@@ -215,7 +215,7 @@ protected function processCss($contents, $optimize = FALSE) {
*
* @param array $matches
* An array of matches by a preg_replace_callback() call that scans for
* _url() references in CSS files, except for external or absolute ones.
* url() references in CSS files, except for external or absolute ones.
*
* Note: the only reason this method is public is so color.module can call it;
* it is not on the AssetOptimizerInterface, so future refactorings can make
......
......@@ -193,8 +193,8 @@ public function urlInfo($rel = 'canonical', array $options = []) {
}
}
// Pass the entity data to _url() so that alter functions do not need to
// look up this entity again.
// Pass the entity data through as options, so that alter functions do not
// need to look up this entity again.
$uri
->setOption('entity_type', $this->getEntityTypeId())
->setOption('entity', $this);
......
......@@ -1273,7 +1273,7 @@ protected static function schemaDefinition() {
'not null' => FALSE,
),
'options' => array(
'description' => 'A serialized array of options to be passed to the _url() or _l() function, such as a query string or HTML attributes.',
'description' => 'A serialized array of URL options, such as a query string or HTML attributes.',
'type' => 'blob',
'size' => 'big',
'not null' => FALSE,
......
......@@ -88,7 +88,7 @@ protected function loadMenuPathRoots() {
*/
public function get($offset) {
$this->lazyLoadCache();
// _url() may be called with paths that are not represented by menu router
// this may be called with paths that are not represented by menu router
// items such as paths that will be rewritten by hook_url_outbound_alter().
// Therefore internally TRUE is used to indicate whitelisted paths. FALSE is
// used to indicate paths that have already been checked but are not
......
......@@ -291,9 +291,8 @@ public static function preRenderAjaxForm($element) {
$settings['progress'] = array('type' => $settings['progress']);
}
// Change progress path to a full URL.
if (isset($settings['progress']['path'])) {
$settings['progress']['url'] = _url($settings['progress']['path']);
unset($settings['progress']['path']);
if (isset($settings['progress']['url']) && $settings['progress']['url'] instanceof Url) {
$settings['progress']['url'] = $settings['progress']['url']->toString();
}
$element['#attached']['drupalSettings']['ajax'][$element['#id']] = $settings;
......
......@@ -251,8 +251,7 @@ public function generateFromPath($path = NULL, $options = array()) {
// \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols() if $path
// contains a ':' before any / ? or #. Note: we could use
// \Drupal\Component\Utility\UrlHelper::isExternal($path) here, but that
// would require another function call, and performance inside _url() is
// critical.
// would require another function call, and performance here is critical.
$colonpos = strpos($path, ':');
$options['external'] = ($colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && UrlHelper::stripDangerousProtocols($path) == $path);
}
......
......@@ -155,13 +155,29 @@ protected function buildLocalUrl($uri, array $options = []) {
* The options to merge in the defaults.
*/
protected function addOptionDefaults(array &$options) {
$request = $this->requestStack->getCurrentRequest();
$current_base_path = $request->getBasePath() . '/';
$current_script_path = '';
$base_path_with_script = $request->getBaseUrl();
// If the current request was made with the script name (eg, index.php) in
// it, then extract it, making sure the leading / is gone, and a trailing /
// is added, to allow simple string concatenation with other parts. This
// mirrors code from UrlGenerator::generateFromPath().
if (!empty($base_path_with_script)) {
$script_name = $request->getScriptName();
if (strpos($base_path_with_script, $script_name) !== FALSE) {
$current_script_path = ltrim(substr($script_name, strlen($current_base_path)), '/') . '/';
}
}
// Merge in defaults.
$options += [
'fragment' => '',
'query' => [],
'absolute' => FALSE,
'prefix' => '',
'script' => '',
'script' => $current_script_path,
];
if (isset($options['fragment']) && $options['fragment'] !== '') {
......
......@@ -7,6 +7,7 @@
namespace Drupal\aggregator\Tests;
use Drupal\Core\Url;
use Zend\Feed\Reader\Reader;
/**
......@@ -76,12 +77,11 @@ function testHtmlEntitiesSample() {
}
/**
* Tests error handling when an invalid feed is added.
* Tests that a redirected feed is tracked to its target.
*/
function testRedirectFeed() {
// Simulate a typo in the URL to force a curl exception.
$invalid_url = _url('aggregator/redirect', array('absolute' => TRUE));
$feed = entity_create('aggregator_feed', array('url' => $invalid_url, 'title' => $this->randomMachineName()));
$redirect_url = Url::fromRoute('aggregator_test.redirect')->setAbsolute()->toString();
$feed = entity_create('aggregator_feed', array('url' => $redirect_url, 'title' => $this->randomMachineName()));
$feed->save();
$feed->refreshItems();
......
......@@ -7,6 +7,7 @@
namespace Drupal\basic_auth\Tests\Authentication;
use Drupal\Core\Url;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\simpletest\WebTestBase;
......@@ -29,18 +30,21 @@ class BasicAuthTest extends WebTestBase {
*/
public function testBasicAuth() {
$account = $this->drupalCreateUser();
$url = Url::fromRoute('router_test.11');
$this->basicAuthGet('router_test/test11', $account->getUsername(), $account->pass_raw);
$this->basicAuthGet($url, $account->getUsername(), $account->pass_raw);
$this->assertText($account->getUsername(), 'Account name is displayed.');
$this->assertResponse('200', 'HTTP response is OK');
$this->curlClose();
$this->basicAuthGet('router_test/test11', $account->getUsername(), $this->randomMachineName());
$this->basicAuthGet($url, $account->getUsername(), $this->randomMachineName());
$this->assertNoText($account->getUsername(), 'Bad basic auth credentials do not authenticate the user.');
$this->assertResponse('403', 'Access is not granted.');
$this->curlClose();
$this->drupalGet('router_test/test11');
// @todo Change ->drupalGet() calls to just pass $url when
// https://www.drupal.org/node/2350837 gets committed
$this->drupalGet($url->setAbsolute()->toString());
$this->assertResponse('401', 'Not authenticated on the route that allows only basic_auth. Prompt to authenticate received.');
$this->drupalGet('admin');
......@@ -48,7 +52,7 @@ public function testBasicAuth() {
$account = $this->drupalCreateUser(array('access administration pages'));
$this->basicAuthGet('admin', $account->getUsername(), $account->pass_raw);
$this->basicAuthGet(Url::fromRoute('system.admin'), $account->getUsername(), $account->pass_raw);
$this->assertNoLink('Log out', 0, 'User is not logged in');
$this->assertResponse('403', 'No basic authentication for routes not explicitly defining authentication providers.');
$this->curlClose();
......@@ -67,14 +71,15 @@ function testGlobalLoginFloodControl() {
$user = $this->drupalCreateUser(array());
$incorrect_user = clone $user;
$incorrect_user->pass_raw .= 'incorrect';
$url = Url::fromRoute('router_test.11');
// Try 2 failed logins.
for ($i = 0; $i < 2; $i++) {
$this->basicAuthGet('router_test/test11', $incorrect_user->getUsername(), $incorrect_user->pass_raw);
$this->basicAuthGet($url, $incorrect_user->getUsername(), $incorrect_user->pass_raw);
}
// IP limit has reached to its limit. Even valid user credentials will fail.
$this->basicAuthGet('router_test/test11', $user->getUsername(), $user->pass_raw);
$this->basicAuthGet($url, $user->getUsername(), $user->pass_raw);
$this->assertResponse('403', 'Access is blocked because of IP based flood prevention.');
}
......@@ -92,26 +97,27 @@ function testPerUserLoginFloodControl() {
$incorrect_user = clone $user;
$incorrect_user->pass_raw .= 'incorrect';
$user2 = $this->drupalCreateUser(array());
$url = Url::fromRoute('router_test.11');
// Try a failed login.
$this->basicAuthGet('router_test/test11', $incorrect_user->getUsername(), $incorrect_user->pass_raw);
$this->basicAuthGet($url, $incorrect_user->getUsername(), $incorrect_user->pass_raw);
// A successful login will reset the per-user flood control count.
$this->basicAuthGet('router_test/test11', $user->getUsername(), $user->pass_raw);
$this->basicAuthGet($url, $user->getUsername(), $user->pass_raw);
$this->assertResponse('200', 'Per user flood prevention gets reset on a successful login.');
// Try 2 failed logins for a user. They will trigger flood control.
for ($i = 0; $i < 2; $i++) {
$this->basicAuthGet('router_test/test11', $incorrect_user->getUsername(), $incorrect_user->pass_raw);
$this->basicAuthGet($url, $incorrect_user->getUsername(), $incorrect_user->pass_raw);
}
// Now the user account is blocked.
$this->basicAuthGet('router_test/test11', $user->getUsername(), $user->pass_raw);
$this->basicAuthGet($url, $user->getUsername(), $user->pass_raw);
$this->assertResponse('403', 'The user account is blocked due to per user flood prevention.');
// Try one successful attempt for a different user, it should not trigger
// any flood control.
$this->basicAuthGet('router_test/test11', $user2->getUsername(), $user2->pass_raw);
$this->basicAuthGet($url, $user2->getUsername(), $user2->pass_raw);
$this->assertResponse('200', 'Per user flood prevention does not block access for other users.');
}
......@@ -123,8 +129,9 @@ function testLocale() {
$this->config('system.site')->set('langcode', 'de')->save();
$account = $this->drupalCreateUser();
$url = Url::fromRoute('router_test.11');
$this->basicAuthGet('router_test/test11', $account->getUsername(), $account->pass_raw);
$this->basicAuthGet($url, $account->getUsername(), $account->pass_raw);
$this->assertText($account->getUsername(), 'Account name is displayed.');
$this->assertResponse('200', 'HTTP response is OK');
$this->curlClose();
......@@ -136,8 +143,8 @@ function testLocale() {
* We do not use \Drupal\simpletest\WebTestBase::drupalGet because we need to
* set curl settings for basic authentication.
*
* @param string $path
* The request path.
* @param \Drupal\Core\Url|string $path
* Drupal path or URL to load into internal browser
* @param string $username
* The user name to authenticate with.
* @param string $password
......@@ -147,10 +154,14 @@ function testLocale() {
* Curl output.
*/
protected function basicAuthGet($path, $username, $password) {
if ($path instanceof Url) {
$path = $path->setAbsolute()->toString();
}
$out = $this->curlExec(
array(
CURLOPT_HTTPGET => TRUE,
CURLOPT_URL => _url($path, array('absolute' => TRUE)),
CURLOPT_URL => $path,
CURLOPT_NOBODY => FALSE,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $username . ':' . $password,
......
......@@ -112,9 +112,9 @@ function testFileCreateUrl() {
'%C3%A9%C3%B8%C3%AF%D0%B2%CE%B2%E4%B8%AD%E5%9C%8B%E6%9B%B8%DB%9E';
// Public files should not be served by Drupal, so their URLs should not be
// generated by _url(), whereas private files should be served by Drupal, so
// their URLs should be generated by _url(). The difference is most apparent
// when $script_path is not empty (i.e., when not using clean URLs).
// routed through Drupal, whereas private files should be served by Drupal,
// so they need to be. The difference is most apparent when $script_path
// is not empty (i.e., when not using clean URLs).
$clean_url_settings = array(
'clean' => '',
'unclean' => 'index.php/',
......
......@@ -21,7 +21,7 @@ class FilterDefaultConfigTest extends KernelTestBase {
protected function setUp() {
parent::setUp();
// Drupal\filter\FilterPermissions::permissions() calls into _url() to output
// Drupal\filter\FilterPermissions::permissions() builds an URL to output
// a link in the description.
$this->installSchema('system', 'url_alias');
......
......@@ -7,6 +7,7 @@
namespace Drupal\hal\Tests;
use Drupal\Core\Url;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
/**
......@@ -24,7 +25,7 @@ public function testTypeHandling() {
$data_with_valid_type = array(
'_links' => array(
'type' => array(
'href' => _url('rest/type/entity_test/entity_test', array('absolute' => TRUE)),
'href' => Url::fromUri('base://rest/type/entity_test/entity_test', array('absolute' => TRUE))->toString(),
),
),
);
......@@ -36,10 +37,10 @@ public function testTypeHandling() {
'_links' => array(
'type' => array(
array(
'href' => _url('rest/types/foo', array('absolute' => TRUE)),
'href' => Url::fromUri('base://rest/types/foo', array('absolute' => TRUE))->toString(),
),
array(
'href' => _url('rest/type/entity_test/entity_test', array('absolute' => TRUE)),
'href' => Url::fromUri('base://rest/type/entity_test/entity_test', array('absolute' => TRUE))->toString(),
),
),
),
......@@ -51,7 +52,7 @@ public function testTypeHandling() {
$data_with_invalid_type = array(
'_links' => array(
'type' => array(
'href' => _url('rest/types/foo', array('absolute' => TRUE)),
'href' => Url::fromUri('base://rest/types/foo', array('absolute' => TRUE))->toString(),
),
),
);
......@@ -84,7 +85,7 @@ public function testMarkFieldForDeletion() {
$no_field_data = array(
'_links' => array(
'type' => array(
'href' => _url('rest/type/entity_test/entity_test', array('absolute' => TRUE)),
'href' => Url::fromUri('base://rest/type/entity_test/entity_test', array('absolute' => TRUE))->toString(),
),
),
);
......@@ -94,7 +95,7 @@ public function testMarkFieldForDeletion() {
$empty_field_data = array(
'_links' => array(
'type' => array(
'href' => _url('rest/type/entity_test/entity_test', array('absolute' => TRUE)),
'href' => Url::fromUri('base://rest/type/entity_test/entity_test', array('absolute' => TRUE))->toString(),
),
),
'field_test_text' => array(),
......@@ -112,7 +113,7 @@ public function testBasicFieldDenormalization() {
$data = array(
'_links' => array(
'type' => array(
'href' => _url('rest/type/entity_test/entity_test', array('absolute' => TRUE)),
'href' => Url::fromUri('base://rest/type/entity_test/entity_test', array('absolute' => TRUE))->toString(),
),
),
'uuid' => array(
......@@ -182,7 +183,7 @@ public function testPatchDenormailzation() {
$data = array(
'_links' => array(
'type' => array(
'href' => _url('rest/type/entity_test/entity_test', array('absolute' => TRUE)),
'href' => Url::fromUri('base://rest/type/entity_test/entity_test', array('absolute' => TRUE))->toString(),
),
),
'field_test_text' => array(
......
......@@ -39,7 +39,8 @@ protected function setUp() {
$this->installEntitySchema('file');
$entity_manager = \Drupal::entityManager();
$link_manager = new LinkManager(new TypeLinkManager(new MemoryBackend('default')), new RelationLinkManager(new MemoryBackend('default'), $entity_manager));
$url_assembler = \Drupal::service('unrouted_url_assembler');
$link_manager = new LinkManager(new TypeLinkManager(new MemoryBackend('default'), $url_assembler), new RelationLinkManager(new MemoryBackend('default'), $entity_manager, $url_assembler));
// Set up the mock serializer.
$normalizers = array(
......
......@@ -7,6 +7,8 @@
namespace Drupal\hal\Tests;
use Drupal\Core\Url;
/**
* Tests that entities can be normalized in HAL.
*
......@@ -59,8 +61,8 @@ public function testNormalize() {
$entity->getTranslation('en')->set('field_test_entity_reference', array(0 => $translation_values['field_test_entity_reference']));
$entity->save();
$type_uri = _url('rest/type/entity_test/entity_test', array('absolute' => TRUE));
$relation_uri = _url('rest/relation/entity_test/entity_test/field_test_entity_reference', array('absolute' => TRUE));
$type_uri = Url::fromUri('base://rest/type/entity_test/entity_test', array('absolute' => TRUE))->toString();
$relation_uri = Url::fromUri('base://rest/relation/entity_test/entity_test/field_test_entity_reference', array('absolute' => TRUE))->toString();
$expected_array = array(
'_links' => array(
......
......@@ -134,7 +134,8 @@ protected function setUp() {
))->save();
$entity_manager = \Drupal::entityManager();
$link_manager = new LinkManager(new TypeLinkManager(new MemoryBackend('default')), new RelationLinkManager(new MemoryBackend('default'), $entity_manager));
$url_assembler = \Drupal::service('unrouted_url_assembler');
$link_manager = new LinkManager(new TypeLinkManager(new MemoryBackend('default'), $url_assembler), new RelationLinkManager(new MemoryBackend('default'), $entity_manager, $url_assembler));
$chain_resolver = new ChainEntityResolver(array(new UuidResolver($entity_manager), new TargetIdResolver()));
......
......@@ -14,6 +14,7 @@
use Drupal\Core\Entity\EntityWithPluginCollectionInterface;
use Drupal\Core\Routing\RequestHelper;
use Drupal\Core\Site\Settings;
use Drupal\Core\Url;
use Drupal\image\ImageEffectPluginCollection;
use Drupal\image\ImageEffectInterface;
use Drupal\image\ImageStyleInterface;
......@@ -218,12 +219,13 @@ public function buildUrl($path, $clean_urls = NULL) {
}
// If not using clean URLs, the image derivative callback is only available
// with the script path. If the file does not exist, use _url() to ensure
// that it is included. Once the file exists it's fine to fall back to the
// actual file path, this avoids bootstrapping PHP once the files are built.
// with the script path. If the file does not exist, use Url::fromUri() to
// ensure that it is included. Once the file exists it's fine to fall back
// to the actual file path, this avoids bootstrapping PHP once the files are
// built.
if ($clean_urls === FALSE && file_uri_scheme($uri) == 'public' && !file_exists($uri)) {
$directory_path = file_stream_wrapper_get_instance_by_uri($uri)->getDirectoryPath();
return _url($directory_path . '/' . file_uri_target($uri), array('absolute' => TRUE, 'query' => $token_query));
return Url::fromUri('base://' . $directory_path . '/' . file_uri_target($uri), array('absolute' => TRUE, 'query' => $token_query))->toString();
}
$file_url = file_create_url($uri);
......
......@@ -25,7 +25,7 @@
* - Content language: The language used to present content that is available
* in more than one language.
* - URL language: The language associated with URLs. When generating a URL,
* this value will be used by _url() as a default if no explicit preference is
* this value will be used for URL's as a default if no explicit preference is
* provided.
* Modules can define additional language types through
* hook_language_types_info(), and alter existing language type definitions
......
......@@ -7,6 +7,7 @@
namespace Drupal\language\Tests;
use Drupal\Core\Url;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationBrowser;
use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationSelected;
......@@ -417,7 +418,7 @@ function testUrlLanguageFallback() {
}
/**
* Tests _url() when separate domains are used for multiple languages.
* Tests URL handling when separate domains are used for multiple languages.
*/
function testLanguageDomain() {
global $base_url;
......@@ -462,23 +463,22 @@ function testLanguageDomain() {
// 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('admin', array('language' => $languages['it'], 'script' => ''));
$italian_url = Url::fromRoute('system.admin', [], ['language' => $languages['it']])->toString();
$url_scheme = \Drupal::request()->isSecure() ? 'https://' : 'http://';
$correct_link = $url_scheme . $link;
$this->assertEqual($italian_url, $correct_link, format_string('The _url() function returns the right URL (@url) in accordance with the chosen language', array('@url' => $italian_url)));
$this->assertEqual($italian_url, $correct_link, format_string('The right URL (@url) in accordance with the chosen language', array('@url' => $italian_url)));
// Test HTTPS via options.
$italian_url = _url('admin', array('https' => TRUE, 'language' => $languages['it'], 'script' => ''));
$italian_url = Url::fromRoute('system.admin', [], ['https' => TRUE, 'language' => $languages['it']])->toString();
$correct_link = 'https://' . $link;
$this->assertTrue($italian_url == $correct_link, format_string('The _url() function returns the right HTTPS URL (via options) (@url) in accordance with the chosen language', array('@url' => $italian_url)));
$this->assertTrue($italian_url == $correct_link, format_string('The right HTTPS URL (via options) (@url) in accordance with the chosen language', array('@url' => $italian_url)));
// Test HTTPS via current URL scheme.
$request = Request::create('', 'GET', array(), array(), array(), array('HTTPS' => 'on'));
$this->container->get('request_stack')->push($request);
$generator = $this->container->get('url_generator');
$italian_url = _url('admin', array('language' => $languages['it'], 'script' => ''));
$italian_url = Url::fromRoute('system.admin', [], ['language' => $languages['it']])->toString();
$correct_link = 'https://' . $link;
$this->assertTrue($italian_url == $correct_link, format_string('The _url() function returns the right URL (via current URL scheme) (@url) in accordance with the chosen language', array('@url' => $italian_url)));
$this->assertTrue($italian_url == $correct_link, format_string('The right URL (via current URL scheme) (@url) in accordance with the chosen language', array('@url' => $italian_url)));
}
/**
......
......@@ -9,6 +9,7 @@
use Drupal\Core\Language\Language;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Url;
use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl;
use Drupal\simpletest\WebTestBase;
use Symfony\Component\HttpFoundation\Request;
......@@ -138,21 +139,21 @@ function testDomainNameNegotiationPort() {
// Create an absolute French link.
$language = \Drupal::languageManager()->getLanguage('fr');
$url = _url('', array(
$url = Url::fromRoute('<none>', [], [
'absolute' => TRUE,
'language' => $language,
));
])->toString();
$expected = ($index_php ? 'http://example.fr:88/index.php' : 'http://example.fr:88') . rtrim(base_path(), '/') . '/';
$this->assertEqual($url, $expected, 'The right port is used.');
// If we set the port explicitly in _url(), it should not be overriden.
$url = _url('', array(
// If we set the port explicitly, it should not be overriden.
$url = Url::fromRoute('<none>', [], [
'absolute' => TRUE,
'language' => $language,
'base_url' => $request->getBaseUrl() . ':90',
));
])->toString();
$expected = $index_php ? 'http://example.fr:90/index.php' : 'http://example.fr:90' . rtrim(base_path(), '/') . '/';
......
......@@ -8,6 +8,7 @@
namespace Drupal\locale\Tests;
use Drupal\Core\StreamWrapper\PublicStream;