Issue #3034072 by kim.pepper, Berdir, alexpott, jibran, larowlan, claudiu.cristea: Move file uri/scheme functions from file.inc and FileSystem to StreamWrapperManager

merge-requests/1119/head
Alex Pott 2019-06-02 08:53:50 +01:00
parent d2792e13d7
commit e08ec1395c
No known key found for this signature in database
GPG Key ID: 31905460D4A69276
36 changed files with 622 additions and 232 deletions

View File

@ -1599,7 +1599,7 @@ services:
- { name: needs_destruction }
library.discovery.parser:
class: Drupal\Core\Asset\LibraryDiscoveryParser
arguments: ['@app.root', '@module_handler', '@theme.manager']
arguments: ['@app.root', '@module_handler', '@theme.manager', '@stream_wrapper_manager']
library.dependency_resolver:
class: Drupal\Core\Asset\LibraryDependencyResolver
arguments: ['@library.discovery']

View File

@ -16,6 +16,7 @@ use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Site\Settings;
use Drupal\Core\StreamWrapper\PrivateStream;
use Drupal\Core\StreamWrapper\PublicStream;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
/**
* Default mode for new directories.
@ -98,25 +99,29 @@ const FILE_STATUS_PERMANENT = 1;
/**
* Returns the scheme of a URI (e.g. a stream).
*
* @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
* Use \Drupal\Core\File\FileSystem::uriScheme().
* @deprecated in drupal:8.8.0 and will be removed from drupal:9.0.0. Use
* Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::getScheme()
* instead.
*
* @see https://www.drupal.org/node/2418133
* @see https://www.drupal.org/node/3035273
*/
function file_uri_scheme($uri) {
return \Drupal::service('file_system')->uriScheme($uri);
@trigger_error('file_uri_scheme() is deprecated in drupal:8.0.0 and will be removed before drupal:9.0.0. Use \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::getScheme() instead. See https://www.drupal.org/node/3035273', E_USER_DEPRECATED);
return StreamWrapperManager::getScheme($uri);
}
/**
* Checks that the scheme of a stream URI is valid.
*
* @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
* Use \Drupal\Core\File\FileSystem::validScheme().
* @deprecated in drupal:8.8.0 and will be removed from Drupal 9.0.0. Use
* Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::isValidScheme()
* instead.
*
* @see https://www.drupal.org/node/2418133
* @see https://www.drupal.org/node/3035273
*/
function file_stream_wrapper_valid_scheme($scheme) {
return \Drupal::service('file_system')->validScheme($scheme);
@trigger_error('file_stream_wrapper_valid_scheme() is deprecated in drupal:8.0.0 and will be removed before drupal:9.0.0. Use \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::isValidScheme() instead. See https://www.drupal.org/node/3035273', E_USER_DEPRECATED);
return \Drupal::service('stream_wrapper_manager')->isValidScheme($scheme);
}
/**
@ -130,15 +135,15 @@ function file_stream_wrapper_valid_scheme($scheme) {
* For example, the URI "public://sample/test.txt" would return
* "sample/test.txt".
*
* @see file_uri_scheme()
* @deprecated in drupal:8.8.0 and will be removed from drupal:9.0.0. Use
* \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::getTarget()
* instead.
*
* @see https://www.drupal.org/node/3035273
*/
function file_uri_target($uri) {
// Remove the scheme from the URI and remove erroneous leading or trailing,
// forward-slashes and backslashes.
$target = trim(preg_replace('/^[\w\-]+:\/\/|^data:/', '', $uri), '\/');
// If nothing was replaced, the URI doesn't have a valid scheme.
return $target !== $uri ? $target : FALSE;
@trigger_error('file_uri_target() is deprecated in drupal:8.8.0 and will be removed before drupal:9.0.0. Use \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::getTarget() instead. See https://www.drupal.org/node/3035273', E_USER_DEPRECATED);
return StreamWrapperManager::getTarget($uri);
}
/**
@ -171,19 +176,16 @@ function file_default_scheme() {
*
* @return string
* The normalized URI.
*
* @deprecated in drupal:8.8.0 and will be removed from drupal:9.0.0. Use
* \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::normalizeUri()
* instead.
*
* @see https://www.drupal.org/node/3035273
*/
function file_stream_wrapper_uri_normalize($uri) {
$scheme = \Drupal::service('file_system')->uriScheme($uri);
if (file_stream_wrapper_valid_scheme($scheme)) {
$target = file_uri_target($uri);
if ($target !== FALSE) {
$uri = $scheme . '://' . $target;
}
}
return $uri;
@trigger_error('file_stream_wrapper_uri_normalize() is deprecated in drupal:8.8.0 and will be removed before drupal:9.0.0. Use \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::normalizeUri() instead. See https://www.drupal.org/node/3035273', E_USER_DEPRECATED);
return \Drupal::service('stream_wrapper_manager')->normalizeUri($uri);
}
/**
@ -216,7 +218,7 @@ function file_create_url($uri) {
// file server.
\Drupal::moduleHandler()->alter('file_url', $uri);
$scheme = \Drupal::service('file_system')->uriScheme($uri);
$scheme = StreamWrapperManager::getScheme($uri);
if (!$scheme) {
// Allow for:
@ -364,8 +366,12 @@ function file_ensure_htaccess() {
* if one is already present. Defaults to FALSE.
*/
function file_save_htaccess($directory, $private = TRUE, $force_overwrite = FALSE) {
if (\Drupal::service('file_system')->uriScheme($directory)) {
$htaccess_path = file_stream_wrapper_uri_normalize($directory . '/.htaccess');
/** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
if ($stream_wrapper_manager::getScheme($directory)) {
$htaccess_path = $stream_wrapper_manager->normalizeUri($directory . '/.htaccess');
}
else {
$directory = rtrim($directory, '/\\');
@ -421,14 +427,16 @@ function file_htaccess_lines($private = TRUE) {
*
* @return
* TRUE if the URI is allowed.
*
* @deprecated in drupal:8.8.0 and will be removed before drupal:9.0.0. Use
* \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::isValidUri()
* instead.
*
* @see https://www.drupal.org/node/3035273
*/
function file_valid_uri($uri) {
// Assert that the URI has an allowed scheme. Bare paths are not allowed.
$uri_scheme = \Drupal::service('file_system')->uriScheme($uri);
if (!file_stream_wrapper_valid_scheme($uri_scheme)) {
return FALSE;
}
return TRUE;
@trigger_error('file_valid_uri() is deprecated in drupal:8.8.0 and will be removed before drupal:9.0.0. Use \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::isValidUri() instead. See https://www.drupal.org/node/3035273', E_USER_DEPRECATED);
return \Drupal::service('stream_wrapper_manager')->isValidUri($uri);
}
/**
@ -586,7 +594,9 @@ function file_unmanaged_prepare($source, &$destination = NULL, $replace = FILE_E
*/
function file_build_uri($path) {
$uri = \Drupal::config('system.file')->get('default_scheme') . '://' . $path;
return file_stream_wrapper_uri_normalize($uri);
/** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
return $stream_wrapper_manager->normalizeUri($uri);
}
/**
@ -1001,7 +1011,9 @@ function file_scan_directory($dir, $mask, $options = [], $depth = 0) {
];
// Normalize $dir only once.
if ($depth == 0) {
$dir = file_stream_wrapper_uri_normalize($dir);
/** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
$dir = $stream_wrapper_manager->normalizeUri($dir);
$dir_has_slash = (substr($dir, -1) === '/');
}

View File

@ -3,6 +3,7 @@
namespace Drupal\Core\Asset;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
/**
* Optimizes a CSS asset.
@ -103,7 +104,7 @@ class CssOptimizer implements AssetOptimizerInterface {
// Stylesheets are relative one to each other. Start by adding a base path
// prefix provided by the parent stylesheet (if necessary).
if ($basepath && !file_uri_scheme($file)) {
if ($basepath && !StreamWrapperManager::getScheme($file)) {
$file = $basepath . '/' . $file;
}
// Store the parent base path to restore it later.

View File

@ -8,6 +8,7 @@ use Drupal\Core\Asset\Exception\InvalidLibraryFileException;
use Drupal\Core\Asset\Exception\LibraryDefinitionMissingLicenseException;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
use Drupal\Core\Theme\ThemeManagerInterface;
use Drupal\Component\Serialization\Exception\InvalidDataTypeException;
use Drupal\Component\Utility\NestedArray;
@ -38,6 +39,13 @@ class LibraryDiscoveryParser {
*/
protected $root;
/**
* The stream wrapper manager.
*
* @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface
*/
protected $streamWrapperManager;
/**
* Constructs a new LibraryDiscoveryParser instance.
*
@ -47,11 +55,18 @@ class LibraryDiscoveryParser {
* The module handler.
* @param \Drupal\Core\Theme\ThemeManagerInterface $theme_manager
* The theme manager.
* @param \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager
* The stream wrapper manager.
*/
public function __construct($root, ModuleHandlerInterface $module_handler, ThemeManagerInterface $theme_manager) {
public function __construct($root, ModuleHandlerInterface $module_handler, ThemeManagerInterface $theme_manager, StreamWrapperManagerInterface $stream_wrapper_manager = NULL) {
$this->root = $root;
$this->moduleHandler = $module_handler;
$this->themeManager = $theme_manager;
if (!$stream_wrapper_manager) {
@trigger_error('Calling LibraryDiscoveryParser::__construct() without the $stream_wrapper_manager argument is deprecated in drupal:8.8.0. The $stream_wrapper_manager argument will be required in drupal:9.0.0. See https://www.drupal.org/node/3035273', E_USER_DEPRECATED);
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
}
$this->streamWrapperManager = $stream_wrapper_manager;
}
/**
@ -183,7 +198,7 @@ class LibraryDiscoveryParser {
}
}
// A stream wrapper URI (e.g., public://generated_js/example.js).
elseif ($this->fileValidUri($source)) {
elseif ($this->streamWrapperManager->isValidUri($source)) {
$options['data'] = $source;
}
// A regular URI (e.g., http://example.com/example.js) without
@ -393,10 +408,15 @@ class LibraryDiscoveryParser {
}
/**
* Wraps file_valid_uri().
* Wraps \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::isValidUri().
*
* @deprecated in drupal:8.8.0 and will be removed before drupal:9.0.0. Use
* \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::isValidUri()
* instead.
*/
protected function fileValidUri($source) {
return file_valid_uri($source);
@trigger_error('fileValidUri() is deprecated in Drupal 8.8.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::isValidUri() instead. See https://www.drupal.org/node/3035273', E_USER_DEPRECATED);
return $this->streamWrapperManager->isValidUri($source);
}
/**

View File

@ -10,6 +10,7 @@ use Drupal\Core\File\Exception\FileNotExistsException;
use Drupal\Core\File\Exception\FileWriteException;
use Drupal\Core\File\Exception\NotRegularFileException;
use Drupal\Core\Site\Settings;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
use Psr\Log\LoggerInterface;
@ -110,8 +111,7 @@ class FileSystem implements FileSystemInterface {
* {@inheritdoc}
*/
public function unlink($uri, $context = NULL) {
$scheme = $this->uriScheme($uri);
if (!$this->validScheme($scheme) && (substr(PHP_OS, 0, 3) == 'WIN')) {
if (!$this->streamWrapperManager->isValidUri($uri) && (substr(PHP_OS, 0, 3) == 'WIN')) {
chmod($uri, 0600);
}
if ($context) {
@ -140,9 +140,9 @@ class FileSystem implements FileSystemInterface {
* {@inheritdoc}
*/
public function dirname($uri) {
$scheme = $this->uriScheme($uri);
$scheme = StreamWrapperManager::getScheme($uri);
if ($this->validScheme($scheme)) {
if ($this->streamWrapperManager->isValidScheme($scheme)) {
return $this->streamWrapperManager->getViaScheme($scheme)->dirname($uri);
}
else {
@ -181,7 +181,7 @@ class FileSystem implements FileSystemInterface {
// If the URI has a scheme, don't override the umask - schemes can handle
// this issue in their own implementation.
if ($this->uriScheme($uri)) {
if (StreamWrapperManager::getScheme($uri)) {
return $this->mkdirCall($uri, $mode, $recursive, $context);
}
@ -252,8 +252,7 @@ class FileSystem implements FileSystemInterface {
* {@inheritdoc}
*/
public function rmdir($uri, $context = NULL) {
$scheme = $this->uriScheme($uri);
if (!$this->validScheme($scheme) && (substr(PHP_OS, 0, 3) == 'WIN')) {
if (!$this->streamWrapperManager->isValidUri($uri) && (substr(PHP_OS, 0, 3) == 'WIN')) {
chmod($uri, 0700);
}
if ($context) {
@ -268,9 +267,9 @@ class FileSystem implements FileSystemInterface {
* {@inheritdoc}
*/
public function tempnam($directory, $prefix) {
$scheme = $this->uriScheme($directory);
$scheme = StreamWrapperManager::getScheme($directory);
if ($this->validScheme($scheme)) {
if ($this->streamWrapperManager->isValidScheme($scheme)) {
$wrapper = $this->streamWrapperManager->getViaScheme($scheme);
if ($filename = tempnam($wrapper->getDirectoryPath(), $prefix)) {
@ -290,22 +289,16 @@ class FileSystem implements FileSystemInterface {
* {@inheritdoc}
*/
public function uriScheme($uri) {
if (preg_match('/^([\w\-]+):\/\/|^(data):/', $uri, $matches)) {
// The scheme will always be the last element in the matches array.
return array_pop($matches);
}
return FALSE;
@trigger_error('FileSystem::uriScheme() is deprecated in drupal:8.8.0. It will be removed from drupal:9.0.0. Use \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::getScheme() instead. See https://www.drupal.org/node/3035273', E_USER_DEPRECATED);
return StreamWrapperManager::getScheme($uri);
}
/**
* {@inheritdoc}
*/
public function validScheme($scheme) {
if (!$scheme) {
return FALSE;
}
return class_exists($this->streamWrapperManager->getClass($scheme));
@trigger_error('FileSystem::validScheme() is deprecated in drupal:8.8.0 and will be removed before drupal:9.0.0. Use \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::isValidScheme() instead. See https://www.drupal.org/node/3035273', E_USER_DEPRECATED);
return $this->streamWrapperManager->isValidScheme($scheme);
}
/**
@ -397,8 +390,7 @@ class FileSystem implements FileSystemInterface {
// Ensure compatibility with Windows.
// @see \Drupal\Core\File\FileSystemInterface::unlink().
$scheme = $this->uriScheme($source);
if (!$this->validScheme($scheme) && (substr(PHP_OS, 0, 3) == 'WIN')) {
if (!$this->streamWrapperManager->isValidUri($source) && (substr(PHP_OS, 0, 3) == 'WIN')) {
chmod($source, 0600);
}
// Attempt to resolve the URIs. This is necessary in certain
@ -481,7 +473,7 @@ class FileSystem implements FileSystemInterface {
// Prepare the destination directory.
if ($this->prepareDirectory($destination)) {
// The destination is already a directory, so append the source basename.
$destination = file_stream_wrapper_uri_normalize($destination . '/' . $this->basename($source));
$destination = $this->streamWrapperManager->normalizeUri($destination . '/' . $this->basename($source));
}
else {
// Perhaps $destination is a dir/file?
@ -537,7 +529,7 @@ class FileSystem implements FileSystemInterface {
* {@inheritdoc}
*/
public function prepareDirectory(&$directory, $options = self::MODIFY_PERMISSIONS) {
if (!$this->validScheme($this->uriScheme($directory))) {
if (!$this->streamWrapperManager->isValidUri($directory)) {
// Only trim if we're not dealing with a stream.
$directory = rtrim($directory, '/\\');
}

View File

@ -242,7 +242,11 @@ interface FileSystemInterface {
* A string containing the name of the scheme, or FALSE if none. For
* example, the URI "public://example.txt" would return "public".
*
* @see file_uri_target()
* @deprecated in drupal:8.8.0 and will be removed from drupal:9.0.0. Use
* Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::getScheme()
* instead.
*
* @see https://www.drupal.org/node/3035273
*/
public function uriScheme($uri);
@ -259,6 +263,12 @@ interface FileSystemInterface {
* @return bool
* Returns TRUE if the string is the name of a validated stream, or FALSE if
* the scheme does not have a registered handler.
*
* @deprecated in drupal:8.0.0 and will be removed before Drupal 9.0.0. Use
* Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::isValidScheme()
* instead.
*
* @see https://www.drupal.org/node/3035273
*/
public function validScheme($scheme);

View File

@ -5,6 +5,8 @@
* Hooks related to the File management system.
*/
use Drupal\Core\StreamWrapper\StreamWrapperManager;
/**
* @addtogroup hooks
* @{
@ -30,8 +32,8 @@
*/
function hook_file_download($uri) {
// Check to see if this is a config download.
$scheme = file_uri_scheme($uri);
$target = file_uri_target($uri);
$scheme = StreamWrapperManager::getScheme($uri);
$target = StreamWrapperManager::getTarget($uri);
if ($scheme == 'temporary' && $target == 'config.tar.gz') {
return [
'Content-disposition' => 'attachment; filename="config.tar.gz"',
@ -70,7 +72,10 @@ function hook_file_url_alter(&$uri) {
// so don't support this in the common case.
$schemes = ['public'];
$scheme = file_uri_scheme($uri);
/** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
$scheme = $stream_wrapper_manager::getScheme($uri);
// Only serve shipped files and public created files from the CDN.
if (!$scheme || in_array($scheme, $schemes)) {
@ -80,8 +85,8 @@ function hook_file_url_alter(&$uri) {
}
// Public created files.
else {
$wrapper = \Drupal::service('stream_wrapper_manager')->getViaScheme($scheme);
$path = $wrapper->getDirectoryPath() . '/' . file_uri_target($uri);
$wrapper = $stream_wrapper_manager->getViaScheme($scheme);
$path = $wrapper->getDirectoryPath() . '/' . $stream_wrapper_manager::getTarget($uri);
}
// Clean up Windows paths.

View File

@ -100,7 +100,7 @@ class StreamWrapperManager implements ContainerAwareInterface, StreamWrapperMana
* {@inheritdoc}
*/
public function getViaUri($uri) {
$scheme = file_uri_scheme($uri);
$scheme = static::getScheme($uri);
return $this->getWrapper($scheme, $uri);
}
@ -208,4 +208,75 @@ class StreamWrapperManager implements ContainerAwareInterface, StreamWrapperMana
}
}
/**
* {@inheritdoc}
*/
public static function getTarget($uri) {
// Remove the scheme from the URI and remove erroneous leading or trailing,
// forward-slashes and backslashes.
$target = trim(preg_replace('/^[\w\-]+:\/\/|^data:/', '', $uri), '\/');
// If nothing was replaced, the URI doesn't have a valid scheme.
return $target !== $uri ? $target : FALSE;
}
/**
* Normalizes a URI by making it syntactically correct.
*
* A stream is referenced as "scheme://target".
*
* The following actions are taken:
* - Remove trailing slashes from target
* - Trim erroneous leading slashes from target. e.g. ":///" becomes "://".
*
* @param string $uri
* String reference containing the URI to normalize.
*
* @return string
* The normalized URI.
*/
public function normalizeUri($uri) {
$scheme = $this->getScheme($uri);
if ($this->isValidScheme($scheme)) {
$target = $this->getTarget($uri);
if ($target !== FALSE) {
$uri = $scheme . '://' . $target;
}
}
return $uri;
}
/**
* {@inheritdoc}
*/
public static function getScheme($uri) {
if (preg_match('/^([\w\-]+):\/\/|^(data):/', $uri, $matches)) {
// The scheme will always be the last element in the matches array.
return array_pop($matches);
}
return FALSE;
}
/**
* {@inheritdoc}
*/
public function isValidScheme($scheme) {
if (!$scheme) {
return FALSE;
}
return class_exists($this->getClass($scheme));
}
/**
* {@inheritdoc}
*/
public function isValidUri($uri) {
// Assert that the URI has an allowed scheme. Bare paths are not allowed.
return $this->isValidScheme($this->getScheme($uri));
}
}

View File

@ -169,4 +169,81 @@ interface StreamWrapperManagerInterface {
*/
public function registerWrapper($scheme, $class, $type);
/**
* Returns the part of a URI after the schema.
*
* @param string $uri
* A stream, referenced as "scheme://target" or "data:target".
*
* @return string|bool
* A string containing the target (path), or FALSE if none.
* For example, the URI "public://sample/test.txt" would return
* "sample/test.txt".
*
* @see \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::getScheme()
*/
public static function getTarget($uri);
/**
* Normalizes a URI by making it syntactically correct.
*
* A stream is referenced as "scheme://target".
*
* The following actions are taken:
* - Remove trailing slashes from target
* - Trim erroneous leading slashes from target. e.g. ":///" becomes "://".
*
* @param string $uri
* String reference containing the URI to normalize.
*
* @return string
* The normalized URI.
*/
public function normalizeUri($uri);
/**
* Returns the scheme of a URI (e.g. a stream).
*
* @param string $uri
* A stream, referenced as "scheme://target" or "data:target".
*
* @return string|bool
* A string containing the name of the scheme, or FALSE if none. For
* example, the URI "public://example.txt" would return "public".
*
* @see \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::getTarget()
*/
public static function getScheme($uri);
/**
* Checks that the scheme of a stream URI is valid.
*
* Confirms that there is a registered stream handler for the provided scheme
* and that it is callable. This is useful if you want to confirm a valid
* scheme without creating a new instance of the registered handler.
*
* @param string $scheme
* A URI scheme, a stream is referenced as "scheme://target".
*
* @return bool
* Returns TRUE if the string is the name of a validated stream, or FALSE if
* the scheme does not have a registered handler.
*/
public function isValidScheme($scheme);
/**
* Determines whether the URI has a valid scheme for file API operations.
*
* There must be a scheme and it must be a Drupal-provided scheme like
* 'public', 'private', 'temporary', or an extension provided with
* hook_stream_wrappers().
*
* @param string $uri
* The URI to be tested.
*
* @return bool
* TRUE if the URI is valid.
*/
public function isValidUri($uri);
}

View File

@ -5,8 +5,9 @@
* Allows site administrators to modify configuration.
*/
use Drupal\Core\Url;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
use Drupal\Core\Url;
/**
* Implements hook_help().
@ -63,8 +64,8 @@ function config_help($route_name, RouteMatchInterface $route_match) {
* Implements hook_file_download().
*/
function config_file_download($uri) {
$scheme = file_uri_scheme($uri);
$target = file_uri_target($uri);
$scheme = StreamWrapperManager::getScheme($uri);
$target = StreamWrapperManager::getTarget($uri);
if ($scheme == 'temporary' && $target == 'config.tar.gz') {
if (\Drupal::currentUser()->hasPermission('export configuration')) {
$request = \Drupal::request();

View File

@ -77,7 +77,7 @@ class ConfigController implements ContainerInjectionInterface {
$container->get('config.storage'),
$container->get('config.storage.sync'),
$container->get('config.manager'),
new FileDownloadController(),
FileDownloadController::create($container),
$container->get('diff.formatter'),
$container->get('file_system'),
$container->get('config.storage.export')

View File

@ -157,7 +157,10 @@ function file_load($fid, $reset = FALSE) {
function file_copy(FileInterface $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
if (!file_valid_uri($destination)) {
/** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
if (!$stream_wrapper_manager->isValidUri($destination)) {
if (($realpath = $file_system->realpath($source->getFileUri())) !== FALSE) {
\Drupal::logger('file')->notice('File %file (%realpath) could not be copied because the destination %destination is invalid. This is often caused by improper use of file_copy() or a missing stream wrapper.', ['%file' => $source->getFileUri(), '%realpath' => $realpath, '%destination' => $destination]);
}
@ -237,7 +240,10 @@ function file_copy(FileInterface $source, $destination = NULL, $replace = FILE_E
function file_move(FileInterface $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
if (!file_valid_uri($destination)) {
/** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
if (!$stream_wrapper_manager->isValidUri($destination)) {
if (($realpath = $file_system->realpath($source->getFileUri())) !== FALSE) {
\Drupal::logger('file')->notice('File %file (%realpath) could not be moved because the destination %destination is invalid. This may be caused by improper use of file_move() or a missing stream wrapper.', ['%file' => $source->getFileUri(), '%realpath' => $realpath, '%destination' => $destination]);
}
@ -561,7 +567,10 @@ function file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAM
if (empty($destination)) {
$destination = \Drupal::config('system.file')->get('default_scheme') . '://';
}
if (!file_valid_uri($destination)) {
/** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
if (!$stream_wrapper_manager->isValidUri($destination)) {
\Drupal::logger('file')->notice('The data could not be saved because the destination %destination is invalid. This may be caused by improper use of file_save_data() or a missing stream wrapper.', ['%destination' => $destination]);
\Drupal::messenger()->addError(t('The data could not be saved because the destination is invalid. More information is available in the system log.'));
return FALSE;
@ -716,6 +725,9 @@ function file_cron() {
$age = \Drupal::config('system.file')->get('temporary_maximum_age');
$file_storage = \Drupal::entityTypeManager()->getStorage('file');
/** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
// Only delete temporary files if older than $age. Note that automatic cleanup
// is disabled if $age set to 0.
if ($age) {
@ -729,7 +741,7 @@ function file_cron() {
$references = \Drupal::service('file.usage')->listUsage($file);
if (empty($references)) {
if (!file_exists($file->getFileUri())) {
if (!file_valid_uri($file->getFileUri())) {
if (!$stream_wrapper_manager->isValidUri($file->getFileUri())) {
\Drupal::logger('file system')->warning('Temporary file "%path" that was deleted during garbage collection did not exist on the filesystem. This could be caused by a missing stream wrapper.', ['%path' => $file->getFileUri()]);
}
else {
@ -1029,9 +1041,12 @@ function _file_save_upload_single(\SplFileInfo $file_info, $form_field_name, $va
$destination = 'temporary://';
}
/** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
// Assert that the destination contains a valid stream.
$destination_scheme = file_uri_scheme($destination);
if (!file_stream_wrapper_valid_scheme($destination_scheme)) {
$destination_scheme = $stream_wrapper_manager::getScheme($destination);
if (!$stream_wrapper_manager->isValidScheme($destination_scheme)) {
\Drupal::messenger()->addError(t('The file could not be uploaded because the destination %destination is invalid.', ['%destination' => $destination]));
return FALSE;
}

View File

@ -21,7 +21,7 @@ class FileAccessControlHandler extends EntityAccessControlHandler {
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
/** @var \Drupal\file\FileInterface $entity */
if ($operation == 'download' || $operation == 'view') {
if (\Drupal::service('file_system')->uriScheme($entity->getFileUri()) === 'public') {
if (\Drupal::service('stream_wrapper_manager')->getScheme($entity->getFileUri()) === 'public') {
if ($operation === 'download') {
return AccessResult::allowed();
}

View File

@ -198,6 +198,9 @@ function file_test_file_predelete(File $file) {
* Implements hook_file_url_alter().
*/
function file_test_file_url_alter(&$uri) {
/** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
// Only run this hook when this variable is set. Otherwise, we'd have to add
// another hidden test module just for this hook.
$alter_mode = \Drupal::state()->get('file_test.hook_file_url_alter');
@ -212,7 +215,7 @@ function file_test_file_url_alter(&$uri) {
// so don't support this in the common case.
$schemes = ['public'];
$scheme = file_uri_scheme($uri);
$scheme = $stream_wrapper_manager::getScheme($uri);
// Only serve shipped files and public created files from the CDN.
if (!$scheme || in_array($scheme, $schemes)) {
@ -222,8 +225,8 @@ function file_test_file_url_alter(&$uri) {
}
// Public created files.
else {
$wrapper = \Drupal::service('stream_wrapper_manager')->getViaScheme($scheme);
$path = $wrapper->getDirectoryPath() . '/' . file_uri_target($uri);
$wrapper = $stream_wrapper_manager->getViaScheme($scheme);
$path = $wrapper->getDirectoryPath() . '/' . $stream_wrapper_manager::getTarget($uri);
}
// Clean up Windows paths.
@ -244,7 +247,7 @@ function file_test_file_url_alter(&$uri) {
elseif ($alter_mode == 'root-relative') {
// Only serve shipped files and public created files with root-relative
// URLs.
$scheme = file_uri_scheme($uri);
$scheme = $stream_wrapper_manager::getScheme($uri);
if (!$scheme || $scheme == 'public') {
// Shipped files.
if (!$scheme) {
@ -252,8 +255,8 @@ function file_test_file_url_alter(&$uri) {
}
// Public created files.
else {
$wrapper = \Drupal::service('stream_wrapper_manager')->getViaScheme($scheme);
$path = $wrapper->getDirectoryPath() . '/' . file_uri_target($uri);
$wrapper = $stream_wrapper_manager->getViaScheme($scheme);
$path = $wrapper->getDirectoryPath() . '/' . $stream_wrapper_manager::getTarget($uri);
}
// Clean up Windows paths.
@ -267,7 +270,7 @@ function file_test_file_url_alter(&$uri) {
elseif ($alter_mode == 'protocol-relative') {
// Only serve shipped files and public created files with protocol-relative
// URLs.
$scheme = file_uri_scheme($uri);
$scheme = $stream_wrapper_manager::getScheme($uri);
if (!$scheme || $scheme == 'public') {
// Shipped files.
if (!$scheme) {
@ -275,8 +278,8 @@ function file_test_file_url_alter(&$uri) {
}
// Public created files.
else {
$wrapper = \Drupal::service('stream_wrapper_manager')->getViaScheme($scheme);
$path = $wrapper->getDirectoryPath() . '/' . file_uri_target($uri);
$wrapper = $stream_wrapper_manager->getViaScheme($scheme);
$path = $wrapper->getDirectoryPath() . '/' . $stream_wrapper_manager::getTarget($uri);
}
// Clean up Windows paths.

View File

@ -124,7 +124,11 @@ class FileItemTest extends FieldKernelTestBase {
$this->entityValidateAndSave($entity);
// Verify that the sample file was stored in the correct directory.
$uri = $entity->file_test->entity->getFileUri();
$this->assertEqual($this->directory, dirname(file_uri_target($uri)));
/** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
$this->assertEqual($this->directory, dirname($stream_wrapper_manager::getTarget($uri)));
// Make sure the computed files reflects updates to the file.
file_put_contents('public://example-3.txt', $this->randomMachineName());

View File

@ -2,6 +2,7 @@
namespace Drupal\Tests\file\Kernel;
use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
use Drupal\file\Entity\File;
/**
@ -20,7 +21,9 @@ class SaveDataTest extends FileManagedUnitTestBase {
$result = file_save_data($contents);
$this->assertTrue($result, 'Unnamed file saved correctly.');
$this->assertEqual(\Drupal::config('system.file')->get('default_scheme'), file_uri_scheme($result->getFileUri()), "File was placed in Drupal's files directory.");
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
assert($stream_wrapper_manager instanceof StreamWrapperManagerInterface);
$this->assertEqual(\Drupal::config('system.file')->get('default_scheme'), $stream_wrapper_manager::getScheme($result->getFileUri()), "File was placed in Drupal's files directory.");
$this->assertEqual($result->getFilename(), \Drupal::service('file_system')->basename($result->getFileUri()), "Filename was set to the file's basename.");
$this->assertEqual($contents, file_get_contents($result->getFileUri()), 'Contents of the file are correct.');
$this->assertEqual($result->getMimeType(), 'application/octet-stream', 'A MIME type was set.');
@ -45,7 +48,9 @@ class SaveDataTest extends FileManagedUnitTestBase {
$result = file_save_data($contents, 'public://' . $filename);
$this->assertTrue($result, 'Unnamed file saved correctly.');
$this->assertEqual('public', file_uri_scheme($result->getFileUri()), "File was placed in Drupal's files directory.");
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
assert($stream_wrapper_manager instanceof StreamWrapperManagerInterface);
$this->assertEqual('public', $stream_wrapper_manager::getScheme($result->getFileUri()), "File was placed in Drupal's files directory.");
$this->assertEqual($filename, \Drupal::service('file_system')->basename($result->getFileUri()), 'File was named correctly.');
$this->assertEqual($contents, file_get_contents($result->getFileUri()), 'Contents of the file are correct.');
$this->assertEqual($result->getMimeType(), 'text/plain', 'A MIME type was set.');
@ -69,7 +74,9 @@ class SaveDataTest extends FileManagedUnitTestBase {
$result = file_save_data($contents, $existing->getFileUri(), FILE_EXISTS_RENAME);
$this->assertTrue($result, 'File saved successfully.');
$this->assertEqual('public', file_uri_scheme($result->getFileUri()), "File was placed in Drupal's files directory.");
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
assert($stream_wrapper_manager instanceof StreamWrapperManagerInterface);
$this->assertEqual('public', $stream_wrapper_manager::getScheme($result->getFileUri()), "File was placed in Drupal's files directory.");
$this->assertEqual($result->getFilename(), $existing->getFilename(), 'Filename was set to the basename of the source, rather than that of the renamed file.');
$this->assertEqual($contents, file_get_contents($result->getFileUri()), 'Contents of the file are correct.');
$this->assertEqual($result->getMimeType(), 'application/octet-stream', 'A MIME type was set.');
@ -97,7 +104,9 @@ class SaveDataTest extends FileManagedUnitTestBase {
$result = file_save_data($contents, $existing->getFileUri(), FILE_EXISTS_REPLACE);
$this->assertTrue($result, 'File saved successfully.');
$this->assertEqual('public', file_uri_scheme($result->getFileUri()), "File was placed in Drupal's files directory.");
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
assert($stream_wrapper_manager instanceof StreamWrapperManagerInterface);
$this->assertEqual('public', $stream_wrapper_manager::getScheme($result->getFileUri()), "File was placed in Drupal's files directory.");
$this->assertEqual($result->getFilename(), $existing->getFilename(), 'Filename was set to the basename of the existing file, rather than preserving the original name.');
$this->assertEqual($contents, file_get_contents($result->getFileUri()), 'Contents of the file are correct.');
$this->assertEqual($result->getMimeType(), 'application/octet-stream', 'A MIME type was set.');

View File

@ -5,13 +5,14 @@
* Exposes global functionality for creating image styles.
*/
use Drupal\Core\Url;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\file\FileInterface;
use Drupal\field\FieldStorageConfigInterface;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
use Drupal\Core\Url;
use Drupal\field\FieldConfigInterface;
use Drupal\field\FieldStorageConfigInterface;
use Drupal\file\FileInterface;
use Drupal\image\Entity\ImageStyle;
/**
@ -179,7 +180,8 @@ function image_theme() {
* Control the access to files underneath the styles directory.
*/
function image_file_download($uri) {
$path = file_uri_target($uri);
$path = StreamWrapperManager::getTarget($uri);
// Private file access for image style derivatives.
if (strpos($path, 'styles/') === 0) {
@ -189,7 +191,7 @@ function image_file_download($uri) {
$args = array_slice($args, 3);
// Then the remaining parts are the path to the image.
$original_uri = file_uri_scheme($uri) . '://' . implode('/', $args);
$original_uri = StreamWrapperManager::getScheme($uri) . '://' . implode('/', $args);
// Check that the file exists and is an image.
$image = \Drupal::service('image.factory')->get($uri);
@ -434,7 +436,7 @@ function image_field_storage_config_update(FieldStorageConfigInterface $field_st
}
// If the upload destination changed, then move the file.
if ($file_new && (file_uri_scheme($file_new->getFileUri()) != $field_storage->getSetting('uri_scheme'))) {
if ($file_new && (StreamWrapperManager::getScheme($file_new->getFileUri()) != $field_storage->getSetting('uri_scheme'))) {
$directory = $field_storage->getSetting('uri_scheme') . '://default_images/';
\Drupal::service('file_system')->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY);
file_move($file_new, $directory . $file_new->getFilename());
@ -472,7 +474,7 @@ function image_field_config_update(FieldConfigInterface $field) {
}
// If the upload destination changed, then move the file.
if ($file_new && (file_uri_scheme($file_new->getFileUri()) != $field_storage->getSetting('uri_scheme'))) {
if ($file_new && (StreamWrapperManager::getScheme($file_new->getFileUri()) != $field_storage->getSetting('uri_scheme'))) {
$directory = $field_storage->getSetting('uri_scheme') . '://default_images/';
\Drupal::service('file_system')->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY);
file_move($file_new, $directory . $file_new->getFilename());

View File

@ -5,6 +5,7 @@ namespace Drupal\image\Controller;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Image\ImageFactory;
use Drupal\Core\Lock\LockBackendInterface;
use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
use Drupal\image\ImageStyleInterface;
use Drupal\system\FileDownloadController;
use Symfony\Component\DependencyInjection\ContainerInterface;
@ -48,8 +49,11 @@ class ImageStyleDownloadController extends FileDownloadController {
* The lock backend.
* @param \Drupal\Core\Image\ImageFactory $image_factory
* The image factory.
* @param \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager
* The stream wrapper manager.
*/
public function __construct(LockBackendInterface $lock, ImageFactory $image_factory) {
public function __construct(LockBackendInterface $lock, ImageFactory $image_factory, StreamWrapperManagerInterface $stream_wrapper_manager = NULL) {
parent::__construct($stream_wrapper_manager);
$this->lock = $lock;
$this->imageFactory = $image_factory;
$this->logger = $this->getLogger('image');
@ -61,7 +65,8 @@ class ImageStyleDownloadController extends FileDownloadController {
public static function create(ContainerInterface $container) {
return new static(
$container->get('lock'),
$container->get('image.factory')
$container->get('image.factory'),
$container->get('stream_wrapper_manager')
);
}
@ -102,7 +107,7 @@ class ImageStyleDownloadController extends FileDownloadController {
// The $target variable for a derivative of a style has
// styles/<style_name>/... as structure, so we check if the $target variable
// starts with styles/.
$valid = !empty($image_style) && file_stream_wrapper_valid_scheme($scheme);
$valid = !empty($image_style) && $this->streamWrapperManager->isValidScheme($scheme);
if (!$this->config('image.settings')->get('allow_insecure_derivatives') || strpos(ltrim($target, '\/'), 'styles/') === 0) {
$valid &= $request->query->get(IMAGE_DERIVATIVE_TOKEN) === $image_style->getPathToken($image_uri);
}

View File

@ -11,6 +11,7 @@ use Drupal\Core\File\Exception\FileException;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Routing\RequestHelper;
use Drupal\Core\Site\Settings;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
use Drupal\Core\Url;
use Drupal\image\ImageEffectPluginCollection;
use Drupal\image\ImageEffectInterface;
@ -173,11 +174,11 @@ class ImageStyle extends ConfigEntityBase implements ImageStyleInterface, Entity
* {@inheritdoc}
*/
public function buildUri($uri) {
$source_scheme = $scheme = $this->fileUriScheme($uri);
$source_scheme = $scheme = StreamWrapperManager::getScheme($uri);
$default_scheme = $this->fileDefaultScheme();
if ($source_scheme) {
$path = $this->fileUriTarget($uri);
$path = StreamWrapperManager::getTarget($uri);
// The scheme of derivative image files only needs to be computed for
// source files not stored in the default scheme.
if ($source_scheme != $default_scheme) {
@ -202,6 +203,10 @@ class ImageStyle extends ConfigEntityBase implements ImageStyleInterface, Entity
*/
public function buildUrl($path, $clean_urls = NULL) {
$uri = $this->buildUri($path);
/** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
// The token query is added even if the
// 'image.settings:allow_insecure_derivatives' configuration is TRUE, so
// that the emitted links remain valid if it is changed back to the default
@ -214,7 +219,7 @@ class ImageStyle extends ConfigEntityBase implements ImageStyleInterface, Entity
$token_query = [];
if (!\Drupal::config('image.settings')->get('suppress_itok_output')) {
// The passed $path variable can be either a relative path or a full URI.
$original_uri = file_uri_scheme($path) ? file_stream_wrapper_uri_normalize($path) : file_build_uri($path);
$original_uri = $stream_wrapper_manager::getScheme($path) ? $stream_wrapper_manager->normalizeUri($path) : file_build_uri($path);
$token_query = [IMAGE_DERIVATIVE_TOKEN => $this->getPathToken($original_uri)];
}
@ -234,9 +239,9 @@ class ImageStyle extends ConfigEntityBase implements ImageStyleInterface, Entity
// 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 = $this->getStreamWrapperManager()->getViaUri($uri)->getDirectoryPath();
return Url::fromUri('base:' . $directory_path . '/' . file_uri_target($uri), ['absolute' => TRUE, 'query' => $token_query])->toString();
if ($clean_urls === FALSE && $stream_wrapper_manager::getScheme($uri) == 'public' && !file_exists($uri)) {
$directory_path = $stream_wrapper_manager->getViaUri($uri)->getDirectoryPath();
return Url::fromUri('base:' . $directory_path . '/' . $stream_wrapper_manager::getTarget($uri), ['absolute' => TRUE, 'query' => $token_query])->toString();
}
$file_url = file_create_url($uri);
@ -505,16 +510,18 @@ class ImageStyle extends ConfigEntityBase implements ImageStyleInterface, Entity
* @param string $uri
* A stream, referenced as "scheme://target" or "data:target".
*
* @see file_uri_target()
*
* @todo: Remove when https://www.drupal.org/node/2050759 is in.
*
* @return string
* A string containing the name of the scheme, or FALSE if none. For
* example, the URI "public://example.txt" would return "public".
*
* @deprecated in drupal:8.8.0 and will be removed from drupal:9.0.0. Use
* \Drupal\Core\StreamWrapper\StreamWrapperManager::getTarget() instead.
*
* @see https://www.drupal.org/node/3035273
*/
protected function fileUriScheme($uri) {
return file_uri_scheme($uri);
@trigger_error('fileUriTarget() is deprecated in drupal:8.8.0. It will be removed from drupal:9.0.0. See https://www.drupal.org/node/3035273', E_USER_DEPRECATED);
return StreamWrapperManager::getScheme($uri);
}
/**
@ -525,17 +532,19 @@ class ImageStyle extends ConfigEntityBase implements ImageStyleInterface, Entity
* @param string $uri
* A stream, referenced as "scheme://target" or "data:target".
*
* @see file_uri_scheme()
*
* @todo: Convert file_uri_target() into a proper injectable service.
*
* @return string|bool
* A string containing the target (path), or FALSE if none.
* For example, the URI "public://sample/test.txt" would return
* "sample/test.txt".
*
* @deprecated in drupal:8.8.0 and will be removed from drupal:9.0.0. Use
* \Drupal\Core\StreamWrapper\StreamWrapperManager::getUriTarget() instead.
*
* @see https://www.drupal.org/node/3035273
*/
protected function fileUriTarget($uri) {
return file_uri_target($uri);
@trigger_error('fileUriTarget() is deprecated in drupal:8.8.0. It will be removed from drupal:9.0.0. See https://www.drupal.org/node/3035273', E_USER_DEPRECATED);
return StreamWrapperManager::getTarget($uri);
}
/**

View File

@ -2,13 +2,14 @@
namespace Drupal\Tests\image\Functional;
use Drupal\Core\Url;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
use Drupal\Core\Url;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Tests\TestFileCreationTrait;
use Drupal\Tests\system\Functional\Cache\AssertPageCacheContextsAndTagsTrait;
use Drupal\user\RoleInterface;
use Drupal\image\Entity\ImageStyle;
use Drupal\Tests\system\Functional\Cache\AssertPageCacheContextsAndTagsTrait;
use Drupal\Tests\TestFileCreationTrait;
use Drupal\user\RoleInterface;
/**
* Tests the display of image fields.
@ -451,7 +452,8 @@ class ImageFieldDisplayTest extends ImageFieldTestBase {
$private_field_storage = FieldStorageConfig::loadByName('node', $private_field_name);
$default_image = $private_field_storage->getSetting('default_image');
$file = \Drupal::service('entity.repository')->loadEntityByUuid('file', $default_image['uuid']);
$this->assertEqual('private', file_uri_scheme($file->getFileUri()), 'Default image uses private:// scheme.');
$this->assertEqual('private', StreamWrapperManager::getScheme($file->getFileUri()), 'Default image uses private:// scheme.');
$this->assertTrue($file->isPermanent(), 'The default image status is permanent.');
// Create a new node with no image attached and ensure that default private
// image is displayed.

View File

@ -3,6 +3,7 @@
namespace Drupal\Tests\image\Functional;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
use Drupal\image\Entity\ImageStyle;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\Tests\BrowserTestBase;
@ -189,7 +190,7 @@ class ImageStylesPathAndUrlTest extends BrowserTestBase {
// match the desired scheme before testing this, then switch it back to the
// "temporary" scheme used throughout this test afterwards.
$this->config('system.file')->set('default_scheme', $scheme)->save();
$relative_path = file_uri_target($original_uri);
$relative_path = StreamWrapperManager::getTarget($original_uri);
$generate_url_from_relative_path = $this->style->buildUrl($relative_path, $clean_url);
$this->assertEqual($generate_url, $generate_url_from_relative_path);
$this->config('system.file')->set('default_scheme', 'temporary')->save();

View File

@ -5,6 +5,7 @@ namespace Drupal\Tests\image\Kernel;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\StreamWrapper\PrivateStream;
use Drupal\Core\StreamWrapper\PublicStream;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
use Drupal\file_test\StreamWrapper\DummyReadOnlyStreamWrapper;
use Drupal\file_test\StreamWrapper\DummyRemoteReadOnlyStreamWrapper;
use Drupal\file_test\StreamWrapper\DummyStreamWrapper;
@ -75,7 +76,7 @@ class ImageStyleCustomStreamWrappersTest extends KernelTestBase {
*/
public function testCustomStreamWrappers($source_scheme, $expected_scheme) {
$derivative_uri = $this->imageStyle->buildUri("$source_scheme://some/path/image.png");
$derivative_scheme = $this->fileSystem->uriScheme($derivative_uri);
$derivative_scheme = StreamWrapperManager::getScheme($derivative_uri);
// Check that the derivative scheme is the expected scheme.
$this->assertSame($expected_scheme, $derivative_scheme);

View File

@ -2,8 +2,8 @@
namespace Drupal\Tests\image\Unit;
use Drupal\Tests\UnitTestCase;
use Drupal\Component\Utility\Crypt;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\image\Entity\ImageStyle
@ -69,12 +69,6 @@ class ImageStyleTest extends UnitTestCase {
$image_style->expects($this->any())
->method('getImageEffectPluginManager')
->will($this->returnValue($effectManager));
$image_style->expects($this->any())
->method('fileUriScheme')
->will($this->returnCallback([$this, 'fileUriScheme']));
$image_style->expects($this->any())
->method('fileUriTarget')
->will($this->returnCallback([$this, 'fileUriTarget']));
$image_style->expects($this->any())
->method('fileDefaultScheme')
->will($this->returnCallback([$this, 'fileDefaultScheme']));
@ -203,30 +197,6 @@ class ImageStyleTest extends UnitTestCase {
$this->assertEquals(substr(Crypt::hmacBase64($image_style->id() . ':' . 'public://test.jpeg', $private_key . $hash_salt), 0, 8), $image_style->getPathToken('public://test.jpeg'));
}
/**
* Mock function for ImageStyle::fileUriScheme().
*/
public function fileUriScheme($uri) {
if (preg_match('/^([\w\-]+):\/\/|^(data):/', $uri, $matches)) {
// The scheme will always be the last element in the matches array.
return array_pop($matches);
}
return FALSE;
}
/**
* Mock function for ImageStyle::fileUriTarget().
*/
public function fileUriTarget($uri) {
// Remove the scheme from the URI and remove erroneous leading or trailing,
// forward-slashes and backslashes.
$target = trim(preg_replace('/^[\w\-]+:\/\/|^data:/', '', $uri), '\/');
// If nothing was replaced, the URI doesn't have a valid scheme.
return $target !== $uri ? $target : FALSE;
}
/**
* Mock function for ImageStyle::fileDefaultScheme().
*/

View File

@ -5,6 +5,8 @@
* Common API for interface translation.
*/
use Drupal\Core\StreamWrapper\StreamWrapperManager;
/**
* Comparison result of source files timestamps.
*
@ -376,7 +378,7 @@ function locale_cron_fill_queue() {
* TRUE if the $uri is a remote file.
*/
function _locale_translation_file_is_remote($uri) {
$scheme = file_uri_scheme($uri);
$scheme = StreamWrapperManager::getScheme($uri);
if ($scheme) {
return !\Drupal::service('file_system')->realpath($scheme . '://');
}

View File

@ -342,7 +342,11 @@ class OEmbed extends MediaSourceBase implements OEmbedInterface {
*/
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
$thumbnails_directory = $form_state->getValue('thumbnails_directory');
if (!file_valid_uri($thumbnails_directory)) {
/** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
if (!$stream_wrapper_manager->isValidUri($thumbnails_directory)) {
$form_state->setErrorByName('thumbnails_directory', $this->t('@path is not a valid path.', [
'@path' => $thumbnails_directory,
]));

View File

@ -6,6 +6,7 @@ use Drupal\Core\File\Exception\FileException;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StreamWrapper\LocalStream;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
use Drupal\migrate\MigrateException;
use Drupal\migrate\MigrateExecutableInterface;
@ -243,7 +244,7 @@ class FileCopy extends FileProcessBase implements ContainerFactoryPluginInterfac
* @return bool
*/
protected function isLocalUri($uri) {
$scheme = $this->fileSystem->uriScheme($uri);
$scheme = StreamWrapperManager::getScheme($uri);
// The vfs scheme is vfsStream, which is used in testing. vfsStream is a
// simulated file system that exists only in memory, but should be treated

View File

@ -3,16 +3,48 @@
namespace Drupal\system;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
/**
* System file controller.
*/
class FileDownloadController extends ControllerBase {
/**
* The stream wrapper manager.
*
* @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface
*/
protected $streamWrapperManager;
/**
* FileDownloadController constructor.
*
* @param \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $streamWrapperManager
* The stream wrapper manager.
*/
public function __construct(StreamWrapperManagerInterface $streamWrapperManager = NULL) {
if (!$streamWrapperManager) {
@trigger_error('Calling FileDownloadController::__construct() without the $streamWrapperManager argument is deprecated in drupal:8.8.0. The $streamWrapperManager argument will be required in drupal:9.0.0. See https://www.drupal.org/node/3035273', E_USER_DEPRECATED);
$streamWrapperManager = \Drupal::service('stream_wrapper_manager');
}
$this->streamWrapperManager = $streamWrapperManager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('stream_wrapper_manager')
);
}
/**
* Handles private file transfers.
*
@ -43,7 +75,7 @@ class FileDownloadController extends ControllerBase {
// Merge remaining path arguments into relative file path.
$uri = $scheme . '://' . $target;
if (file_stream_wrapper_valid_scheme($scheme) && file_exists($uri)) {
if ($this->streamWrapperManager->isValidScheme($scheme) && file_exists($uri)) {
// Let other modules provide headers and controls access to the file.
$headers = $this->moduleHandler()->invokeAll('file_download', [$uri]);

View File

@ -8,6 +8,7 @@ use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\StreamWrapper\PublicStream;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
@ -295,8 +296,9 @@ class ThemeSettingsForm extends ConfigFormBase {
// directory; stream wrappers are not end-user friendly.
$original_path = $element['#default_value'];
$friendly_path = NULL;
if (file_uri_scheme($original_path) == 'public') {
$friendly_path = file_uri_target($original_path);
if (StreamWrapperManager::getScheme($original_path) == 'public') {
$friendly_path = StreamWrapperManager::getTarget($original_path);
$element['#default_value'] = $friendly_path;
}
@ -313,7 +315,7 @@ class ThemeSettingsForm extends ConfigFormBase {
$element['#description'] = t('Examples: <code>@implicit-public-file</code> (for a file in the public filesystem), <code>@explicit-file</code>, or <code>@local-file</code>.', [
'@implicit-public-file' => isset($friendly_path) ? $friendly_path : $default,
'@explicit-file' => file_uri_scheme($original_path) !== FALSE ? $original_path : 'public://' . $default,
'@explicit-file' => StreamWrapperManager::getScheme($original_path) !== FALSE ? $original_path : 'public://' . $default,
'@local-file' => $local_file,
]);
}
@ -526,7 +528,7 @@ class ThemeSettingsForm extends ConfigFormBase {
return $path;
}
// Prepend 'public://' for relative file paths within public filesystem.
if (file_uri_scheme($path) === FALSE) {
if (StreamWrapperManager::getScheme($path) === FALSE) {
$path = 'public://' . $path;
}
if (is_file($path)) {

View File

@ -10,6 +10,7 @@ use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\ImageToolkit\ImageToolkitBase;
use Drupal\Core\ImageToolkit\ImageToolkitOperationManagerInterface;
use Drupal\Core\StreamWrapper\StreamWrapperInterface;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
@ -230,9 +231,9 @@ class GDToolkit extends ImageToolkitBase {
* {@inheritdoc}
*/
public function save($destination) {
$scheme = file_uri_scheme($destination);
$scheme = StreamWrapperManager::getScheme($destination);
// Work around lack of stream wrapper support in imagejpeg() and imagepng().
if ($scheme && file_stream_wrapper_valid_scheme($scheme)) {
if ($scheme && $this->streamWrapperManager->isValidScheme($scheme)) {
// If destination is not local, save image to temporary local file.
$local_wrappers = $this->streamWrapperManager->getWrappers(StreamWrapperInterface::LOCAL);
if (!isset($local_wrappers[$scheme])) {

View File

@ -3,6 +3,7 @@
namespace Drupal\Tests\system\Functional\System;
use Drupal\Core\StreamWrapper\PublicStream;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\TestFileCreationTrait;
@ -64,12 +65,12 @@ class ThemeTest extends BrowserTestBase {
$supported_paths = [
// Raw stream wrapper URI.
$file->uri => [
'form' => file_uri_target($file->uri),
'form' => StreamWrapperManager::getTarget($file->uri),
'src' => file_url_transform_relative(file_create_url($file->uri)),
],
// Relative path within the public filesystem.
file_uri_target($file->uri) => [
'form' => file_uri_target($file->uri),
StreamWrapperManager::getTarget($file->uri) => [
'form' => StreamWrapperManager::getTarget($file->uri),
'src' => file_url_transform_relative(file_create_url($file->uri)),
],
// Relative path to a public file.
@ -107,17 +108,17 @@ class ThemeTest extends BrowserTestBase {
$explicit_file = 'public://logo.svg';
$local_file = $default_theme_path . '/logo.svg';
// Adjust for fully qualified stream wrapper URI in public filesystem.
if (file_uri_scheme($input) == 'public') {
$implicit_public_file = file_uri_target($input);
if (StreamWrapperManager::getScheme($input) == 'public') {
$implicit_public_file = StreamWrapperManager::getTarget($input);
$explicit_file = $input;
$local_file = strtr($input, ['public:/' => PublicStream::basePath()]);
}
// Adjust for fully qualified stream wrapper URI elsewhere.
elseif (file_uri_scheme($input) !== FALSE) {
elseif (StreamWrapperManager::getScheme($input) !== FALSE) {
$explicit_file = $input;
}
// Adjust for relative path within public filesystem.
elseif ($input == file_uri_target($file->uri)) {
elseif ($input == StreamWrapperManager::getTarget($file->uri)) {
$implicit_public_file = $input;
$explicit_file = 'public://' . $input;
$local_file = PublicStream::basePath() . '/' . $input;

View File

@ -3,9 +3,10 @@
namespace Drupal\Tests\user\Functional;
use Drupal\Core\Database\Database;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;
use Drupal\Tests\BrowserTestBase;
use Drupal\file\Entity\File;
use Drupal\Tests\TestFileCreationTrait;
/**
@ -65,7 +66,7 @@ class UserPictureTest extends BrowserTestBase {
// Verify that the image is displayed on the user account page.
$this->drupalGet('user');
$this->assertRaw(file_uri_target($file->getFileUri()), 'User picture found on user account page.');
$this->assertRaw(StreamWrapperManager::getTarget($file->getFileUri()), 'User picture found on user account page.');
// Delete the picture.
$edit = [];
@ -136,7 +137,7 @@ class UserPictureTest extends BrowserTestBase {
->save();
$this->drupalGet('node/' . $node->id());
$this->assertNoRaw(file_uri_target($file->getFileUri()), 'User picture not found on node and comment.');
$this->assertNoRaw(StreamWrapperManager::getTarget($file->getFileUri()), 'User picture not found on node and comment.');
}
/**

View File

@ -20,6 +20,21 @@ class FileSystemDeprecationTest extends KernelTestBase {
*/
public static $modules = ['system'];
/**
* The file system service.
*
* @var \Drupal\Core\File\FileSystemInterface
*/
protected $fileSystem;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->fileSystem = $fileSystem = $this->container->get('file_system');
}
/**
* @expectedDeprecation drupal_move_uploaded_file() is deprecated in Drupal 8.0.x-dev and will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystemInterface::moveUploadedFile(). See https://www.drupal.org/node/2418133.
*/
@ -176,4 +191,65 @@ class FileSystemDeprecationTest extends KernelTestBase {
$this->assertNotNull(file_directory_os_temp());
}
/**
* @expectedDeprecation file_uri_scheme() is deprecated in drupal:8.0.0 and will be removed before drupal:9.0.0. Use \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::getScheme() instead. See https://www.drupal.org/node/3035273
*/
public function testDeprecatedFileUriScheme() {
$this->assertEquals('public', file_uri_scheme('public://filename'));
}
/**
* @expectedDeprecation file_stream_wrapper_valid_scheme() is deprecated in drupal:8.0.0 and will be removed before drupal:9.0.0. Use \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::isValidScheme() instead. See https://www.drupal.org/node/3035273
*/
public function testDeprecatedValidScheme() {
$this->assertTrue(file_stream_wrapper_valid_scheme('public'));
}
/**
* @expectedDeprecation file_uri_target() is deprecated in drupal:8.8.0 and will be removed before drupal:9.0.0. Use \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::getTarget() instead. See https://www.drupal.org/node/3035273
*/
public function testDeprecatedFileUriTarget() {
$this->assertEquals('sample/test.txt', file_uri_target('public://sample/test.txt'));
}
/**
* @expectedDeprecation file_stream_wrapper_uri_normalize() is deprecated in drupal:8.8.0 and will be removed before drupal:9.0.0. Use \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::normalizeUri() instead. See https://www.drupal.org/node/3035273
*/
public function testDeprecatedFileStreamWrapperUriNormalize() {
$this->assertEquals('public://sample/test.txt', file_stream_wrapper_uri_normalize('public:///sample/test.txt'));
}
/**
* @expectedDeprecation file_valid_uri() is deprecated in drupal:8.8.0 and will be removed before drupal:9.0.0. Use \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::isValidUri() instead. See https://www.drupal.org/node/3035273
*/
public function testDeprecatedValidUri() {
$this->assertTrue(file_valid_uri('public://sample/test.txt'));
}
/**
* @expectedDeprecation FileSystem::uriScheme() is deprecated in drupal:8.8.0. It will be removed from drupal:9.0.0. Use \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface::getScheme() instead. See https://www.drupal.org/node/3035273
*
* @dataProvider providerTestUriScheme
*/
public function testUriScheme($uri, $expected) {
$this->assertSame($expected, $this->fileSystem->uriScheme($uri));
}
public function providerTestUriScheme() {
$data = [];
$data[] = [
'public://filename',
'public',
];
$data[] = [
'public://extra://',
'public',
];
$data[] = [
'invalid',
FALSE,
];
return $data;
}
}

View File

@ -71,24 +71,27 @@ class StreamWrapperTest extends FileTestBase {
public function testUriFunctions() {
$config = $this->config('system.file');
$instance = \Drupal::service('stream_wrapper_manager')->getViaUri($this->scheme . '://foo');
/** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
$instance = $stream_wrapper_manager->getViaUri($this->scheme . '://foo');
$this->assertEqual($this->classname, get_class($instance), 'Got correct class type for dummy URI.');
$instance = \Drupal::service('stream_wrapper_manager')->getViaUri('public://foo');
$instance = $stream_wrapper_manager->getViaUri('public://foo');
$this->assertEqual('Drupal\Core\StreamWrapper\PublicStream', get_class($instance), 'Got correct class type for public URI.');
// Test file_uri_target().
$this->assertEqual(file_uri_target('public://foo/bar.txt'), 'foo/bar.txt', 'Got a valid stream target from public://foo/bar.txt.');
$this->assertEqual(file_uri_target('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='), 'image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==', t('Got a valid stream target from a data URI.'));
$this->assertFalse(file_uri_target('foo/bar.txt'), 'foo/bar.txt is not a valid stream.');
$this->assertFalse(file_uri_target('public://'), 'public:// has no target.');
$this->assertFalse(file_uri_target('data:'), 'data: has no target.');
$this->assertEqual($stream_wrapper_manager::getTarget('public://foo/bar.txt'), 'foo/bar.txt', 'Got a valid stream target from public://foo/bar.txt.');
$this->assertEqual($stream_wrapper_manager::getTarget('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='), 'image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==', t('Got a valid stream target from a data URI.'));
$this->assertFalse($stream_wrapper_manager::getTarget('foo/bar.txt'), 'foo/bar.txt is not a valid stream.');
$this->assertFalse($stream_wrapper_manager::getTarget('public://'), 'public:// has no target.');
$this->assertFalse($stream_wrapper_manager::getTarget('data:'), 'data: has no target.');
// Test file_build_uri() and
// Drupal\Core\StreamWrapper\LocalStream::getDirectoryPath().
$this->assertEqual(file_build_uri('foo/bar.txt'), 'public://foo/bar.txt', 'Expected scheme was added.');
$this->assertEqual(\Drupal::service('stream_wrapper_manager')->getViaScheme('public')->getDirectoryPath(), PublicStream::basePath(), 'Expected default directory path was returned.');
$this->assertEqual(\Drupal::service('stream_wrapper_manager')->getViaScheme('temporary')->getDirectoryPath(), $config->get('path.temporary'), 'Expected temporary directory path was returned.');
$this->assertEqual($stream_wrapper_manager->getViaScheme('public')->getDirectoryPath(), PublicStream::basePath(), 'Expected default directory path was returned.');
$this->assertEqual($stream_wrapper_manager->getViaScheme('temporary')->getDirectoryPath(), $config->get('path.temporary'), 'Expected temporary directory path was returned.');
$config->set('default_scheme', 'private')->save();
$this->assertEqual(file_build_uri('foo/bar.txt'), 'private://foo/bar.txt', 'Got a valid URI from foo/bar.txt.');
@ -137,11 +140,15 @@ class StreamWrapperTest extends FileTestBase {
* Test the scheme functions.
*/
public function testGetValidStreamScheme() {
$this->assertEqual('foo', file_uri_scheme('foo://pork//chops'), 'Got the correct scheme from foo://asdf');
$this->assertEqual('data', file_uri_scheme('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='), 'Got the correct scheme from a data URI.');
$this->assertFalse(file_uri_scheme('foo/bar.txt'), 'foo/bar.txt is not a valid stream.');
$this->assertTrue(file_stream_wrapper_valid_scheme(file_uri_scheme('public://asdf')), 'Got a valid stream scheme from public://asdf');
$this->assertFalse(file_stream_wrapper_valid_scheme(file_uri_scheme('foo://asdf')), 'Did not get a valid stream scheme from foo://asdf');
/** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
$this->assertEqual('foo', $stream_wrapper_manager::getScheme('foo://pork//chops'), 'Got the correct scheme from foo://asdf');
$this->assertEqual('data', $stream_wrapper_manager::getScheme('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='), 'Got the correct scheme from a data URI.');
$this->assertFalse($stream_wrapper_manager::getScheme('foo/bar.txt'), 'foo/bar.txt is not a valid stream.');
$this->assertTrue($stream_wrapper_manager->isValidScheme($stream_wrapper_manager::getScheme('public://asdf')), 'Got a valid stream scheme from public://asdf');
$this->assertFalse($stream_wrapper_manager->isValidScheme($stream_wrapper_manager::getScheme('foo://asdf')), 'Did not get a valid stream scheme from foo://asdf');
}
/**

View File

@ -0,0 +1,63 @@
<?php
namespace Drupal\KernelTests\Core\StreamWrapper;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
use Drupal\KernelTests\KernelTestBase;
/**
* @coversDefaultClass \Drupal\Core\StreamWrapper\StreamWrapperManager
* @group File
*/
class StreamWrapperManagerTest extends KernelTestBase {
/**
* The stream wrapper manager.
*
* @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface
*/
protected $streamWrapperManager;
/**
* {@inheritdoc}
*/
public static $modules = ['system'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->streamWrapperManager = \Drupal::service('stream_wrapper_manager');
}
/**
* @covers ::getScheme
*
* @dataProvider providerTestUriScheme
*/
public function testUriScheme($uri, $expected) {
$this->assertSame($expected, StreamWrapperManager::getScheme($uri));
}
/**
* Data provider.
*/
public function providerTestUriScheme() {
$data = [];
$data[] = [
'public://filename',
'public',
];
$data[] = [
'public://extra://',
'public',
];
$data[] = [
'invalid',
FALSE,
];
return $data;
}
}

View File

@ -11,6 +11,7 @@ use Drupal\Core\Asset\Exception\IncompleteLibraryDefinitionException;
use Drupal\Core\Asset\Exception\InvalidLibraryFileException;
use Drupal\Core\Asset\Exception\LibraryDefinitionMissingLicenseException;
use Drupal\Core\Asset\LibraryDiscoveryParser;
use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
use Drupal\Tests\UnitTestCase;
/**
@ -54,6 +55,13 @@ class LibraryDiscoveryParserTest extends UnitTestCase {
*/
protected $lock;
/**
* The mocked stream wrapper manager.
*
* @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface||\PHPUnit_Framework_MockObject_MockObject
*/
protected $streamWrapperManager;
/**
* {@inheritdoc}
*/
@ -71,7 +79,8 @@ class LibraryDiscoveryParserTest extends UnitTestCase {
$this->themeManager->expects($this->any())
->method('getActiveTheme')
->willReturn($mock_active_theme);
$this->libraryDiscoveryParser = new TestLibraryDiscoveryParser($this->root, $this->moduleHandler, $this->themeManager);
$this->streamWrapperManager = $this->createMock(StreamWrapperManagerInterface::class);
$this->libraryDiscoveryParser = new TestLibraryDiscoveryParser($this->root, $this->moduleHandler, $this->themeManager, $this->streamWrapperManager);
}
/**
@ -354,6 +363,9 @@ class LibraryDiscoveryParserTest extends UnitTestCase {
->method('moduleExists')
->with('data_types')
->will($this->returnValue(TRUE));
$this->streamWrapperManager->expects($this->atLeastOnce())
->method('isValidUri')
->will($this->returnValue(TRUE));
$path = __DIR__ . '/library_test_files';
$path = substr($path, strlen($this->root) + 1);

View File

@ -5,6 +5,7 @@ namespace Drupal\Tests\Core\File;
use Drupal\Core\File\Exception\FileException;
use Drupal\Core\File\FileSystem;
use Drupal\Core\Site\Settings;
use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
use Drupal\Tests\UnitTestCase;
use org\bovigo\vfs\vfsStream;
@ -27,6 +28,13 @@ class FileSystemTest extends UnitTestCase {
*/
protected $logger;
/**
* The stream wrapper manager.
*
* @var \Drupal\Core\StreamWrapper\StreamWrapperInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $streamWrapperManager;
/**
* {@inheritdoc}
*/
@ -34,9 +42,9 @@ class FileSystemTest extends UnitTestCase {
parent::setUp();
$settings = new Settings([]);
$stream_wrapper_manager = $this->createMock('Drupal\Core\StreamWrapper\StreamWrapperManagerInterface');
$this->streamWrapperManager = $this->createMock(StreamWrapperManagerInterface::class);
$this->logger = $this->createMock('Psr\Log\LoggerInterface');
$this->fileSystem = new FileSystem($stream_wrapper_manager, $settings, $this->logger);
$this->fileSystem = new FileSystem($this->streamWrapperManager, $settings, $this->logger);
}
/**
@ -85,12 +93,8 @@ class FileSystemTest extends UnitTestCase {
vfsStream::create(['test.txt' => 'asdf']);
$uri = 'vfs://dir/test.txt';
$this->fileSystem = $this->getMockBuilder('Drupal\Core\File\FileSystem')
->disableOriginalConstructor()
->setMethods(['validScheme'])
->getMock();
$this->fileSystem->expects($this->once())
->method('validScheme')
$this->streamWrapperManager->expects($this->once())
->method('isValidUri')
->willReturn(TRUE);
$this->assertFileExists($uri);
@ -125,32 +129,6 @@ class FileSystemTest extends UnitTestCase {
return $data;
}
/**
* @covers ::uriScheme
*
* @dataProvider providerTestUriScheme
*/
public function testUriScheme($uri, $expected) {
$this->assertSame($expected, $this->fileSystem->uriScheme($uri));
}
public function providerTestUriScheme() {
$data = [];
$data[] = [
'public://filename',
'public',
];
$data[] = [
'public://extra://',
'public',
];
$data[] = [
'invalid',
FALSE,
];
return $data;
}
/**
* Asserts that the file permissions of a given URI matches.
*