Update to Drupal 8.0.0-beta15. For more information, see: https://www.drupal.org/node/2563023

This commit is contained in:
Pantheon Automation 2015-09-04 13:20:09 -07:00 committed by Greg Anderson
parent 2720a9ec4b
commit f3791f1da3
1898 changed files with 54300 additions and 11481 deletions

View file

@ -0,0 +1,75 @@
<?php
/**
* @file
* Contains \Drupal\Component\Assertion\Handle.
*
* For PHP 5 this contains \AssertionError as well.
*/
namespace {
if (!class_exists('AssertionError', FALSE)) {
/**
* Emulates PHP 7 AssertionError as closely as possible.
*
* We force this class to exist at the root namespace for PHP 5.
* This class exists natively in PHP 7. Note that in PHP 7 it extends from
* Error, not Exception, but that isn't possible for PHP 5 - all exceptions
* must extend from exception.
*/
class AssertionError extends Exception {
/**
* {@inheritdoc}
*/
public function __construct($message = '', $code = 0, Exception $previous = NULL, $file = '', $line = 0) {
parent::__construct($message, $code, $previous);
// Preserve the filename and line number of the assertion failure.
$this->file = $file;
$this->line = $line;
}
}
}
}
namespace Drupal\Component\Assertion {
/**
* Handler for runtime assertion failures.
*
* This class allows PHP 5.x to throw exceptions on runtime assertion fails
* in the same manner as PHP 7, and sets the ASSERT_EXCEPTION flag to TRUE
* for the PHP 7 runtime.
*
* @ingroup php_assert
*/
class Handle {
/**
* Registers uniform assertion handling.
*/
public static function register() {
// Since we're using exceptions, turn error warnings off.
assert_options(ASSERT_WARNING, FALSE);
if (version_compare(PHP_VERSION, '7.0.0-dev') < 0) {
// PHP 5 - create a handler to throw the exception directly.
assert_options(ASSERT_CALLBACK, function($file, $line, $code, $message) {
if (empty($message)) {
$message = $code;
}
throw new \AssertionError($message, 0, NULL, $file, $line);
});
}
else {
// PHP 7 - just turn exception throwing on.
assert_options(ASSERT_EXCEPTION, TRUE);
}
}
}
}

View file

@ -0,0 +1,629 @@
<?php
/**
* @file
* Contains \Drupal\Component\DependencyInjection\Container.
*/
namespace Drupal\Component\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\IntrospectableContainerInterface;
use Symfony\Component\DependencyInjection\ScopeInterface;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
/**
* Provides a container optimized for Drupal's needs.
*
* This container implementation is compatible with the default Symfony
* dependency injection container and similar to the Symfony ContainerBuilder
* class, but optimized for speed.
*
* It is based on a PHP array container definition dumped as a
* performance-optimized machine-readable format.
*
* The best way to initialize this container is to use a Container Builder,
* compile it and then retrieve the definition via
* \Drupal\Component\DependencyInjection\Dumper\OptimizedPhpArrayDumper::getArray().
*
* The retrieved array can be cached safely and then passed to this container
* via the constructor.
*
* As the container is unfrozen by default, a second parameter can be passed to
* the container to "freeze" the parameter bag.
*
* This container is different in behavior from the default Symfony container in
* the following ways:
*
* - It only allows lowercase service and parameter names, though it does only
* enforce it via assertions for performance reasons.
* - The following functions, that are not part of the interface, are explicitly
* not supported: getParameterBag(), isFrozen(), compile(),
* getAServiceWithAnIdByCamelCase().
* - The function getServiceIds() was added as it has a use-case in core and
* contrib.
* - Scopes are explicitly not allowed, because Symfony 2.8 has deprecated
* them and they will be removed in Symfony 3.0.
* - Synchronized services are explicitly not supported, because Symfony 2.8 has
* deprecated them and they will be removed in Symfony 3.0.
*
* @ingroup container
*/
class Container implements IntrospectableContainerInterface {
/**
* The parameters of the container.
*
* @var array
*/
protected $parameters = array();
/**
* The aliases of the container.
*
* @var array
*/
protected $aliases = array();
/**
* The service definitions of the container.
*
* @var array
*/
protected $serviceDefinitions = array();
/**
* The instantiated services.
*
* @var array
*/
protected $services = array();
/**
* The instantiated private services.
*
* @var array
*/
protected $privateServices = array();
/**
* The currently loading services.
*
* @var array
*/
protected $loading = array();
/**
* Whether the container parameters can still be changed.
*
* For testing purposes the container needs to be changed.
*
* @var bool
*/
protected $frozen = TRUE;
/**
* Constructs a new Container instance.
*
* @param array $container_definition
* An array containing the following keys:
* - aliases: The aliases of the container.
* - parameters: The parameters of the container.
* - services: The service definitions of the container.
* - frozen: Whether the container definition came from a frozen
* container builder or not.
* - machine_format: Whether this container definition uses the optimized
* machine-readable container format.
*/
public function __construct(array $container_definition = array()) {
if (!empty($container_definition) && (!isset($container_definition['machine_format']) || $container_definition['machine_format'] !== TRUE)) {
throw new InvalidArgumentException('The non-optimized format is not supported by this class. Use an optimized machine-readable format instead, e.g. as produced by \Drupal\Component\DependencyInjection\Dumper\OptimizedPhpArrayDumper.');
}
$this->aliases = isset($container_definition['aliases']) ? $container_definition['aliases'] : array();
$this->parameters = isset($container_definition['parameters']) ? $container_definition['parameters'] : array();
$this->serviceDefinitions = isset($container_definition['services']) ? $container_definition['services'] : array();
$this->frozen = isset($container_definition['frozen']) ? $container_definition['frozen'] : FALSE;
// Register the service_container with itself.
$this->services['service_container'] = $this;
}
/**
* {@inheritdoc}
*/
public function get($id, $invalid_behavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {
if (isset($this->aliases[$id])) {
$id = $this->aliases[$id];
}
// Re-use shared service instance if it exists.
if (isset($this->services[$id]) || ($invalid_behavior === ContainerInterface::NULL_ON_INVALID_REFERENCE && array_key_exists($id, $this->services))) {
return $this->services[$id];
}
if (isset($this->loading[$id])) {
throw new ServiceCircularReferenceException($id, array_keys($this->loading));
}
$definition = isset($this->serviceDefinitions[$id]) ? $this->serviceDefinitions[$id] : NULL;
if (!$definition && $invalid_behavior === ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {
if (!$id) {
throw new ServiceNotFoundException($id);
}
throw new ServiceNotFoundException($id, NULL, NULL, $this->getServiceAlternatives($id));
}
// In case something else than ContainerInterface::NULL_ON_INVALID_REFERENCE
// is used, the actual wanted behavior is to re-try getting the service at a
// later point.
if (!$definition) {
return;
}
// Definition is a keyed array, so [0] is only defined when it is a
// serialized string.
if (isset($definition[0])) {
$definition = unserialize($definition);
}
// Now create the service.
$this->loading[$id] = TRUE;
try {
$service = $this->createService($definition, $id);
}
catch (\Exception $e) {
unset($this->loading[$id]);
// Remove a potentially shared service that was constructed incompletely.
if (array_key_exists($id, $this->services)) {
unset($this->services[$id]);
}
if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $invalid_behavior) {
return;
}
throw $e;
}
unset($this->loading[$id]);
return $service;
}
/**
* Creates a service from a service definition.
*
* @param array $definition
* The service definition to create a service from.
* @param string $id
* The service identifier, necessary so it can be shared if its public.
*
* @return object
* The service described by the service definition.
*
* @throws \Symfony\Component\DependencyInjection\Exception\RuntimeException
* Thrown when the service is a synthetic service.
* @throws \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* Thrown when the configurator callable in $definition['configurator'] is
* not actually a callable.
* @throws \ReflectionException
* Thrown when the service class takes more than 10 parameters to construct,
* and cannot be instantiated.
*/
protected function createService(array $definition, $id) {
if (isset($definition['synthetic']) && $definition['synthetic'] === TRUE) {
throw new RuntimeException(sprintf('You have requested a synthetic service ("%s"). The service container does not know how to construct this service. The service will need to be set before it is first used.', $id));
}
$arguments = array();
if (isset($definition['arguments'])) {
$arguments = $definition['arguments'];
if ($arguments instanceof \stdClass) {
$arguments = $this->resolveServicesAndParameters($arguments);
}
}
if (isset($definition['file'])) {
$file = $this->frozen ? $definition['file'] : current($this->resolveServicesAndParameters(array($definition['file'])));
require_once $file;
}
if (isset($definition['factory'])) {
$factory = $definition['factory'];
if (is_array($factory)) {
$factory = $this->resolveServicesAndParameters(array($factory[0], $factory[1]));
}
elseif (!is_string($factory)) {
throw new RuntimeException(sprintf('Cannot create service "%s" because of invalid factory', $id));
}
$service = call_user_func_array($factory, $arguments);
}
else {
$class = $this->frozen ? $definition['class'] : current($this->resolveServicesAndParameters(array($definition['class'])));
$length = isset($definition['arguments_count']) ? $definition['arguments_count'] : count($arguments);
// Optimize class instantiation for services with up to 10 parameters as
// ReflectionClass is noticeably slow.
switch ($length) {
case 0:
$service = new $class();
break;
case 1:
$service = new $class($arguments[0]);
break;
case 2:
$service = new $class($arguments[0], $arguments[1]);
break;
case 3:
$service = new $class($arguments[0], $arguments[1], $arguments[2]);
break;
case 4:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3]);
break;
case 5:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4]);
break;
case 6:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5]);
break;
case 7:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6]);
break;
case 8:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7]);
break;
case 9:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7], $arguments[8]);
break;
case 10:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7], $arguments[8], $arguments[9]);
break;
default:
$r = new \ReflectionClass($class);
$service = $r->newInstanceArgs($arguments);
break;
}
}
// Share the service if it is public.
if (!isset($definition['public']) || $definition['public'] !== FALSE) {
// Forward compatibility fix for Symfony 2.8 update.
if (!isset($definition['shared']) || $definition['shared'] !== FALSE) {
$this->services[$id] = $service;
}
}
if (isset($definition['calls'])) {
foreach ($definition['calls'] as $call) {
$method = $call[0];
$arguments = array();
if (!empty($call[1])) {
$arguments = $call[1];
if ($arguments instanceof \stdClass) {
$arguments = $this->resolveServicesAndParameters($arguments);
}
}
call_user_func_array(array($service, $method), $arguments);
}
}
if (isset($definition['properties'])) {
if ($definition['properties'] instanceof \stdClass) {
$definition['properties'] = $this->resolveServicesAndParameters($definition['properties']);
}
foreach ($definition['properties'] as $key => $value) {
$service->{$key} = $value;
}
}
if (isset($definition['configurator'])) {
$callable = $definition['configurator'];
if (is_array($callable)) {
$callable = $this->resolveServicesAndParameters($callable);
}
if (!is_callable($callable)) {
throw new InvalidArgumentException(sprintf('The configurator for class "%s" is not a callable.', get_class($service)));
}
call_user_func($callable, $service);
}
return $service;
}
/**
* {@inheritdoc}
*/
public function set($id, $service, $scope = ContainerInterface::SCOPE_CONTAINER) {
$this->services[$id] = $service;
}
/**
* {@inheritdoc}
*/
public function has($id) {
return isset($this->services[$id]) || isset($this->serviceDefinitions[$id]);
}
/**
* {@inheritdoc}
*/
public function getParameter($name) {
if (!(isset($this->parameters[$name]) || array_key_exists($name, $this->parameters))) {
if (!$name) {
throw new ParameterNotFoundException($name);
}
throw new ParameterNotFoundException($name, NULL, NULL, NULL, $this->getParameterAlternatives($name));
}
return $this->parameters[$name];
}
/**
* {@inheritdoc}
*/
public function hasParameter($name) {
return isset($this->parameters[$name]) || array_key_exists($name, $this->parameters);
}
/**
* {@inheritdoc}
*/
public function setParameter($name, $value) {
if ($this->frozen) {
throw new LogicException('Impossible to call set() on a frozen ParameterBag.');
}
$this->parameters[$name] = $value;
}
/**
* {@inheritdoc}
*/
public function initialized($id) {
if (isset($this->aliases[$id])) {
$id = $this->aliases[$id];
}
return isset($this->services[$id]) || array_key_exists($id, $this->services);
}
/**
* Resolves arguments that represent services or variables to the real values.
*
* @param array|\stdClass $arguments
* The arguments to resolve.
*
* @return array
* The resolved arguments.
*
* @throws \Symfony\Component\DependencyInjection\Exception\RuntimeException
* If a parameter/service could not be resolved.
* @throws \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* If an unknown type is met while resolving parameters and services.
*/
protected function resolveServicesAndParameters($arguments) {
// Check if this collection needs to be resolved.
if ($arguments instanceof \stdClass) {
if ($arguments->type !== 'collection') {
throw new InvalidArgumentException(sprintf('Undefined type "%s" while resolving parameters and services.', $arguments->type));
}
// In case there is nothing to resolve, we are done here.
if (!$arguments->resolve) {
return $arguments->value;
}
$arguments = $arguments->value;
}
// Process the arguments.
foreach ($arguments as $key => $argument) {
// For this machine-optimized format, only \stdClass arguments are
// processed and resolved. All other values are kept as is.
if ($argument instanceof \stdClass) {
$type = $argument->type;
// Check for parameter.
if ($type == 'parameter') {
$name = $argument->name;
if (!isset($this->parameters[$name])) {
$arguments[$key] = $this->getParameter($name);
// This can never be reached as getParameter() throws an Exception,
// because we already checked that the parameter is not set above.
}
// Update argument.
$argument = $arguments[$key] = $this->parameters[$name];
// In case there is not a machine readable value (e.g. a service)
// behind this resolved parameter, continue.
if (!($argument instanceof \stdClass)) {
continue;
}
// Fall through.
$type = $argument->type;
}
// Create a service.
if ($type == 'service') {
$id = $argument->id;
// Does the service already exist?
if (isset($this->aliases[$id])) {
$id = $this->aliases[$id];
}
if (isset($this->services[$id])) {
$arguments[$key] = $this->services[$id];
continue;
}
// Return the service.
$arguments[$key] = $this->get($id, $argument->invalidBehavior);
continue;
}
// Create private service.
elseif ($type == 'private_service') {
$id = $argument->id;
// Does the private service already exist.
if (isset($this->privateServices[$id])) {
$arguments[$key] = $this->privateServices[$id];
continue;
}
// Create the private service.
$arguments[$key] = $this->createService($argument->value, $id);
if ($argument->shared) {
$this->privateServices[$id] = $arguments[$key];
}
continue;
}
// Check for collection.
elseif ($type == 'collection') {
$value = $argument->value;
// Does this collection need resolving?
if ($argument->resolve) {
$arguments[$key] = $this->resolveServicesAndParameters($value);
}
else {
$arguments[$key] = $value;
}
continue;
}
if ($type !== NULL) {
throw new InvalidArgumentException(sprintf('Undefined type "%s" while resolving parameters and services.', $type));
}
}
}
return $arguments;
}
/**
* Provides alternatives for a given array and key.
*
* @param string $search_key
* The search key to get alternatives for.
* @param array $keys
* The search space to search for alternatives in.
*
* @return string[]
* An array of strings with suitable alternatives.
*/
protected function getAlternatives($search_key, array $keys) {
$alternatives = array();
foreach ($keys as $key) {
$lev = levenshtein($search_key, $key);
if ($lev <= strlen($search_key) / 3 || strpos($key, $search_key) !== FALSE) {
$alternatives[] = $key;
}
}
return $alternatives;
}
/**
* Provides alternatives in case a service was not found.
*
* @param string $id
* The service to get alternatives for.
*
* @return string[]
* An array of strings with suitable alternatives.
*/
protected function getServiceAlternatives($id) {
$all_service_keys = array_unique(array_merge(array_keys($this->services), array_keys($this->serviceDefinitions)));
return $this->getAlternatives($id, $all_service_keys);
}
/**
* Provides alternatives in case a parameter was not found.
*
* @param string $name
* The parameter to get alternatives for.
*
* @return string[]
* An array of strings with suitable alternatives.
*/
protected function getParameterAlternatives($name) {
return $this->getAlternatives($name, array_keys($this->parameters));
}
/**
* {@inheritdoc}
*/
public function enterScope($name) {
throw new \BadMethodCallException(sprintf("'%s' is not supported by Drupal 8.", __FUNCTION__));
}
/**
* {@inheritdoc}
*/
public function leaveScope($name) {
throw new \BadMethodCallException(sprintf("'%s' is not supported by Drupal 8.", __FUNCTION__));
}
/**
* {@inheritdoc}
*/
public function addScope(ScopeInterface $scope) {
throw new \BadMethodCallException(sprintf("'%s' is not supported by Drupal 8.", __FUNCTION__));
}
/**
* {@inheritdoc}
*/
public function hasScope($name) {
throw new \BadMethodCallException(sprintf("'%s' is not supported by Drupal 8.", __FUNCTION__));
}
/**
* {@inheritdoc}
*/
public function isScopeActive($name) {
throw new \BadMethodCallException(sprintf("'%s' is not supported by Drupal 8.", __FUNCTION__));
}
/**
* Gets all defined service IDs.
*
* @return array
* An array of all defined service IDs.
*/
public function getServiceIds() {
return array_keys($this->serviceDefinitions + $this->services);
}
}

View file

@ -0,0 +1,513 @@
<?php
/**
* @file
* Contains \Drupal\Component\DependencyInjection\Dumper\OptimizedPhpArrayDumper.
*/
namespace Drupal\Component\DependencyInjection\Dumper;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Parameter;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Dumper\Dumper;
use Symfony\Component\ExpressionLanguage\Expression;
/**
* OptimizedPhpArrayDumper dumps a service container as a serialized PHP array.
*
* The format of this dumper is very similar to the internal structure of the
* ContainerBuilder, but based on PHP arrays and \stdClass objects instead of
* rich value objects for performance reasons.
*
* By removing the abstraction and optimizing some cases like deep collections,
* fewer classes need to be loaded, fewer function calls need to be executed and
* fewer run time checks need to be made.
*
* In addition to that, this container dumper treats private services as
* strictly private with their own private services storage, whereas in the
* Symfony service container builder and PHP dumper, shared private services can
* still be retrieved via get() from the container.
*
* It is machine-optimized, for a human-readable version based on this one see
* \Drupal\Component\DependencyInjection\Dumper\PhpArrayDumper.
*
* @see \Drupal\Component\DependencyInjection\Container
*/
class OptimizedPhpArrayDumper extends Dumper {
/**
* Whether to serialize service definitions or not.
*
* Service definitions are serialized by default to avoid having to
* unserialize the whole container on loading time, which improves early
* bootstrap performance for e.g. the page cache.
*
* @var bool
*/
protected $serialize = TRUE;
/**
* {@inheritdoc}
*/
public function dump(array $options = array()) {
return serialize($this->getArray());
}
/**
* Gets the service container definition as a PHP array.
*
* @return array
* A PHP array representation of the service container.
*/
public function getArray() {
$definition = array();
$definition['aliases'] = $this->getAliases();
$definition['parameters'] = $this->getParameters();
$definition['services'] = $this->getServiceDefinitions();
$definition['frozen'] = $this->container->isFrozen();
$definition['machine_format'] = $this->supportsMachineFormat();
return $definition;
}
/**
* Gets the aliases as a PHP array.
*
* @return array
* The aliases.
*/
protected function getAliases() {
$alias_definitions = array();
$aliases = $this->container->getAliases();
foreach ($aliases as $alias => $id) {
$id = (string) $id;
while (isset($aliases[$id])) {
$id = (string) $aliases[$id];
}
$alias_definitions[$alias] = $id;
}
return $alias_definitions;
}
/**
* Gets parameters of the container as a PHP array.
*
* @return array
* The escaped and prepared parameters of the container.
*/
protected function getParameters() {
if (!$this->container->getParameterBag()->all()) {
return array();
}
$parameters = $this->container->getParameterBag()->all();
$is_frozen = $this->container->isFrozen();
return $this->prepareParameters($parameters, $is_frozen);
}
/**
* Gets services of the container as a PHP array.
*
* @return array
* The service definitions.
*/
protected function getServiceDefinitions() {
if (!$this->container->getDefinitions()) {
return array();
}
$services = array();
foreach ($this->container->getDefinitions() as $id => $definition) {
// Only store public service definitions, references to shared private
// services are handled in ::getReferenceCall().
if ($definition->isPublic()) {
$service_definition = $this->getServiceDefinition($definition);
$services[$id] = $this->serialize ? serialize($service_definition) : $service_definition;
}
}
return $services;
}
/**
* Prepares parameters for the PHP array dumping.
*
* @param array $parameters
* An array of parameters.
* @param bool $escape
* Whether keys with '%' should be escaped or not.
*
* @return array
* An array of prepared parameters.
*/
protected function prepareParameters(array $parameters, $escape = TRUE) {
$filtered = array();
foreach ($parameters as $key => $value) {
if (is_array($value)) {
$value = $this->prepareParameters($value, $escape);
}
elseif ($value instanceof Reference) {
$value = $this->dumpValue($value);
}
$filtered[$key] = $value;
}
return $escape ? $this->escape($filtered) : $filtered;
}
/**
* Escapes parameters.
*
* @param array $parameters
* The parameters to escape for '%' characters.
*
* @return array
* The escaped parameters.
*/
protected function escape(array $parameters) {
$args = array();
foreach ($parameters as $key => $value) {
if (is_array($value)) {
$args[$key] = $this->escape($value);
}
elseif (is_string($value)) {
$args[$key] = str_replace('%', '%%', $value);
}
else {
$args[$key] = $value;
}
}
return $args;
}
/**
* Gets a service definition as PHP array.
*
* @param \Symfony\Component\DependencyInjection\Definition $definition
* The definition to process.
*
* @return array
* The service definition as PHP array.
*
* @throws \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* Thrown when the definition is marked as decorated, or with an explicit
* scope different from SCOPE_CONTAINER and SCOPE_PROTOTYPE.
*/
protected function getServiceDefinition(Definition $definition) {
$service = array();
if ($definition->getClass()) {
$service['class'] = $definition->getClass();
}
if (!$definition->isPublic()) {
$service['public'] = FALSE;
}
if ($definition->getFile()) {
$service['file'] = $definition->getFile();
}
if ($definition->isSynthetic()) {
$service['synthetic'] = TRUE;
}
if ($definition->isLazy()) {
$service['lazy'] = TRUE;
}
if ($definition->getArguments()) {
$arguments = $definition->getArguments();
$service['arguments'] = $this->dumpCollection($arguments);
$service['arguments_count'] = count($arguments);
}
else {
$service['arguments_count'] = 0;
}
if ($definition->getProperties()) {
$service['properties'] = $this->dumpCollection($definition->getProperties());
}
if ($definition->getMethodCalls()) {
$service['calls'] = $this->dumpMethodCalls($definition->getMethodCalls());
}
if (($scope = $definition->getScope()) !== ContainerInterface::SCOPE_CONTAINER) {
if ($scope === ContainerInterface::SCOPE_PROTOTYPE) {
// Scope prototype has been replaced with 'shared' => FALSE.
// This is a Symfony 2.8 forward compatibility fix.
// Reference: https://github.com/symfony/symfony/blob/2.8/UPGRADE-2.8.md#dependencyinjection
$service['shared'] = FALSE;
}
else {
throw new InvalidArgumentException("The 'scope' definition is deprecated in Symfony 3.0 and not supported by Drupal 8.");
}
}
if (($decorated = $definition->getDecoratedService()) !== NULL) {
throw new InvalidArgumentException("The 'decorated' definition is not supported by the Drupal 8 run-time container. The Container Builder should have resolved that during the DecoratorServicePass compiler pass.");
}
if ($callable = $definition->getFactory()) {
$service['factory'] = $this->dumpCallable($callable);
}
if ($callable = $definition->getConfigurator()) {
$service['configurator'] = $this->dumpCallable($callable);
}
return $service;
}
/**
* Dumps method calls to a PHP array.
*
* @param array $calls
* An array of method calls.
*
* @return array
* The PHP array representation of the method calls.
*/
protected function dumpMethodCalls(array $calls) {
$code = array();
foreach ($calls as $key => $call) {
$method = $call[0];
$arguments = array();
if (!empty($call[1])) {
$arguments = $this->dumpCollection($call[1]);
}
$code[$key] = [$method, $arguments];
}
return $code;
}
/**
* Dumps a collection to a PHP array.
*
* @param mixed $collection
* A collection to process.
* @param bool &$resolve
* Used for passing the information to the caller whether the given
* collection needed to be resolved or not. This is used for optimizing
* deep arrays that don't need to be traversed.
*
* @return \stdClass|array
* The collection in a suitable format.
*/
protected function dumpCollection($collection, &$resolve = FALSE) {
$code = array();
foreach ($collection as $key => $value) {
if (is_array($value)) {
$resolve_collection = FALSE;
$code[$key] = $this->dumpCollection($value, $resolve_collection);
if ($resolve_collection) {
$resolve = TRUE;
}
}
else {
if (is_object($value)) {
$resolve = TRUE;
}
$code[$key] = $this->dumpValue($value);
}
}
if (!$resolve) {
return $collection;
}
return (object) array(
'type' => 'collection',
'value' => $code,
'resolve' => $resolve,
);
}
/**
* Dumps callable to a PHP array.
*
* @param array|callable $callable
* The callable to process.
*
* @return callable
* The processed callable.
*/
protected function dumpCallable($callable) {
if (is_array($callable)) {
$callable[0] = $this->dumpValue($callable[0]);
$callable = array($callable[0], $callable[1]);
}
return $callable;
}
/**
* Gets a private service definition in a suitable format.
*
* @param string $id
* The ID of the service to get a private definition for.
* @param \Symfony\Component\DependencyInjection\Definition $definition
* The definition to process.
* @param bool $shared
* (optional) Whether the service will be shared with others.
* By default this parameter is FALSE.
*
* @return \stdClass
* A very lightweight private service value object.
*/
protected function getPrivateServiceCall($id, Definition $definition, $shared = FALSE) {
$service_definition = $this->getServiceDefinition($definition);
if (!$id) {
$hash = hash('sha1', serialize($service_definition));
$id = 'private__' . $hash;
}
return (object) array(
'type' => 'private_service',
'id' => $id,
'value' => $service_definition,
'shared' => $shared,
);
}
/**
* Dumps the value to PHP array format.
*
* @param mixed $value
* The value to dump.
*
* @return mixed
* The dumped value in a suitable format.
*
* @throws RuntimeException
* When trying to dump object or resource.
*/
protected function dumpValue($value) {
if (is_array($value)) {
$code = array();
foreach ($value as $k => $v) {
$code[$k] = $this->dumpValue($v);
}
return $code;
}
elseif ($value instanceof Reference) {
return $this->getReferenceCall((string) $value, $value);
}
elseif ($value instanceof Definition) {
return $this->getPrivateServiceCall(NULL, $value);
}
elseif ($value instanceof Parameter) {
return $this->getParameterCall((string) $value);
}
elseif ($value instanceof Expression) {
throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
}
elseif (is_object($value)) {
// Drupal specific: Instantiated objects have a _serviceId parameter.
if (isset($value->_serviceId)) {
return $this->getReferenceCall($value->_serviceId);
}
throw new RuntimeException('Unable to dump a service container if a parameter is an object without _serviceId.');
}
elseif (is_resource($value)) {
throw new RuntimeException('Unable to dump a service container if a parameter is a resource.');
}
return $value;
}
/**
* Gets a service reference for a reference in a suitable PHP array format.
*
* The main difference is that this function treats references to private
* services differently and returns a private service reference instead of
* a normal reference.
*
* @param string $id
* The ID of the service to get a reference for.
* @param \Symfony\Component\DependencyInjection\Reference|NULL $reference
* (optional) The reference object to process; needed to get the invalid
* behavior value.
*
* @return string|\stdClass
* A suitable representation of the service reference.
*/
protected function getReferenceCall($id, Reference $reference = NULL) {
$invalid_behavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
if ($reference !== NULL) {
$invalid_behavior = $reference->getInvalidBehavior();
}
// Private shared service.
$definition = $this->container->getDefinition($id);
if (!$definition->isPublic()) {
// The ContainerBuilder does not share a private service, but this means a
// new service is instantiated every time. Use a private shared service to
// circumvent the problem.
return $this->getPrivateServiceCall($id, $definition, TRUE);
}
return $this->getServiceCall($id, $invalid_behavior);
}
/**
* Gets a service reference for an ID in a suitable PHP array format.
*
* @param string $id
* The ID of the service to get a reference for.
* @param int $invalid_behavior
* (optional) The invalid behavior of the service.
*
* @return string|\stdClass
* A suitable representation of the service reference.
*/
protected function getServiceCall($id, $invalid_behavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {
return (object) array(
'type' => 'service',
'id' => $id,
'invalidBehavior' => $invalid_behavior,
);
}
/**
* Gets a parameter reference in a suitable PHP array format.
*
* @param string $name
* The name of the parameter to get a reference for.
*
* @return string|\stdClass
* A suitable representation of the parameter reference.
*/
protected function getParameterCall($name) {
return (object) array(
'type' => 'parameter',
'name' => $name,
);
}
/**
* Whether this supports the machine-optimized format or not.
*
* @return bool
* TRUE if this supports machine-optimized format, FALSE otherwise.
*/
protected function supportsMachineFormat() {
return TRUE;
}
}

View file

@ -0,0 +1,77 @@
<?php
/**
* @file
* Contains \Drupal\Component\DependencyInjection\Dumper\PhpArrayDumper.
*/
namespace Drupal\Component\DependencyInjection\Dumper;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* PhpArrayDumper dumps a service container as a PHP array.
*
* The format of this dumper is a human-readable serialized PHP array, which is
* very similar to the YAML based format, but based on PHP arrays instead of
* YAML strings.
*
* It is human-readable, for a machine-optimized version based on this one see
* \Drupal\Component\DependencyInjection\Dumper\OptimizedPhpArrayDumper.
*
* @see \Drupal\Component\DependencyInjection\PhpArrayContainer
*/
class PhpArrayDumper extends OptimizedPhpArrayDumper {
/**
* {@inheritdoc}
*/
public function getArray() {
$this->serialize = FALSE;
return parent::getArray();
}
/**
* {@inheritdoc}
*/
protected function dumpCollection($collection, &$resolve = FALSE) {
$code = array();
foreach ($collection as $key => $value) {
if (is_array($value)) {
$code[$key] = $this->dumpCollection($value);
}
else {
$code[$key] = $this->dumpValue($value);
}
}
return $code;
}
/**
* {@inheritdoc}
*/
protected function getServiceCall($id, $invalid_behavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {
if ($invalid_behavior !== ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {
return '@?' . $id;
}
return '@' . $id;
}
/**
* {@inheritdoc}
*/
protected function getParameterCall($name) {
return '%' . $name . '%';
}
/**
* {@inheritdoc}
*/
protected function supportsMachineFormat() {
return FALSE;
}
}

View file

@ -0,0 +1,276 @@
<?php
/**
* @file
* Contains \Drupal\Component\DependencyInjection\PhpArrayContainer.
*/
namespace Drupal\Component\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
/**
* Provides a container optimized for Drupal's needs.
*
* This container implementation is compatible with the default Symfony
* dependency injection container and similar to the Symfony ContainerBuilder
* class, but optimized for speed.
*
* It is based on a human-readable PHP array container definition with a
* structure very similar to the YAML container definition.
*
* @see \Drupal\Component\DependencyInjection\Container
* @see \Drupal\Component\DependencyInjection\Dumper\PhpArrayDumper
* @see \Drupal\Component\DependencyInjection\DependencySerializationTrait
*
* @ingroup container
*/
class PhpArrayContainer extends Container {
/**
* {@inheritdoc}
*/
public function __construct(array $container_definition = array()) {
if (isset($container_definition['machine_format']) && $container_definition['machine_format'] === TRUE) {
throw new InvalidArgumentException('The machine-optimized format is not supported by this class. Use a human-readable format instead, e.g. as produced by \Drupal\Component\DependencyInjection\Dumper\PhpArrayDumper.');
}
// Do not call the parent's constructor as it would bail on the
// machine-optimized format.
$this->aliases = isset($container_definition['aliases']) ? $container_definition['aliases'] : array();
$this->parameters = isset($container_definition['parameters']) ? $container_definition['parameters'] : array();
$this->serviceDefinitions = isset($container_definition['services']) ? $container_definition['services'] : array();
$this->frozen = isset($container_definition['frozen']) ? $container_definition['frozen'] : FALSE;
// Register the service_container with itself.
$this->services['service_container'] = $this;
}
/**
* {@inheritdoc}
*/
protected function createService(array $definition, $id) {
// This method is a verbatim copy of
// \Drupal\Component\DependencyInjection\Container::createService
// except for the following difference:
// - There are no instanceof checks on \stdClass, which are used in the
// parent class to avoid resolving services and parameters when it is
// known from dumping that there is nothing to resolve.
if (isset($definition['synthetic']) && $definition['synthetic'] === TRUE) {
throw new RuntimeException(sprintf('You have requested a synthetic service ("%s"). The service container does not know how to construct this service. The service will need to be set before it is first used.', $id));
}
$arguments = array();
if (isset($definition['arguments'])) {
$arguments = $this->resolveServicesAndParameters($definition['arguments']);
}
if (isset($definition['file'])) {
$file = $this->frozen ? $definition['file'] : current($this->resolveServicesAndParameters(array($definition['file'])));
require_once $file;
}
if (isset($definition['factory'])) {
$factory = $definition['factory'];
if (is_array($factory)) {
$factory = $this->resolveServicesAndParameters(array($factory[0], $factory[1]));
}
elseif (!is_string($factory)) {
throw new RuntimeException(sprintf('Cannot create service "%s" because of invalid factory', $id));
}
$service = call_user_func_array($factory, $arguments);
}
else {
$class = $this->frozen ? $definition['class'] : current($this->resolveServicesAndParameters(array($definition['class'])));
$length = isset($definition['arguments_count']) ? $definition['arguments_count'] : count($arguments);
// Optimize class instantiation for services with up to 10 parameters as
// reflection is noticeably slow.
switch ($length) {
case 0:
$service = new $class();
break;
case 1:
$service = new $class($arguments[0]);
break;
case 2:
$service = new $class($arguments[0], $arguments[1]);
break;
case 3:
$service = new $class($arguments[0], $arguments[1], $arguments[2]);
break;
case 4:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3]);
break;
case 5:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4]);
break;
case 6:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5]);
break;
case 7:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6]);
break;
case 8:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7]);
break;
case 9:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7], $arguments[8]);
break;
case 10:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7], $arguments[8], $arguments[9]);
break;
default:
$r = new \ReflectionClass($class);
$service = $r->newInstanceArgs($arguments);
break;
}
}
// Share the service if it is public.
if (!isset($definition['public']) || $definition['public'] !== FALSE) {
// Forward compatibility fix for Symfony 2.8 update.
if (!isset($definition['shared']) || $definition['shared'] !== FALSE) {
$this->services[$id] = $service;
}
}
if (isset($definition['calls'])) {
foreach ($definition['calls'] as $call) {
$method = $call[0];
$arguments = array();
if (!empty($call[1])) {
$arguments = $call[1];
$arguments = $this->resolveServicesAndParameters($arguments);
}
call_user_func_array(array($service, $method), $arguments);
}
}
if (isset($definition['properties'])) {
$definition['properties'] = $this->resolveServicesAndParameters($definition['properties']);
foreach ($definition['properties'] as $key => $value) {
$service->{$key} = $value;
}
}
if (isset($definition['configurator'])) {
$callable = $definition['configurator'];
if (is_array($callable)) {
$callable = $this->resolveServicesAndParameters($callable);
}
if (!is_callable($callable)) {
throw new InvalidArgumentException(sprintf('The configurator for class "%s" is not a callable.', get_class($service)));
}
call_user_func($callable, $service);
}
return $service;
}
/**
* {@inheritdoc}
*/
protected function resolveServicesAndParameters($arguments) {
// This method is different from the parent method only for the following
// cases:
// - A service is denoted by '@service' and not by a \stdClass object.
// - A parameter is denoted by '%parameter%' and not by a \stdClass object.
// - The depth of the tree representing the arguments is not known in
// advance, so it needs to be fully traversed recursively.
foreach ($arguments as $key => $argument) {
if ($argument instanceof \stdClass) {
$type = $argument->type;
// Private services are a special flavor: In case a private service is
// only used by one other service, the ContainerBuilder uses a
// Definition object as an argument, which does not have an ID set.
// Therefore the format uses a \stdClass object to store the definition
// and to be able to create the service on the fly.
//
// Note: When constructing a private service by hand, 'id' must be set.
//
// The PhpArrayDumper just uses the hash of the private service
// definition to generate a unique ID.
//
// @see \Drupal\Component\DependecyInjection\Dumper\OptimizedPhpArrayDumper::getPrivateServiceCall
if ($type == 'private_service') {
$id = $argument->id;
// Check if the private service already exists - in case it is shared.
if (!empty($argument->shared) && isset($this->privateServices[$id])) {
$arguments[$key] = $this->privateServices[$id];
continue;
}
// Create a private service from a service definition.
$arguments[$key] = $this->createService($argument->value, $id);
if (!empty($argument->shared)) {
$this->privateServices[$id] = $arguments[$key];
}
continue;
}
if ($type !== NULL) {
throw new InvalidArgumentException("Undefined type '$type' while resolving parameters and services.");
}
}
if (is_array($argument)) {
$arguments[$key] = $this->resolveServicesAndParameters($argument);
continue;
}
if (!is_string($argument)) {
continue;
}
// Resolve parameters.
if ($argument[0] === '%') {
$name = substr($argument, 1, -1);
if (!isset($this->parameters[$name])) {
$arguments[$key] = $this->getParameter($name);
// This can never be reached as getParameter() throws an Exception,
// because we already checked that the parameter is not set above.
}
$argument = $this->parameters[$name];
$arguments[$key] = $argument;
}
// Resolve services.
if ($argument[0] === '@') {
$id = substr($argument, 1);
$invalid_behavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
if ($id[0] === '?') {
$id = substr($id, 1);
$invalid_behavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
}
if (isset($this->services[$id])) {
$arguments[$key] = $this->services[$id];
}
else {
$arguments[$key] = $this->get($id, $invalid_behavior);
}
}
}
return $arguments;
}
}

View file

@ -0,0 +1,18 @@
{
"name": "drupal/core-dependency-injection",
"description": "Dependency Injection container optimized for Drupal's needs.",
"keywords": ["drupal", "dependency injection"],
"type": "library",
"homepage": "https://www.drupal.org/project/drupal",
"license": "GPL-2.0+",
"support": {
"issues": "https://www.drupal.org/project/issues/drupal",
"irc": "irc://irc.freenode.net/drupal-contribute",
"source": "https://www.drupal.org/project/drupal/git-instructions"
},
"autoload": {
"psr-4": {
"Drupal\\Component\\DependencyInjection\\": ""
}
}
}

View file

@ -8,7 +8,6 @@
namespace Drupal\Component\Diff\Engine;
use Drupal\Component\Utility\Unicode;
use Drupal\Component\Utility\SafeMarkup;
/**
* Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
@ -38,10 +37,10 @@ class HWLDFWordAccumulator {
protected function _flushGroup($new_tag) {
if ($this->group !== '') {
if ($this->tag == 'mark') {
$this->line = SafeMarkup::format('@original_line<span class="diffchange">@group</span>', ['@original_line' => $this->line, '@group' => $this->group]);
$this->line = $this->line . '<span class="diffchange">' . $this->group . '</span>';
}
else {
$this->line = SafeMarkup::format('@original_line@group', ['@original_line' => $this->line, '@group' => $this->group]);
$this->line = $this->line . $this->group;
}
}
$this->group = '';

View file

@ -102,4 +102,10 @@ class FileReadOnlyStorage implements PhpStorageInterface {
return $names;
}
/**
* {@inheritdoc}
*/
public function garbageCollection() {
}
}

View file

@ -266,4 +266,10 @@ EOF;
return $names;
}
/**
* {@inheritdoc}
*/
public function garbageCollection() {
}
}

View file

@ -63,7 +63,7 @@ class MTimeProtectedFastFileStorage extends FileStorage {
}
/**
* Implements Drupal\Component\PhpStorage\PhpStorageInterface::save().
* {@inheritdoc}
*/
public function save($name, $data) {
$this->ensureDirectory($this->directory);
@ -78,44 +78,32 @@ class MTimeProtectedFastFileStorage extends FileStorage {
// permission.
chmod($temporary_path, 0444);
// Prepare a directory dedicated for just this file. Ensure it has a current
// mtime so that when the file (hashed on that mtime) is moved into it, the
// mtime remains the same (unless the clock ticks to the next second during
// the rename, in which case we'll try again).
$directory = $this->getContainingDirectoryFullPath($name);
if (file_exists($directory)) {
$this->unlink($directory);
}
$this->ensureDirectory($directory);
// Determine the exact modification time of the file.
$mtime = $this->getUncachedMTime($temporary_path);
// Move the file to its final place. The mtime of a directory is the time of
// the last file create or delete in the directory. So the moving will
// update the directory mtime. However, this update will very likely not
// show up, because it has a coarse, one second granularity and typical
// moves takes significantly less than that. In the unlucky case the clock
// ticks during the move, we need to keep trying until the mtime we hashed
// on and the updated mtime match.
$previous_mtime = 0;
$i = 0;
while (($mtime = $this->getUncachedMTime($directory)) && ($mtime != $previous_mtime)) {
$previous_mtime = $mtime;
// Reset the file back in the temporary location if this is not the first
// iteration.
if ($i > 0) {
$this->unlink($temporary_path);
$temporary_path = $this->tempnam($this->directory, '.');
rename($full_path, $temporary_path);
// Make sure to not loop infinitely on a hopelessly slow filesystem.
if ($i > 10) {
$this->unlink($temporary_path);
return FALSE;
}
}
$full_path = $this->getFullPath($name, $directory, $mtime);
rename($temporary_path, $full_path);
$i++;
// Move the temporary file into the proper directory. Note that POSIX
// compliant systems as well as modern Windows perform the rename operation
// atomically, i.e. there is no point at which another process attempting to
// access the new path will find it missing.
$directory = $this->getContainingDirectoryFullPath($name);
$this->ensureDirectory($directory);
$full_path = $this->getFullPath($name, $directory, $mtime);
$result = rename($temporary_path, $full_path);
// Finally reset the modification time of the directory to match the one of
// the newly created file. In order to prevent the creation of a file if the
// directory does not exist, ensure that the path terminates with a
// directory separator.
//
// Recall that when subsequently loading the file, the hash is calculated
// based on the file name, the containing mtime, and a the secret string.
// Hence updating the mtime here is comparable to pointing a symbolic link
// at a new target, i.e., the newly created file.
if ($result) {
$result &= touch($directory . '/', $mtime);
}
return TRUE;
return (bool) $result;
}
/**
@ -161,6 +149,44 @@ class MTimeProtectedFastFileStorage extends FileStorage {
return FALSE;
}
/**
* {@inheritdoc}
*/
public function garbageCollection() {
$flags = \FilesystemIterator::CURRENT_AS_FILEINFO;
$flags += \FilesystemIterator::SKIP_DOTS;
foreach ($this->listAll() as $name) {
$directory = $this->getContainingDirectoryFullPath($name);
try {
$dir_iterator = new \FilesystemIterator($directory, $flags);
}
catch (\UnexpectedValueException $e) {
// FilesystemIterator throws an UnexpectedValueException if the
// specified path is not a directory, or if it is not accessible.
continue;
}
$directory_unlink = TRUE;
$directory_mtime = filemtime($directory);
foreach ($dir_iterator as $fileinfo) {
if ($directory_mtime > $fileinfo->getMTime()) {
// Ensure the folder is writable.
@chmod($directory, 0777);
@unlink($fileinfo->getPathName());
}
else {
// The directory still contains valid files.
$directory_unlink = FALSE;
}
}
if ($directory_unlink) {
$this->unlink($name);
}
}
}
/**
* Gets the full path of the containing directory where the file is or should
* be stored.
@ -208,4 +234,5 @@ class MTimeProtectedFastFileStorage extends FileStorage {
} while (file_exists($path));
return $path;
}
}

View file

@ -99,4 +99,11 @@ interface PhpStorageInterface {
*/
public function listAll();
/**
* Performs garbage collection on the storage.
*
* The storage may choose to delete expired or invalidated items.
*/
public function garbageCollection();
}

View file

@ -46,7 +46,7 @@ class ReflectionFactory extends DefaultFactory {
* @param string $plugin_id
* The identifier of the plugin implementation.
* @param mixed $plugin_definition
* The definition associated to the plugin_id.
* The definition associated with the plugin_id.
* @param array $configuration
* An array of configuration that may be passed to the instance.
*

View file

@ -338,14 +338,59 @@ EOD;
* "&lt;", not "<"). Be careful when using this function, as it will revert
* previous sanitization efforts (&lt;script&gt; will become <script>).
*
* This method is not the opposite of Html::escape(). For example, this method
* will convert "&eacute;" to "é", whereas Html::escape() will not convert "é"
* to "&eacute;".
*
* @param string $text
* The text to decode entities in.
*
* @return string
* The input $text, with all HTML entities decoded once.
*
* @see html_entity_decode()
* @see \Drupal\Component\Utility\Html::escape()
*/
public static function decodeEntities($text) {
return html_entity_decode($text, ENT_QUOTES, 'UTF-8');
}
/**
* Escapes text by converting special characters to HTML entities.
*
* This method escapes HTML for sanitization purposes by replacing the
* following special characters with their HTML entity equivalents:
* - & (ampersand) becomes &amp;
* - " (double quote) becomes &quot;
* - ' (single quote) becomes &#039;
* - < (less than) becomes &lt;
* - > (greater than) becomes &gt;
* Special characters that have already been escaped will be double-escaped
* (for example, "&lt;" becomes "&amp;lt;"), and invalid UTF-8 encoding
* will be converted to the Unicode replacement character ("<EFBFBD>").
*
* This method is not the opposite of Html::decodeEntities(). For example,
* this method will not encode "é" to "&eacute;", whereas
* Html::decodeEntities() will convert all HTML entities to UTF-8 bytes,
* including "&eacute;" and "&lt;" to "é" and "<".
*
* When constructing @link theme_render render arrays @endlink passing the output of Html::escape() to
* '#markup' is not recommended. Use the '#plain_text' key instead and the
* renderer will autoescape the text.
*
* @param string $text
* The input text.
*
* @return string
* The text with all HTML special characters converted.
*
* @see htmlspecialchars()
* @see \Drupal\Component\Utility\Html::decodeEntities()
*
* @ingroup sanitization
*/
public static function escape($text) {
return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
}

View file

@ -15,9 +15,9 @@ namespace Drupal\Component\Utility;
* provides a store for known safe strings and methods to manage them
* throughout the page request.
*
* Strings sanitized by self::checkPlain() and self::escape() or
* self::xssFilter() are automatically marked safe, as are markup strings
* created from @link theme_render render arrays @endlink via drupal_render().
* Strings sanitized by self::checkPlain() and self::escape() are automatically
* marked safe, as are markup strings created from @link theme_render render
* arrays @endlink via drupal_render().
*
* This class should be limited to internal use only. Module developers should
* instead use the appropriate
@ -35,57 +35,28 @@ class SafeMarkup {
/**
* The list of safe strings.
*
* Strings in this list are marked as secure for the entire page render, not
* just the code or element that set it. Therefore, only valid HTML should be
* marked as safe (never partial markup). For example, you should never mark
* string such as '<' or '<script>' safe.
*
* @var array
*/
protected static $safeStrings = array();
/**
* Adds a string to a list of strings marked as secure.
*
* This method is for internal use. Do not use it to prevent escaping of
* markup; instead, use the appropriate
* @link sanitization sanitization functions @endlink or the
* @link theme_render theme and render systems @endlink so that the output
* can be themed, escaped, and altered properly.
*
* This marks strings as secure for the entire page render, not just the code
* or element that set it. Therefore, only valid HTML should be
* marked as safe (never partial markup). For example, you should never do:
* @code
* SafeMarkup::set('<');
* @endcode
* or:
* @code
* SafeMarkup::set('<script>');
* @endcode
*
* @param string $string
* The content to be marked as secure.
* @param string $strategy
* The escaping strategy used for this string. Two values are supported
* by default:
* - 'html': (default) The string is safe for use in HTML code.
* - 'all': The string is safe for all use cases.
* See the
* @link http://twig.sensiolabs.org/doc/filters/escape.html Twig escape documentation @endlink
* for more information on escaping strategies in Twig.
*
* @return string
* The input string that was marked as safe.
*/
public static function set($string, $strategy = 'html') {
$string = (string) $string;
static::$safeStrings[$string][$strategy] = TRUE;
return $string;
}
/**
* Checks if a string is safe to output.
*
* @param string|\Drupal\Component\Utility\SafeStringInterface $string
* The content to be checked.
* @param string $strategy
* The escaping strategy. See self::set(). Defaults to 'html'.
* The escaping strategy. Defaults to 'html'. Two escaping strategies are
* supported by default:
* - 'html': (default) The string is safe for use in HTML code.
* - 'all': The string is safe for all use cases.
* See the
* @link http://twig.sensiolabs.org/doc/filters/escape.html Twig escape documentation @endlink
* for more information on escaping strategies in Twig.
*
* @return bool
* TRUE if the string has been marked secure, FALSE otherwise.
@ -100,14 +71,34 @@ class SafeMarkup {
/**
* Adds previously retrieved known safe strings to the safe string list.
*
* This is useful for the batch and form APIs, where it is important to
* preserve the safe markup state across page requests. The strings will be
* added to any safe strings already marked for the current request.
* This method is for internal use. Do not use it to prevent escaping of
* markup; instead, use the appropriate
* @link sanitization sanitization functions @endlink or the
* @link theme_render theme and render systems @endlink so that the output
* can be themed, escaped, and altered properly.
*
* This marks strings as secure for the entire page render, not just the code
* or element that set it. Therefore, only valid HTML should be
* marked as safe (never partial markup). For example, you should never do:
* @code
* SafeMarkup::setMultiple(['<' => ['html' => TRUE]]);
* @endcode
* or:
* @code
* SafeMarkup::setMultiple(['<script>' => ['all' => TRUE]]);
* @endcode
* @param array $safe_strings
* A list of safe strings as previously retrieved by self::getAll().
* Every string in this list will be represented by a multidimensional
* array in which the keys are the string and the escaping strategy used for
* this string, and in which the value is the boolean TRUE.
* See self::isSafe() for the list of supported escaping strategies.
*
* @throws \UnexpectedValueException
*
* @internal This is called by FormCache, StringTranslation and the Batch API.
* It should not be used anywhere else.
*/
public static function setMultiple(array $safe_strings) {
foreach ($safe_strings as $string => $strategies) {
@ -124,98 +115,6 @@ class SafeMarkup {
}
}
/**
* Encodes special characters in a plain-text string for display as HTML.
*
* @param string $string
* A string.
*
* @return string
* The escaped string. If $string was already set as safe with
* self::set(), it won't be escaped again.
*/
public static function escape($string) {
return static::isSafe($string) ? $string : static::checkPlain($string);
}
/**
* Applies a very permissive XSS/HTML filter for admin-only use.
*
* Note: This method only filters if $string is not marked safe already.
*
* @deprecated as of Drupal 8.0.x, will be removed before Drupal 8.0.0. If the
* string used as part of a @link theme_render render array @endlink use
* #markup to allow the render system to filter automatically. If the result
* is not being used directly in the rendering system (for example, when its
* result is being combined with other strings before rendering), use
* Xss::filterAdmin(). Otherwise, use SafeMarkup::xssFilter() and the tag
* list provided by Xss::getAdminTagList() instead. In the rare instance
* that the caller does not want to filter strings that are marked safe
* already, it needs to check SafeMarkup::isSafe() itself.
*
* @see \Drupal\Component\Utility\SafeMarkup::xssFilter()
* @see \Drupal\Component\Utility\SafeMarkup::isSafe()
* @see \Drupal\Component\Utility\Xss::filterAdmin()
* @see \Drupal\Component\Utility\Xss::getAdminTagList()
*/
public static function checkAdminXss($string) {
return static::isSafe($string) ? $string : static::xssFilter($string, Xss::getAdminTagList());
}
/**
* Filters HTML for XSS vulnerabilities and marks the result as safe.
*
* Calling this method unnecessarily will result in bloating the safe string
* list and increases the chance of unintended side effects.
*
* If Twig receives a value that is not marked as safe then it will
* automatically encode special characters in a plain-text string for display
* as HTML. Therefore, SafeMarkup::xssFilter() should only be used when the
* string might contain HTML that needs to be rendered properly by the
* browser.
*
* If you need to filter for admin use, like Xss::filterAdmin(), then:
* - If the string is used as part of a @link theme_render render array @endlink,
* use #markup to allow the render system to filter by the admin tag list
* automatically.
* - Otherwise, use the SafeMarkup::xssFilter() with tag list provided by
* Xss::getAdminTagList() instead.
*
* This method should only be used instead of Xss::filter() when the result is
* being added to a render array that is constructed before rendering begins.
*
* In the rare instance that the caller does not want to filter strings that
* are marked safe already, it needs to check SafeMarkup::isSafe() itself.
*
* @param $string
* The string with raw HTML in it. It will be stripped of everything that
* can cause an XSS attack. The string provided will always be escaped
* regardless of whether the string is already marked as safe.
* @param array $html_tags
* (optional) An array of HTML tags. If omitted, it uses the default tag
* list defined by \Drupal\Component\Utility\Xss::filter().
*
* @return string
* An XSS-safe version of $string, or an empty string if $string is not
* valid UTF-8. The string is marked as safe.
*
* @ingroup sanitization
*
* @see \Drupal\Component\Utility\Xss::filter()
* @see \Drupal\Component\Utility\Xss::filterAdmin()
* @see \Drupal\Component\Utility\Xss::getAdminTagList()
* @see \Drupal\Component\Utility\SafeMarkup::isSafe()
*/
public static function xssFilter($string, $html_tags = NULL) {
if (is_null($html_tags)) {
$string = Xss::filter($string);
}
else {
$string = Xss::filter($string, $html_tags);
}
return static::set($string);
}
/**
* Gets all strings currently marked as safe.
*
@ -244,10 +143,17 @@ class SafeMarkup {
*
* @ingroup sanitization
*
* @deprecated Will be removed before Drupal 8.0.0. Rely on Twig's
* auto-escaping feature, or use the @link theme_render #plain_text @endlink
* key when constructing a render array that contains plain text in order to
* use the renderer's auto-escaping feature. If neither of these are
* possible, \Drupal\Component\Utility\Html::escape() can be used in places
* where explicit escaping is needed.
*
* @see drupal_validate_utf8()
*/
public static function checkPlain($text) {
$string = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
$string = Html::escape($text);
static::$safeStrings[$string]['html'] = TRUE;
return $string;
}
@ -275,8 +181,8 @@ class SafeMarkup {
* formatting depends on the first character of the key:
* - @variable: Escaped to HTML using self::escape(). Use this as the
* default choice for anything displayed on a page on the site.
* - %variable: Escaped to HTML and formatted using self::placeholder(),
* which makes the following HTML code:
* - %variable: Escaped to HTML wrapped in <em> tags, which makes the
* following HTML code:
* @code
* <em class="placeholder">text output here.</em>
* @endcode
@ -296,7 +202,7 @@ class SafeMarkup {
*
* @see t()
*/
public static function format($string, array $args = array()) {
public static function format($string, array $args) {
$safe = TRUE;
// Transform arguments before inserting them.
@ -304,13 +210,18 @@ class SafeMarkup {
switch ($key[0]) {
case '@':
// Escaped only.
$args[$key] = static::escape($value);
if (!SafeMarkup::isSafe($value)) {
$args[$key] = Html::escape($value);
}
break;
case '%':
default:
// Escaped and placeholder.
$args[$key] = static::placeholder($value);
if (!SafeMarkup::isSafe($value)) {
$value = Html::escape($value);
}
$args[$key] = '<em class="placeholder">' . $value . '</em>';
break;
case '!':
@ -329,68 +240,4 @@ class SafeMarkup {
return $output;
}
/**
* Formats text for emphasized display in a placeholder inside a sentence.
*
* Used automatically by self::format().
*
* @param string $text
* The text to format (plain-text).
*
* @return string
* The formatted text (html).
*/
public static function placeholder($text) {
$string = '<em class="placeholder">' . static::escape($text) . '</em>';
static::$safeStrings[$string]['html'] = TRUE;
return $string;
}
/**
* Replaces all occurrences of the search string with the replacement string.
*
* Functions identically to str_replace(), but marks the returned output as
* safe if all the inputs and the subject have also been marked as safe.
*
* @param string|array $search
* The value being searched for. An array may be used to designate multiple
* values to search for.
* @param string|array $replace
* The replacement value that replaces found search values. An array may be
* used to designate multiple replacements.
* @param string $subject
* The string or array being searched and replaced on.
*
* @return string
* The passed subject with replaced values.
*/
public static function replace($search, $replace, $subject) {
$output = str_replace($search, $replace, $subject);
// If any replacement is unsafe, then the output is also unsafe, so just
// return the output.
if (!is_array($replace)) {
if (!SafeMarkup::isSafe($replace)) {
return $output;
}
}
else {
foreach ($replace as $replacement) {
if (!SafeMarkup::isSafe($replacement)) {
return $output;
}
}
}
// If the subject is unsafe, then the output is as well, so return it.
if (!SafeMarkup::isSafe($subject)) {
return $output;
}
else {
// If we have reached this point, then all replacements were safe. If the
// subject was also safe, then mark the entire output as safe.
return SafeMarkup::set($output);
}
}
}

View file

@ -10,20 +10,29 @@ namespace Drupal\Component\Utility;
/**
* Marks an object's __toString() method as returning safe markup.
*
* All objects that implement this interface should be marked @internal.
*
* This interface should only be used on objects that emit known safe strings
* from their __toString() method. If there is any risk of the method returning
* user-entered data that has not been filtered first, it must not be used.
*
* If the object is going to be used directly in Twig templates it should
* implement \Countable so it can be used in if statements.
*
* @internal
* This interface is marked as internal because it should only be used by
* objects used during rendering. Currently, there is no use case for this
* interface in contrib or custom code.
* objects used during rendering. This interface should be used by modules if
* they interrupt the render pipeline and explicitly deal with SafeString
* objects created by the render system. Additionally, if a module reuses the
* regular render pipeline internally and passes processed data into it. For
* example, Views implements a custom render pipeline in order to render JSON
* and to fast render fields.
*
* @see \Drupal\Component\Utility\SafeMarkup::set()
* @see \Drupal\Component\Utility\SafeStringTrait
* @see \Drupal\Component\Utility\SafeMarkup::isSafe()
* @see \Drupal\Core\Template\TwigExtension::escapeFilter()
*/
interface SafeStringInterface {
interface SafeStringInterface extends \JsonSerializable {
/**
* Returns a safe string.

View file

@ -0,0 +1,80 @@
<?php
/**
* @file
* Contains \Drupal\Component\Utility\SafeStringTrait.
*/
namespace Drupal\Component\Utility;
/**
* Implements SafeStringInterface and Countable for rendered objects.
*
* @see \Drupal\Component\Utility\SafeStringInterface
*/
trait SafeStringTrait {
/**
* The safe string.
*
* @var string
*/
protected $string;
/**
* Creates a SafeString object if necessary.
*
* If $string is equal to a blank string then it is not necessary to create a
* SafeString object. If $string is an object that implements
* SafeStringInterface it is returned unchanged.
*
* @param mixed $string
* The string to mark as safe. This value will be cast to a string.
*
* @return string|\Drupal\Component\Utility\SafeStringInterface
* A safe string.
*/
public static function create($string) {
if ($string instanceof SafeStringInterface) {
return $string;
}
$string = (string) $string;
if ($string === '') {
return '';
}
$safe_string = new static();
$safe_string->string = $string;
return $safe_string;
}
/**
* Returns the string version of the SafeString object.
*
* @return string
* The safe string content.
*/
public function __toString() {
return $this->string;
}
/**
* Returns the string length.
*
* @return int
* The length of the string.
*/
public function count() {
return Unicode::strlen($this->string);
}
/**
* Returns a representation of the object for use in JSON serialization.
*
* @return string
* The safe string content.
*/
public function jsonSerialize() {
return $this->__toString();
}
}

View file

@ -508,7 +508,7 @@ EOD;
* @param bool $add_ellipsis
* If TRUE, add '...' to the end of the truncated string (defaults to
* FALSE). The string length will still fall within $max_length.
* @param bool $min_wordsafe_length
* @param int $min_wordsafe_length
* If $wordsafe is TRUE, the minimum acceptable length for truncation (before
* adding an ellipsis, if $add_ellipsis is TRUE). Has no effect if $wordsafe
* is FALSE. This can be used to prevent having a very short resulting string

View file

@ -272,7 +272,7 @@ class UrlHelper {
// Get the plain text representation of the attribute value (i.e. its
// meaning).
$string = Html::decodeEntities($string);
return SafeMarkup::checkPlain(static::stripDangerousProtocols($string));
return Html::escape(static::stripDangerousProtocols($string));
}
/**
@ -300,10 +300,11 @@ class UrlHelper {
*
* This function must be called for all URIs within user-entered input prior
* to being output to an HTML attribute value. It is often called as part of
* check_url() or Drupal\Component\Utility\Xss::filter(), but those functions
* return an HTML-encoded string, so this function can be called independently
* when the output needs to be a plain-text string for passing to functions
* that will call \Drupal\Component\Utility\SafeMarkup::checkPlain() separately.
* \Drupal\Component\Utility\UrlHelper::filterBadProtocol() or
* \Drupal\Component\Utility\Xss::filter(), but those functions return an
* HTML-encoded string, so this function can be called independently when the
* output needs to be a plain-text string for passing to functions that will
* call \Drupal\Component\Utility\SafeMarkup::checkPlain() separately.
*
* @param string $uri
* A plain-text URI that might contain dangerous protocols.

View file

@ -46,9 +46,9 @@ class Variable {
elseif (is_string($var)) {
if (strpos($var, "\n") !== FALSE || strpos($var, "'") !== FALSE) {
// If the string contains a line break or a single quote, use the
// double quote export mode. Encode backslash and double quotes and
// transform some common control characters.
$var = str_replace(array('\\', '"', "\n", "\r", "\t"), array('\\\\', '\"', '\n', '\r', '\t'), $var);
// double quote export mode. Encode backslash, dollar symbols, and
// double quotes and transform some common control characters.
$var = str_replace(array('\\', '$', '"', "\n", "\r", "\t"), array('\\\\', '\$', '\"', '\n', '\r', '\t'), $var);
$output = '"' . $var . '"';
}
else {

View file

@ -15,7 +15,7 @@ namespace Drupal\Component\Utility;
class Xss {
/**
* The list of html tags allowed by filterAdmin().
* The list of HTML tags allowed by filterAdmin().
*
* @var array
*
@ -23,19 +23,21 @@ class Xss {
*/
protected static $adminTags = array('a', 'abbr', 'acronym', 'address', 'article', 'aside', 'b', 'bdi', 'bdo', 'big', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup', 'command', 'dd', 'del', 'details', 'dfn', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'footer', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'menu', 'meter', 'nav', 'ol', 'output', 'p', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'small', 'span', 'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time', 'tr', 'tt', 'u', 'ul', 'var', 'wbr');
/**
* The default list of HTML tags allowed by filter().
*
* @var array
*
* @see \Drupal\Component\Utility\Xss::filter()
*/
protected static $htmlTags = array('a', 'em', 'strong', 'cite', 'blockquote', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd');
/**
* Filters HTML to prevent cross-site-scripting (XSS) vulnerabilities.
*
* Based on kses by Ulf Harnhammar, see http://sourceforge.net/projects/kses.
* For examples of various XSS attacks, see: http://ha.ckers.org/xss.html.
*
* This method is preferred to
* \Drupal\Component\Utility\SafeMarkup::xssFilter() when the result is not
* being used directly in the rendering system (for example, when its result
* is being combined with other strings before rendering). This avoids
* bloating the safe string list with partial strings if the whole result will
* be marked safe.
*
* This code does four things:
* - Removes characters and constructs that can trick browsers.
* - Makes sure all HTML entities are well-formed.
@ -54,11 +56,13 @@ class Xss {
* valid UTF-8.
*
* @see \Drupal\Component\Utility\Unicode::validateUtf8()
* @see \Drupal\Component\Utility\SafeMarkup::xssFilter()
*
* @ingroup sanitization
*/
public static function filter($string, $html_tags = array('a', 'em', 'strong', 'cite', 'blockquote', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd')) {
public static function filter($string, array $html_tags = NULL) {
if (is_null($html_tags)) {
$html_tags = static::$htmlTags;
}
// Only operate on valid UTF-8 strings. This is necessary to prevent cross
// site scripting issues on Internet Explorer 6.
if (!Unicode::validateUtf8($string)) {
@ -84,10 +88,7 @@ class Xss {
$splitter = function ($matches) use ($html_tags, $class) {
return $class::split($matches[1], $html_tags, $class);
};
// Strip any tags that are not in the whitelist, then mark the text as safe
// for output. All other known XSS vectors have been filtered out by this
// point and any HTML tags remaining will have been deliberately allowed, so
// it is acceptable to call SafeMarkup::set() on the resultant string.
// Strip any tags that are not in the whitelist.
return preg_replace_callback('%
(
<(?=[^a-zA-Z!/]) # a lone <
@ -108,13 +109,6 @@ class Xss {
* is desired (so \Drupal\Component\Utility\SafeMarkup::checkPlain() is
* not acceptable).
*
* This method is preferred to
* \Drupal\Component\Utility\SafeMarkup::xssFilter() when the result is
* not being used directly in the rendering system (for example, when its
* result is being combined with other strings before rendering). This avoids
* bloating the safe string list with partial strings if the whole result will
* be marked safe.
*
* Allows all tags that can be used inside an HTML body, save
* for scripts and styles.
*
@ -126,7 +120,6 @@ class Xss {
*
* @ingroup sanitization
*
* @see \Drupal\Component\Utility\SafeMarkup::xssFilter()
* @see \Drupal\Component\Utility\Xss::getAdminTagList()
*
*/
@ -338,13 +331,22 @@ class Xss {
}
/**
* Gets the list of html tags allowed by Xss::filterAdmin().
* Gets the list of HTML tags allowed by Xss::filterAdmin().
*
* @return array
* The list of html tags allowed by filterAdmin().
* The list of HTML tags allowed by filterAdmin().
*/
public static function getAdminTagList() {
return static::$adminTags;
}
/**
* Gets the standard list of HTML tags allowed by Xss::filter().
*
* @return array
* The list of HTML tags allowed by Xss::filter().
*/
public static function getHtmlTagList() {
return static::$htmlTags;
}
}

View file

@ -8,7 +8,7 @@
namespace Drupal\Component\Uuid;
/**
* Interface that defines a UUID backend.
* Interface for generating UUIDs.
*/
interface UuidInterface {