updated packages

This commit is contained in:
2019-05-18 09:06:43 +00:00
parent 901d16349e
commit e9487fa58a
2025 changed files with 30366 additions and 49653 deletions

View File

@@ -22,7 +22,7 @@ class ChainCacheClearer implements CacheClearerInterface
{
private $clearers;
public function __construct(iterable $clearers = array())
public function __construct(iterable $clearers = [])
{
$this->clearers = $clearers;
}

View File

@@ -16,9 +16,9 @@ namespace Symfony\Component\HttpKernel\CacheClearer;
*/
class Psr6CacheClearer implements CacheClearerInterface
{
private $pools = array();
private $pools = [];
public function __construct(array $pools = array())
public function __construct(array $pools = [])
{
$this->pools = $pools;
}

View File

@@ -26,7 +26,7 @@ class CacheWarmerAggregate implements CacheWarmerInterface
private $optionalsEnabled = false;
private $onlyOptionalsEnabled = false;
public function __construct(iterable $warmers = array(), bool $debug = false, string $deprecationLogsFilepath = null)
public function __construct(iterable $warmers = [], bool $debug = false, string $deprecationLogsFilepath = null)
{
$this->warmers = $warmers;
$this->debug = $debug;
@@ -51,7 +51,7 @@ class CacheWarmerAggregate implements CacheWarmerInterface
public function warmUp($cacheDir)
{
if ($this->debug) {
$collectedLogs = array();
$collectedLogs = [];
$previousHandler = \defined('PHPUNIT_COMPOSER_INSTALL');
$previousHandler = $previousHandler ?: set_error_handler(function ($type, $message, $file, $line) use (&$collectedLogs, &$previousHandler) {
if (E_USER_DEPRECATED !== $type && E_DEPRECATED !== $type) {
@@ -73,14 +73,14 @@ class CacheWarmerAggregate implements CacheWarmerInterface
}
}
$collectedLogs[$message] = array(
$collectedLogs[$message] = [
'type' => $type,
'message' => $message,
'file' => $file,
'line' => $line,
'trace' => $backtrace,
'count' => 1,
);
];
});
}

View File

@@ -39,7 +39,7 @@ class Client extends BaseClient
* @param History $history A History instance to store the browser history
* @param CookieJar $cookieJar A CookieJar instance to store the cookies
*/
public function __construct(HttpKernelInterface $kernel, array $server = array(), History $history = null, CookieJar $cookieJar = null)
public function __construct(HttpKernelInterface $kernel, array $server = [], History $history = null, CookieJar $cookieJar = null)
{
// These class properties must be set before calling the parent constructor, as it may depend on it.
$this->kernel = $kernel;
@@ -159,7 +159,7 @@ EOF;
*/
protected function filterFiles(array $files)
{
$filtered = array();
$filtered = [];
foreach ($files as $key => $value) {
if (\is_array($value)) {
$filtered[$key] = $this->filterFiles($value);

View File

@@ -29,7 +29,7 @@ class FileLocator extends BaseFileLocator
* @param string|null $path The path the global resource directory
* @param array $paths An array of paths where to look for resources
*/
public function __construct(KernelInterface $kernel, string $path = null, array $paths = array())
public function __construct(KernelInterface $kernel, string $path = null, array $paths = [])
{
$this->kernel = $kernel;
if (null !== $path) {

View File

@@ -34,7 +34,7 @@ final class ArgumentResolver implements ArgumentResolverInterface
*/
private $argumentValueResolvers;
public function __construct(ArgumentMetadataFactoryInterface $argumentMetadataFactory = null, iterable $argumentValueResolvers = array())
public function __construct(ArgumentMetadataFactoryInterface $argumentMetadataFactory = null, iterable $argumentValueResolvers = [])
{
$this->argumentMetadataFactory = $argumentMetadataFactory ?: new ArgumentMetadataFactory();
$this->argumentValueResolvers = $argumentValueResolvers ?: self::getDefaultArgumentValueResolvers();
@@ -45,7 +45,7 @@ final class ArgumentResolver implements ArgumentResolverInterface
*/
public function getArguments(Request $request, $controller)
{
$arguments = array();
$arguments = [];
foreach ($this->argumentMetadataFactory->createArgumentMetadata($controller) as $metadata) {
foreach ($this->argumentValueResolvers as $resolver) {
@@ -83,12 +83,12 @@ final class ArgumentResolver implements ArgumentResolverInterface
public static function getDefaultArgumentValueResolvers(): iterable
{
return array(
return [
new RequestAttributeValueResolver(),
new RequestValueResolver(),
new SessionValueResolver(),
new DefaultValueResolver(),
new VariadicValueResolver(),
);
];
}
}

View File

@@ -27,15 +27,15 @@ use Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface;
class ControllerReference
{
public $controller;
public $attributes = array();
public $query = array();
public $attributes = [];
public $query = [];
/**
* @param string $controller The controller name
* @param array $attributes An array of parameters to add to the Request attributes
* @param array $query An array of parameters to add to the Request query string
*/
public function __construct(string $controller, array $attributes = array(), array $query = array())
public function __construct(string $controller, array $attributes = [], array $query = [])
{
$this->controller = $controller;
$this->attributes = $attributes;

View File

@@ -107,7 +107,7 @@ class ControllerResolver implements ControllerResolverInterface
list($class, $method) = explode('::', $controller, 2);
try {
return array($this->instantiateController($class), $method);
return [$this->instantiateController($class), $method];
} catch (\Error | \LogicException $e) {
try {
if ((new \ReflectionMethod($class, $method))->isStatic()) {
@@ -155,7 +155,7 @@ class ControllerResolver implements ControllerResolverInterface
}
if (!isset($callable[0]) || !isset($callable[1]) || 2 !== \count($callable)) {
return 'Invalid array callable, expected array(controller, method).';
return 'Invalid array callable, expected [controller, method].';
}
list($controller, $method) = $callable;
@@ -172,7 +172,7 @@ class ControllerResolver implements ControllerResolverInterface
$collection = $this->getClassMethodsWithoutMagicMethods($controller);
$alternatives = array();
$alternatives = [];
foreach ($collection as $item) {
$lev = levenshtein($method, $item);

View File

@@ -23,7 +23,7 @@ final class ArgumentMetadataFactory implements ArgumentMetadataFactoryInterface
*/
public function createArgumentMetadata($controller)
{
$arguments = array();
$arguments = [];
if (\is_array($controller)) {
$reflection = new \ReflectionMethod($controller[0], $controller[1]);

View File

@@ -57,7 +57,7 @@ class ConfigDataCollector extends DataCollector implements LateDataCollectorInte
*/
public function collect(Request $request, Response $response, \Exception $exception = null)
{
$this->data = array(
$this->data = [
'app_name' => $this->name,
'app_version' => $this->version,
'token' => $response->headers->get('X-Debug-Token'),
@@ -72,9 +72,9 @@ class ConfigDataCollector extends DataCollector implements LateDataCollectorInte
'xdebug_enabled' => \extension_loaded('xdebug'),
'apcu_enabled' => \extension_loaded('apcu') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN),
'zend_opcache_enabled' => \extension_loaded('Zend OPcache') && filter_var(ini_get('opcache.enable'), FILTER_VALIDATE_BOOLEAN),
'bundles' => array(),
'bundles' => [],
'sapi_name' => \PHP_SAPI,
);
];
if (isset($this->kernel)) {
foreach ($this->kernel->getBundles() as $name => $bundle) {
@@ -100,7 +100,7 @@ class ConfigDataCollector extends DataCollector implements LateDataCollectorInte
*/
public function reset()
{
$this->data = array();
$this->data = [];
}
public function lateCollect()

View File

@@ -27,7 +27,7 @@ use Symfony\Component\VarDumper\Cloner\VarCloner;
*/
abstract class DataCollector implements DataCollectorInterface, \Serializable
{
protected $data = array();
protected $data = [];
/**
* @var ClonerInterface
@@ -36,12 +36,15 @@ abstract class DataCollector implements DataCollectorInterface, \Serializable
public function serialize()
{
return serialize($this->data);
$trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 2);
$isCalledFromOverridingMethod = isset($trace[1]['function'], $trace[1]['object']) && 'serialize' === $trace[1]['function'] && $this === $trace[1]['object'];
return $isCalledFromOverridingMethod ? $this->data : serialize($this->data);
}
public function unserialize($data)
{
$this->data = unserialize($data);
$this->data = \is_array($data) ? $data : unserialize($data);
}
/**
@@ -76,7 +79,7 @@ abstract class DataCollector implements DataCollectorInterface, \Serializable
*/
protected function getCasters()
{
return array(
return [
'*' => function ($v, array $a, Stub $s, $isNested) {
if (!$v instanceof Stub) {
foreach ($a as $k => $v) {
@@ -88,6 +91,6 @@ abstract class DataCollector implements DataCollectorInterface, \Serializable
return $a;
},
);
];
}
}

View File

@@ -52,12 +52,12 @@ class DumpDataCollector extends DataCollector implements DataDumperInterface
$this->dumper = $dumper;
// All clones share these properties by reference:
$this->rootRefs = array(
$this->rootRefs = [
&$this->data,
&$this->dataCount,
&$this->isCollected,
&$this->clonesCount,
);
];
$this->sourceContextProvider = $dumper instanceof Connection && isset($dumper->getContextProviders()['source']) ? $dumper->getContextProviders()['source'] : new SourceContextProvider($this->charset);
}
@@ -110,7 +110,7 @@ class DumpDataCollector extends DataCollector implements DataDumperInterface
) {
if ($response->headers->has('Content-Type') && false !== strpos($response->headers->get('Content-Type'), 'html')) {
$dumper = new HtmlDumper('php://output', $this->charset);
$dumper->setDisplayOptions(array('fileLinkFormat' => $this->fileLinkFormat));
$dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
} else {
$dumper = new CliDumper('php://output', $this->charset);
}
@@ -126,7 +126,7 @@ class DumpDataCollector extends DataCollector implements DataDumperInterface
if ($this->stopwatch) {
$this->stopwatch->reset();
}
$this->data = array();
$this->data = [];
$this->dataCount = 0;
$this->isCollected = true;
$this->clonesCount = 0;
@@ -142,7 +142,7 @@ class DumpDataCollector extends DataCollector implements DataDumperInterface
$this->data[] = $this->fileLinkFormat;
$this->data[] = $this->charset;
$ser = serialize($this->data);
$this->data = array();
$this->data = [];
$this->dataCount = 0;
$this->isCollected = true;
@@ -151,7 +151,7 @@ class DumpDataCollector extends DataCollector implements DataDumperInterface
public function unserialize($data)
{
parent::unserialize($data);
$this->data = unserialize($data);
$charset = array_pop($this->data);
$fileLinkFormat = array_pop($this->data);
$this->dataCount = \count($this->data);
@@ -169,11 +169,11 @@ class DumpDataCollector extends DataCollector implements DataDumperInterface
if ('html' === $format) {
$dumper = new HtmlDumper($data, $this->charset);
$dumper->setDisplayOptions(array('fileLinkFormat' => $this->fileLinkFormat));
$dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
} else {
throw new \InvalidArgumentException(sprintf('Invalid dump format: %s', $format));
}
$dumps = array();
$dumps = [];
foreach ($this->data as $dump) {
$dumper->dump($dump['data']->withMaxDepth($maxDepthLimit)->withMaxItemsPerDepth($maxItemsPerDepth));
@@ -207,12 +207,12 @@ class DumpDataCollector extends DataCollector implements DataDumperInterface
if (isset($_SERVER['VAR_DUMPER_FORMAT'])) {
$html = 'html' === $_SERVER['VAR_DUMPER_FORMAT'];
} else {
$html = !\in_array(\PHP_SAPI, array('cli', 'phpdbg'), true) && stripos($h[$i], 'html');
$html = !\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && stripos($h[$i], 'html');
}
if ($html) {
$dumper = new HtmlDumper('php://output', $this->charset);
$dumper->setDisplayOptions(array('fileLinkFormat' => $this->fileLinkFormat));
$dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
} else {
$dumper = new CliDumper('php://output', $this->charset);
}
@@ -222,7 +222,7 @@ class DumpDataCollector extends DataCollector implements DataDumperInterface
$this->doDump($dumper, $dump['data'], $dump['name'], $dump['file'], $dump['line']);
}
$this->data = array();
$this->data = [];
$this->dataCount = 0;
}
}
@@ -236,7 +236,7 @@ class DumpDataCollector extends DataCollector implements DataDumperInterface
$s = $this->style('meta', '%s');
$f = strip_tags($this->style('', $file));
$name = strip_tags($this->style('', $name));
if ($fmt && $link = \is_string($fmt) ? strtr($fmt, array('%f' => $file, '%l' => $line)) : $fmt->format($file, $line)) {
if ($fmt && $link = \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : $fmt->format($file, $line)) {
$name = sprintf('<a href="%s" title="%s">'.$s.'</a>', strip_tags($this->style('', $link)), $f, $name);
} else {
$name = sprintf('<abbr title="%s">'.$s.'</abbr>', $f, $name);

View File

@@ -37,16 +37,16 @@ class EventDataCollector extends DataCollector implements LateDataCollectorInter
*/
public function collect(Request $request, Response $response, \Exception $exception = null)
{
$this->data = array(
'called_listeners' => array(),
'not_called_listeners' => array(),
'orphaned_events' => array(),
);
$this->data = [
'called_listeners' => [],
'not_called_listeners' => [],
'orphaned_events' => [],
];
}
public function reset()
{
$this->data = array();
$this->data = [];
if ($this->dispatcher instanceof ResetInterface) {
$this->dispatcher->reset();

View File

@@ -28,9 +28,9 @@ class ExceptionDataCollector extends DataCollector
public function collect(Request $request, Response $response, \Exception $exception = null)
{
if (null !== $exception) {
$this->data = array(
$this->data = [
'exception' => FlattenException::create($exception),
);
];
}
}
@@ -39,7 +39,7 @@ class ExceptionDataCollector extends DataCollector
*/
public function reset()
{
$this->data = array();
$this->data = [];
}
/**

View File

@@ -55,7 +55,7 @@ class LoggerDataCollector extends DataCollector implements LateDataCollectorInte
if ($this->logger instanceof DebugLoggerInterface) {
$this->logger->clear();
}
$this->data = array();
$this->data = [];
}
/**
@@ -80,12 +80,12 @@ class LoggerDataCollector extends DataCollector implements LateDataCollectorInte
*/
public function getLogs()
{
return isset($this->data['logs']) ? $this->data['logs'] : array();
return isset($this->data['logs']) ? $this->data['logs'] : [];
}
public function getPriorities()
{
return isset($this->data['priorities']) ? $this->data['priorities'] : array();
return isset($this->data['priorities']) ? $this->data['priorities'] : [];
}
public function countErrors()
@@ -110,7 +110,7 @@ class LoggerDataCollector extends DataCollector implements LateDataCollectorInte
public function getCompilerLogs()
{
return isset($this->data['compiler_logs']) ? $this->data['compiler_logs'] : array();
return isset($this->data['compiler_logs']) ? $this->data['compiler_logs'] : [];
}
/**
@@ -124,13 +124,17 @@ class LoggerDataCollector extends DataCollector implements LateDataCollectorInte
private function getContainerDeprecationLogs()
{
if (null === $this->containerPathPrefix || !file_exists($file = $this->containerPathPrefix.'Deprecations.log')) {
return array();
return [];
}
if ('' === $logContent = trim(file_get_contents($file))) {
return [];
}
$bootTime = filemtime($file);
$logs = array();
foreach (unserialize(file_get_contents($file)) as $log) {
$log['context'] = array('exception' => new SilencedErrorContext($log['type'], $log['file'], $log['line'], $log['trace'], $log['count']));
$logs = [];
foreach (unserialize($logContent) as $log) {
$log['context'] = ['exception' => new SilencedErrorContext($log['type'], $log['file'], $log['line'], $log['trace'], $log['count'])];
$log['timestamp'] = $bootTime;
$log['priority'] = 100;
$log['priorityName'] = 'DEBUG';
@@ -146,17 +150,17 @@ class LoggerDataCollector extends DataCollector implements LateDataCollectorInte
private function getContainerCompilerLogs()
{
if (null === $this->containerPathPrefix || !file_exists($file = $this->containerPathPrefix.'Compiler.log')) {
return array();
return [];
}
$logs = array();
$logs = [];
foreach (file($file, FILE_IGNORE_NEW_LINES) as $log) {
$log = explode(': ', $log, 2);
if (!isset($log[1]) || !preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\\\\[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)++$/', $log[0])) {
$log = array('Unknown Compiler Pass', implode(': ', $log));
$log = ['Unknown Compiler Pass', implode(': ', $log)];
}
$logs[$log[0]][] = array('message' => $log[1]);
$logs[$log[0]][] = ['message' => $log[1]];
}
return $logs;
@@ -164,8 +168,8 @@ class LoggerDataCollector extends DataCollector implements LateDataCollectorInte
private function sanitizeLogs($logs)
{
$sanitizedLogs = array();
$silencedLogs = array();
$sanitizedLogs = [];
$silencedLogs = [];
foreach ($logs as $log) {
if (!$this->isSilencedOrDeprecationErrorLog($log)) {
@@ -184,10 +188,10 @@ class LoggerDataCollector extends DataCollector implements LateDataCollectorInte
$silencedLogs[$h] = true;
if (!isset($sanitizedLogs[$message])) {
$sanitizedLogs[$message] = $log + array(
$sanitizedLogs[$message] = $log + [
'errorCount' => 0,
'scream' => true,
);
];
}
$sanitizedLogs[$message]['errorCount'] += $exception->count;
@@ -199,10 +203,10 @@ class LoggerDataCollector extends DataCollector implements LateDataCollectorInte
if (isset($sanitizedLogs[$errorId])) {
++$sanitizedLogs[$errorId]['errorCount'];
} else {
$log += array(
$log += [
'errorCount' => 1,
'scream' => false,
);
];
$sanitizedLogs[$errorId] = $log;
}
@@ -223,7 +227,7 @@ class LoggerDataCollector extends DataCollector implements LateDataCollectorInte
return true;
}
if ($exception instanceof \ErrorException && \in_array($exception->getSeverity(), array(E_DEPRECATED, E_USER_DEPRECATED), true)) {
if ($exception instanceof \ErrorException && \in_array($exception->getSeverity(), [E_DEPRECATED, E_USER_DEPRECATED], true)) {
return true;
}
@@ -232,23 +236,23 @@ class LoggerDataCollector extends DataCollector implements LateDataCollectorInte
private function computeErrorsCount(array $containerDeprecationLogs)
{
$silencedLogs = array();
$count = array(
$silencedLogs = [];
$count = [
'error_count' => $this->logger->countErrors($this->currentRequest),
'deprecation_count' => 0,
'warning_count' => 0,
'scream_count' => 0,
'priorities' => array(),
);
'priorities' => [],
];
foreach ($this->logger->getLogs($this->currentRequest) as $log) {
if (isset($count['priorities'][$log['priority']])) {
++$count['priorities'][$log['priority']]['count'];
} else {
$count['priorities'][$log['priority']] = array(
$count['priorities'][$log['priority']] = [
'count' => 1,
'name' => $log['priorityName'],
);
];
}
if ('WARNING' === $log['priorityName']) {
++$count['warning_count'];

View File

@@ -39,10 +39,10 @@ class MemoryDataCollector extends DataCollector implements LateDataCollectorInte
*/
public function reset()
{
$this->data = array(
$this->data = [
'memory' => 0,
'memory_limit' => $this->convertToBytes(ini_get('memory_limit')),
);
];
}
/**

View File

@@ -38,7 +38,7 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter
public function collect(Request $request, Response $response, \Exception $exception = null)
{
// attributes are serialized and as they can be anything, they need to be converted to strings.
$attributes = array();
$attributes = [];
$route = '';
foreach ($request->attributes->all() as $key => $value) {
if ('_route' === $key) {
@@ -57,10 +57,10 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter
$content = false;
}
$sessionMetadata = array();
$sessionAttributes = array();
$sessionMetadata = [];
$sessionAttributes = [];
$session = null;
$flashes = array();
$flashes = [];
if ($request->hasSession()) {
$session = $request->getSession();
if ($session->isStarted()) {
@@ -74,19 +74,19 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter
$statusCode = $response->getStatusCode();
$responseCookies = array();
$responseCookies = [];
foreach ($response->headers->getCookies() as $cookie) {
$responseCookies[$cookie->getName()] = $cookie;
}
$dotenvVars = array();
$dotenvVars = [];
foreach (explode(',', getenv('SYMFONY_DOTENV_VARS')) as $name) {
if ('' !== $name && false !== $value = getenv($name)) {
$dotenvVars[$name] = $value;
}
}
$this->data = array(
$this->data = [
'method' => $request->getMethod(),
'format' => $request->getRequestFormat(),
'content' => $content,
@@ -110,7 +110,7 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter
'controller' => 'n/a',
'locale' => $request->getLocale(),
'dotenv_vars' => $dotenvVars,
);
];
if (isset($this->data['request_headers']['php-auth-pw'])) {
$this->data['request_headers']['php-auth-pw'] = '******';
@@ -147,14 +147,14 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter
if ($response->isRedirect()) {
$response->headers->setCookie(new Cookie(
'sf_redirect',
json_encode(array(
json_encode([
'token' => $response->headers->get('x-debug-token'),
'route' => $request->attributes->get('_route', 'n/a'),
'method' => $request->getMethod(),
'controller' => $this->parseController($request->attributes->get('_controller')),
'status_code' => $statusCode,
'status_text' => Response::$statusTexts[(int) $statusCode],
)),
]),
0, '/', null, $request->isSecure(), true, false, 'lax'
));
}
@@ -173,7 +173,7 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter
public function reset()
{
$this->data = array();
$this->data = [];
$this->controllers = new \SplObjectStorage();
}
@@ -308,7 +308,7 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter
*/
public function getRouteParams()
{
return isset($this->data['request_attributes']['_route_params']) ? $this->data['request_attributes']['_route_params']->getValue() : array();
return isset($this->data['request_attributes']['_route_params']) ? $this->data['request_attributes']['_route_params']->getValue() : [];
}
/**
@@ -356,10 +356,10 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter
public static function getSubscribedEvents()
{
return array(
return [
KernelEvents::CONTROLLER => 'onKernelController',
KernelEvents::RESPONSE => 'onKernelResponse',
);
];
}
/**
@@ -387,21 +387,21 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter
try {
$r = new \ReflectionMethod($controller[0], $controller[1]);
return array(
return [
'class' => \is_object($controller[0]) ? \get_class($controller[0]) : $controller[0],
'method' => $controller[1],
'file' => $r->getFileName(),
'line' => $r->getStartLine(),
);
];
} catch (\ReflectionException $e) {
if (\is_callable($controller)) {
// using __call or __callStatic
return array(
return [
'class' => \is_object($controller[0]) ? \get_class($controller[0]) : $controller[0],
'method' => $controller[1],
'file' => 'n/a',
'line' => 'n/a',
);
];
}
}
}
@@ -409,12 +409,12 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter
if ($controller instanceof \Closure) {
$r = new \ReflectionFunction($controller);
$controller = array(
$controller = [
'class' => $r->getName(),
'method' => null,
'file' => $r->getFileName(),
'line' => $r->getStartLine(),
);
];
if (false !== strpos($r->name, '{closure}')) {
return $controller;
@@ -433,12 +433,12 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter
if (\is_object($controller)) {
$r = new \ReflectionClass($controller);
return array(
return [
'class' => $r->getName(),
'method' => null,
'file' => $r->getFileName(),
'line' => $r->getStartLine(),
);
];
}
return \is_string($controller) ? $controller : 'n/a';

View File

@@ -54,11 +54,11 @@ class RouterDataCollector extends DataCollector
{
$this->controllers = new \SplObjectStorage();
$this->data = array(
$this->data = [
'redirect' => false,
'url' => null,
'route' => null,
);
];
}
protected function guessRoute(Request $request, $controller)

View File

@@ -43,11 +43,12 @@ class TimeDataCollector extends DataCollector implements LateDataCollectorInterf
$startTime = $request->server->get('REQUEST_TIME_FLOAT');
}
$this->data = array(
$this->data = [
'token' => $response->headers->get('X-Debug-Token'),
'start_time' => $startTime * 1000,
'events' => array(),
);
'events' => [],
'stopwatch_installed' => \class_exists(Stopwatch::class, false),
];
}
/**
@@ -55,7 +56,7 @@ class TimeDataCollector extends DataCollector implements LateDataCollectorInterf
*/
public function reset()
{
$this->data = array();
$this->data = [];
if (null !== $this->stopwatch) {
$this->stopwatch->reset();
@@ -139,6 +140,14 @@ class TimeDataCollector extends DataCollector implements LateDataCollectorInterf
return $this->data['start_time'];
}
/**
* @return bool whether or not the stopwatch component is installed
*/
public function isStopwatchInstalled()
{
return $this->data['stopwatch_installed'];
}
/**
* {@inheritdoc}
*/

View File

@@ -36,7 +36,7 @@ class FileLinkFormatter implements \Serializable
$fileLinkFormat = $fileLinkFormat ?: ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format');
if ($fileLinkFormat && !\is_array($fileLinkFormat)) {
$i = strpos($f = $fileLinkFormat, '&', max(strrpos($f, '%f'), strrpos($f, '%l'))) ?: \strlen($f);
$fileLinkFormat = array(substr($f, 0, $i)) + preg_split('/&([^>]++)>/', substr($f, $i), -1, PREG_SPLIT_DELIM_CAPTURE);
$fileLinkFormat = [substr($f, 0, $i)] + preg_split('/&([^>]++)>/', substr($f, $i), -1, PREG_SPLIT_DELIM_CAPTURE);
}
$this->fileLinkFormat = $fileLinkFormat;
@@ -55,20 +55,26 @@ class FileLinkFormatter implements \Serializable
}
}
return strtr($fmt[0], array('%f' => $file, '%l' => $line));
return strtr($fmt[0], ['%f' => $file, '%l' => $line]);
}
return false;
}
/**
* @internal
*/
public function serialize()
{
return serialize($this->getFileLinkFormat());
}
/**
* @internal
*/
public function unserialize($serialized)
{
$this->fileLinkFormat = unserialize($serialized, array('allowed_classes' => false));
$this->fileLinkFormat = unserialize($serialized, ['allowed_classes' => false]);
}
/**
@@ -95,10 +101,10 @@ class FileLinkFormatter implements \Serializable
return;
}
return array(
return [
$request->getSchemeAndHttpHost().$request->getBasePath().$this->urlFormat,
$this->baseDir.\DIRECTORY_SEPARATOR, '',
);
];
}
}
}

View File

@@ -59,7 +59,7 @@ class AddAnnotatedClassesToCachePass implements CompilerPassInterface
*/
private function expandClasses(array $patterns, array $classes)
{
$expanded = array();
$expanded = [];
// Explicit classes declared in the patterns are returned directly
foreach ($patterns as $key => $pattern) {
@@ -85,7 +85,7 @@ class AddAnnotatedClassesToCachePass implements CompilerPassInterface
private function getClassesInComposerClassMaps()
{
$classes = array();
$classes = [];
foreach (spl_autoload_functions() as $function) {
if (!\is_array($function)) {
@@ -106,14 +106,14 @@ class AddAnnotatedClassesToCachePass implements CompilerPassInterface
private function patternsToRegexps($patterns)
{
$regexps = array();
$regexps = [];
foreach ($patterns as $pattern) {
// Escape user input
$regex = preg_quote(ltrim($pattern, '\\'));
// Wildcards * and **
$regex = strtr($regex, array('\\*\\*' => '.*?', '\\*' => '[^\\\\]*?'));
$regex = strtr($regex, ['\\*\\*' => '.*?', '\\*' => '[^\\\\]*?']);
// If this class does not end by a slash, anchor the end
if ('\\' !== substr($regex, -1)) {

View File

@@ -52,7 +52,7 @@ class ControllerArgumentValueResolverPass implements CompilerPassInterface
$id = (string) $resolverReference;
$container->register("debug.$id", TraceableValueResolver::class)
->setDecoratedService($id)
->setArguments(array(new Reference("debug.$id.inner"), new Reference($this->traceableResolverStopwatch)));
->setArguments([new Reference("debug.$id.inner"), new Reference($this->traceableResolverStopwatch)]);
}
}

View File

@@ -20,7 +20,7 @@ use Symfony\Component\DependencyInjection\Extension\Extension as BaseExtension;
*/
abstract class Extension extends BaseExtension
{
private $annotatedClasses = array();
private $annotatedClasses = [];
/**
* Gets the annotated classes to cache.

View File

@@ -41,7 +41,7 @@ class FragmentRendererPass implements CompilerPassInterface
}
$definition = $container->getDefinition($this->handlerService);
$renderers = array();
$renderers = [];
foreach ($container->findTaggedServiceIds($this->rendererTag, true) as $id => $tags) {
$def = $container->getDefinition($id);
$class = $container->getParameterBag()->resolveValue($def->getClass());

View File

@@ -23,19 +23,19 @@ use Symfony\Component\HttpKernel\Fragment\FragmentHandler;
class LazyLoadingFragmentHandler extends FragmentHandler
{
private $container;
private $initialized = array();
private $initialized = [];
public function __construct(ContainerInterface $container, RequestStack $requestStack, bool $debug = false)
{
$this->container = $container;
parent::__construct($requestStack, array(), $debug);
parent::__construct($requestStack, [], $debug);
}
/**
* {@inheritdoc}
*/
public function render($uri, $renderer = 'inline', array $options = array())
public function render($uri, $renderer = 'inline', array $options = [])
{
if (!isset($this->initialized[$renderer]) && $this->container->has($renderer)) {
$this->addRenderer($this->container->get($renderer));

View File

@@ -32,7 +32,7 @@ class MergeExtensionConfigurationPass extends BaseMergeExtensionConfigurationPas
{
foreach ($this->extensions as $extension) {
if (!\count($container->getExtensionConfig($extension))) {
$container->loadFromExtension($extension, array());
$container->loadFromExtension($extension, []);
}
}

View File

@@ -49,7 +49,7 @@ class RegisterControllerArgumentLocatorsPass implements CompilerPassInterface
}
$parameterBag = $container->getParameterBag();
$controllers = array();
$controllers = [];
foreach ($container->findTaggedServiceIds($this->controllerTag, true) as $id => $tags) {
$def = $container->getDefinition($id);
@@ -72,14 +72,14 @@ class RegisterControllerArgumentLocatorsPass implements CompilerPassInterface
$isContainerAware = $r->implementsInterface(ContainerAwareInterface::class) || is_subclass_of($class, AbstractController::class);
// get regular public methods
$methods = array();
$arguments = array();
$methods = [];
$arguments = [];
foreach ($r->getMethods(\ReflectionMethod::IS_PUBLIC) as $r) {
if ('setContainer' === $r->name && $isContainerAware) {
continue;
}
if (!$r->isConstructor() && !$r->isDestructor() && !$r->isAbstract()) {
$methods[strtolower($r->name)] = array($r, $r->getParameters());
$methods[strtolower($r->name)] = [$r, $r->getParameters()];
}
}
@@ -89,7 +89,7 @@ class RegisterControllerArgumentLocatorsPass implements CompilerPassInterface
$autowire = true;
continue;
}
foreach (array('action', 'argument', 'id') as $k) {
foreach (['action', 'argument', 'id'] as $k) {
if (!isset($attributes[$k][0])) {
throw new InvalidArgumentException(sprintf('Missing "%s" attribute on tag "%s" %s for service "%s".', $k, $this->controllerTag, json_encode($attributes, JSON_UNESCAPED_UNICODE), $id));
}
@@ -119,7 +119,7 @@ class RegisterControllerArgumentLocatorsPass implements CompilerPassInterface
/** @var \ReflectionMethod $r */
// create a per-method map of argument-names to service/type-references
$args = array();
$args = [];
foreach ($parameters as $p) {
/** @var \ReflectionParameter $p */
$type = ltrim($target = ProxyHelper::getTypeHint($r, $p), '\\');
@@ -138,13 +138,13 @@ class RegisterControllerArgumentLocatorsPass implements CompilerPassInterface
$binding = $bindings[$bindingName];
list($bindingValue, $bindingId) = $binding->getValues();
$binding->setValues(array($bindingValue, $bindingId, true));
$binding->setValues([$bindingValue, $bindingId, true]);
if (!$bindingValue instanceof Reference) {
$args[$p->name] = new Reference('.value.'.$container->hash($bindingValue));
$container->register((string) $args[$p->name], 'mixed')
->setFactory('current')
->addArgument(array($bindingValue));
->addArgument([$bindingValue]);
} else {
$args[$p->name] = $bindingValue;
}

View File

@@ -39,7 +39,7 @@ class ResettableServicePass implements CompilerPassInterface
return;
}
$services = $methods = array();
$services = $methods = [];
foreach ($container->findTaggedServiceIds($this->tagName, true) as $id => $tags) {
$services[$id] = new Reference($id, ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE);

View File

@@ -38,7 +38,7 @@ abstract class AbstractSessionListener implements EventSubscriberInterface
const NO_AUTO_CACHE_CONTROL_HEADER = 'Symfony-Session-NoAutoCacheControl';
protected $container;
private $sessionUsageStack = array();
private $sessionUsageStack = [];
public function __construct(ContainerInterface $container = null)
{
@@ -131,12 +131,12 @@ abstract class AbstractSessionListener implements EventSubscriberInterface
public static function getSubscribedEvents()
{
return array(
KernelEvents::REQUEST => array('onKernelRequest', 128),
return [
KernelEvents::REQUEST => ['onKernelRequest', 128],
// low priority to come after regular response listeners, but higher than StreamedResponseListener
KernelEvents::RESPONSE => array('onKernelResponse', -1000),
KernelEvents::FINISH_REQUEST => array('onFinishRequest'),
);
KernelEvents::RESPONSE => ['onKernelResponse', -1000],
KernelEvents::FINISH_REQUEST => ['onFinishRequest'],
];
}
/**

View File

@@ -32,7 +32,7 @@ abstract class AbstractTestSessionListener implements EventSubscriberInterface
private $sessionId;
private $sessionOptions;
public function __construct(array $sessionOptions = array())
public function __construct(array $sessionOptions = [])
{
$this->sessionOptions = $sessionOptions;
}
@@ -78,7 +78,7 @@ abstract class AbstractTestSessionListener implements EventSubscriberInterface
}
if ($session instanceof Session ? !$session->isEmpty() || (null !== $this->sessionId && $session->getId() !== $this->sessionId) : $wasStarted) {
$params = session_get_cookie_params() + array('samesite' => null);
$params = session_get_cookie_params() + ['samesite' => null];
foreach ($this->sessionOptions as $k => $v) {
if (0 === strpos($k, 'cookie_')) {
$params[substr($k, 7)] = $v;
@@ -98,10 +98,10 @@ abstract class AbstractTestSessionListener implements EventSubscriberInterface
public static function getSubscribedEvents()
{
return array(
KernelEvents::REQUEST => array('onKernelRequest', 192),
KernelEvents::RESPONSE => array('onKernelResponse', -128),
);
return [
KernelEvents::REQUEST => ['onKernelRequest', 192],
KernelEvents::RESPONSE => ['onKernelResponse', -128],
];
}
/**

View File

@@ -45,6 +45,6 @@ class AddRequestFormatsListener implements EventSubscriberInterface
*/
public static function getSubscribedEvents()
{
return array(KernelEvents::REQUEST => array('onKernelRequest', 1));
return [KernelEvents::REQUEST => ['onKernelRequest', 1]];
}
}

View File

@@ -19,6 +19,7 @@ use Symfony\Component\Debug\ErrorHandler;
use Symfony\Component\Debug\ExceptionHandler;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;
use Symfony\Component\HttpKernel\Event\KernelEvent;
use Symfony\Component\HttpKernel\KernelEvents;
@@ -40,13 +41,13 @@ class DebugHandlersListener implements EventSubscriberInterface
private $hasTerminatedWithException;
/**
* @param callable|null $exceptionHandler A handler that will be called on Exception
* @param LoggerInterface|null $logger A PSR-3 logger
* @param array|int $levels An array map of E_* to LogLevel::* or an integer bit field of E_* constants
* @param int|null $throwAt Thrown errors in a bit field of E_* constants, or null to keep the current value
* @param bool $scream Enables/disables screaming mode, where even silenced errors are logged
* @param string|array $fileLinkFormat The format for links to source files
* @param bool $scope Enables/disables scoping mode
* @param callable|null $exceptionHandler A handler that will be called on Exception
* @param LoggerInterface|null $logger A PSR-3 logger
* @param array|int $levels An array map of E_* to LogLevel::* or an integer bit field of E_* constants
* @param int|null $throwAt Thrown errors in a bit field of E_* constants, or null to keep the current value
* @param bool $scream Enables/disables screaming mode, where even silenced errors are logged
* @param string|FileLinkFormatter|null $fileLinkFormat The format for links to source files
* @param bool $scope Enables/disables scoping mode
*/
public function __construct(callable $exceptionHandler = null, LoggerInterface $logger = null, $levels = E_ALL, ?int $throwAt = E_ALL, bool $scream = true, $fileLinkFormat = null, bool $scope = true)
{
@@ -105,7 +106,7 @@ class DebugHandlersListener implements EventSubscriberInterface
if (method_exists($kernel = $event->getKernel(), 'terminateWithException')) {
$request = $event->getRequest();
$hasRun = &$this->hasTerminatedWithException;
$this->exceptionHandler = function (\Exception $e) use ($kernel, $request, &$hasRun) {
$this->exceptionHandler = static function (\Exception $e) use ($kernel, $request, &$hasRun) {
if ($hasRun) {
throw $e;
}
@@ -145,10 +146,10 @@ class DebugHandlersListener implements EventSubscriberInterface
public static function getSubscribedEvents()
{
$events = array(KernelEvents::REQUEST => array('configure', 2048));
$events = [KernelEvents::REQUEST => ['configure', 2048]];
if ('cli' === \PHP_SAPI && \defined('Symfony\Component\Console\ConsoleEvents::COMMAND')) {
$events[ConsoleEvents::COMMAND] = array('configure', 2048);
$events[ConsoleEvents::COMMAND] = ['configure', 2048];
}
return $events;

View File

@@ -54,10 +54,10 @@ class DumpListener implements EventSubscriberInterface
public static function getSubscribedEvents()
{
if (!class_exists(ConsoleEvents::class)) {
return array();
return [];
}
// Register early to have a working dump() as early as possible
return array(ConsoleEvents::COMMAND => array('configure', 1024));
return [ConsoleEvents::COMMAND => ['configure', 1024]];
}
}

View File

@@ -79,13 +79,12 @@ class ExceptionListener implements EventSubscriberInterface
$this->logException($e, sprintf('Exception thrown when handling an exception (%s: %s at %s line %s)', $f->getClass(), $f->getMessage(), $e->getFile(), $e->getLine()));
$wrapper = $e;
while ($prev = $wrapper->getPrevious()) {
$prev = $e;
do {
if ($exception === $wrapper = $prev) {
throw $e;
}
}
} while ($prev = $wrapper->getPrevious());
$prev = new \ReflectionProperty($wrapper instanceof \Exception ? \Exception::class : \Error::class, 'previous');
$prev->setAccessible(true);
@@ -112,12 +111,12 @@ class ExceptionListener implements EventSubscriberInterface
public static function getSubscribedEvents()
{
return array(
KernelEvents::EXCEPTION => array(
array('logKernelException', 0),
array('onKernelException', -128),
),
);
return [
KernelEvents::EXCEPTION => [
['logKernelException', 0],
['onKernelException', -128],
],
];
}
/**
@@ -130,9 +129,9 @@ class ExceptionListener implements EventSubscriberInterface
{
if (null !== $this->logger) {
if (!$exception instanceof HttpExceptionInterface || $exception->getStatusCode() >= 500) {
$this->logger->critical($message, array('exception' => $exception));
$this->logger->critical($message, ['exception' => $exception]);
} else {
$this->logger->error($message, array('exception' => $exception));
$this->logger->error($message, ['exception' => $exception]);
}
}
}
@@ -147,7 +146,7 @@ class ExceptionListener implements EventSubscriberInterface
*/
protected function duplicateRequest(\Exception $exception, Request $request)
{
$attributes = array(
$attributes = [
'exception' => $exception = FlattenException::create($exception),
'_controller' => $this->controller ?: function () use ($exception) {
$handler = new ExceptionHandler($this->debug, $this->charset, $this->fileLinkFormat);
@@ -155,7 +154,7 @@ class ExceptionListener implements EventSubscriberInterface
return new Response($handler->getHtml($exception), $exception->getStatusCode(), $exception->getHeaders());
},
'logger' => $this->logger instanceof DebugLoggerInterface ? $this->logger : null,
);
];
$request = $request->duplicate(null, null, $attributes);
$request->setMethod('GET');

View File

@@ -70,7 +70,7 @@ class FragmentListener implements EventSubscriberInterface
parse_str($request->query->get('_path', ''), $attributes);
$request->attributes->add($attributes);
$request->attributes->set('_route_params', array_replace($request->attributes->get('_route_params', array()), $attributes));
$request->attributes->set('_route_params', array_replace($request->attributes->get('_route_params', []), $attributes));
$request->query->remove('_path');
}
@@ -92,8 +92,8 @@ class FragmentListener implements EventSubscriberInterface
public static function getSubscribedEvents()
{
return array(
KernelEvents::REQUEST => array(array('onKernelRequest', 48)),
);
return [
KernelEvents::REQUEST => [['onKernelRequest', 48]],
];
}
}

View File

@@ -74,10 +74,10 @@ class LocaleListener implements EventSubscriberInterface
public static function getSubscribedEvents()
{
return array(
return [
// must be registered after the Router to have access to the _locale
KernelEvents::REQUEST => array(array('onKernelRequest', 16)),
KernelEvents::FINISH_REQUEST => array(array('onKernelFinishRequest', 0)),
);
KernelEvents::REQUEST => [['onKernelRequest', 16]],
KernelEvents::FINISH_REQUEST => [['onKernelFinishRequest', 0]],
];
}
}

View File

@@ -119,10 +119,10 @@ class ProfilerListener implements EventSubscriberInterface
public static function getSubscribedEvents()
{
return array(
KernelEvents::RESPONSE => array('onKernelResponse', -100),
KernelEvents::EXCEPTION => array('onKernelException', 0),
KernelEvents::TERMINATE => array('onKernelTerminate', -1024),
);
return [
KernelEvents::RESPONSE => ['onKernelResponse', -100],
KernelEvents::EXCEPTION => ['onKernelException', 0],
KernelEvents::TERMINATE => ['onKernelTerminate', -1024],
];
}
}

View File

@@ -49,8 +49,8 @@ class ResponseListener implements EventSubscriberInterface
public static function getSubscribedEvents()
{
return array(
return [
KernelEvents::RESPONSE => 'onKernelResponse',
);
];
}
}

View File

@@ -118,12 +118,12 @@ class RouterListener implements EventSubscriberInterface
}
if (null !== $this->logger) {
$this->logger->info('Matched route "{route}".', array(
$this->logger->info('Matched route "{route}".', [
'route' => isset($parameters['_route']) ? $parameters['_route'] : 'n/a',
'route_parameters' => $parameters,
'request_uri' => $request->getUri(),
'method' => $request->getMethod(),
));
]);
}
$request->attributes->add($parameters);
@@ -157,11 +157,11 @@ class RouterListener implements EventSubscriberInterface
public static function getSubscribedEvents()
{
return array(
KernelEvents::REQUEST => array(array('onKernelRequest', 32)),
KernelEvents::FINISH_REQUEST => array(array('onKernelFinishRequest', 0)),
KernelEvents::EXCEPTION => array('onKernelException', -64),
);
return [
KernelEvents::REQUEST => [['onKernelRequest', 32]],
KernelEvents::FINISH_REQUEST => [['onKernelFinishRequest', 0]],
KernelEvents::EXCEPTION => ['onKernelException', -64],
];
}
private function createWelcomeResponse()

View File

@@ -38,9 +38,9 @@ class SaveSessionListener implements EventSubscriberInterface
public static function getSubscribedEvents()
{
return array(
return [
// low priority but higher than StreamedResponseListener
KernelEvents::RESPONSE => array(array('onKernelResponse', -1000)),
);
KernelEvents::RESPONSE => [['onKernelResponse', -1000]],
];
}
}

View File

@@ -40,9 +40,10 @@ class SessionListener extends AbstractSessionListener
if ($this->container->has('session_storage')
&& ($storage = $this->container->get('session_storage')) instanceof NativeSessionStorage
&& $this->container->get('request_stack')->getMasterRequest()->isSecure()
&& ($masterRequest = $this->container->get('request_stack')->getMasterRequest())
&& $masterRequest->isSecure()
) {
$storage->setOptions(array('cookie_secure' => true));
$storage->setOptions(['cookie_secure' => true]);
}
return $this->container->get('session');

View File

@@ -42,8 +42,8 @@ class StreamedResponseListener implements EventSubscriberInterface
public static function getSubscribedEvents()
{
return array(
KernelEvents::RESPONSE => array('onKernelResponse', -1024),
);
return [
KernelEvents::RESPONSE => ['onKernelResponse', -1024],
];
}
}

View File

@@ -58,8 +58,8 @@ class SurrogateListener implements EventSubscriberInterface
public static function getSubscribedEvents()
{
return array(
return [
KernelEvents::RESPONSE => 'onKernelResponse',
);
];
}
}

View File

@@ -24,7 +24,7 @@ class TestSessionListener extends AbstractTestSessionListener
{
private $container;
public function __construct(ContainerInterface $container, array $sessionOptions = array())
public function __construct(ContainerInterface $container, array $sessionOptions = [])
{
$this->container = $container;
parent::__construct($sessionOptions);

View File

@@ -58,11 +58,11 @@ class TranslatorListener implements EventSubscriberInterface
public static function getSubscribedEvents()
{
return array(
return [
// must be registered after the Locale listener
KernelEvents::REQUEST => array(array('onKernelRequest', 10)),
KernelEvents::FINISH_REQUEST => array(array('onKernelFinishRequest', 0)),
);
KernelEvents::REQUEST => [['onKernelRequest', 10]],
KernelEvents::FINISH_REQUEST => [['onKernelFinishRequest', 0]],
];
}
private function setLocale(Request $request)

View File

@@ -44,10 +44,10 @@ class ValidateRequestListener implements EventSubscriberInterface
*/
public static function getSubscribedEvents()
{
return array(
KernelEvents::REQUEST => array(
array('onKernelRequest', 256),
),
);
return [
KernelEvents::REQUEST => [
['onKernelRequest', 256],
],
];
}
}

View File

@@ -23,7 +23,7 @@ class AccessDeniedHttpException extends HttpException
* @param int $code The internal exception code
* @param array $headers
*/
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = array())
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = [])
{
parent::__construct(403, $message, $previous, $headers, $code);
}

View File

@@ -22,7 +22,7 @@ class BadRequestHttpException extends HttpException
* @param int $code The internal exception code
* @param array $headers
*/
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = array())
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = [])
{
parent::__construct(400, $message, $previous, $headers, $code);
}

View File

@@ -22,7 +22,7 @@ class ConflictHttpException extends HttpException
* @param int $code The internal exception code
* @param array $headers
*/
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = array())
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = [])
{
parent::__construct(409, $message, $previous, $headers, $code);
}

View File

@@ -28,12 +28,12 @@ class ControllerDoesNotReturnResponseException extends \LogicException
$this->line = $controllerDefinition['line'];
$r = new \ReflectionProperty(\Exception::class, 'trace');
$r->setAccessible(true);
$r->setValue($this, array_merge(array(
array(
$r->setValue($this, array_merge([
[
'line' => $line,
'file' => $file,
),
), $this->getTrace()));
],
], $this->getTrace()));
}
private function parseControllerDefinition(callable $controller): ?array
@@ -46,10 +46,10 @@ class ControllerDoesNotReturnResponseException extends \LogicException
try {
$r = new \ReflectionMethod($controller[0], $controller[1]);
return array(
return [
'file' => $r->getFileName(),
'line' => $r->getEndLine(),
);
];
} catch (\ReflectionException $e) {
return null;
}
@@ -58,19 +58,19 @@ class ControllerDoesNotReturnResponseException extends \LogicException
if ($controller instanceof \Closure) {
$r = new \ReflectionFunction($controller);
return array(
return [
'file' => $r->getFileName(),
'line' => $r->getEndLine(),
);
];
}
if (\is_object($controller)) {
$r = new \ReflectionClass($controller);
return array(
return [
'file' => $r->getFileName(),
'line' => $r->getEndLine(),
);
];
}
return null;

View File

@@ -22,7 +22,7 @@ class GoneHttpException extends HttpException
* @param int $code The internal exception code
* @param array $headers
*/
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = array())
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = [])
{
parent::__construct(410, $message, $previous, $headers, $code);
}

View File

@@ -21,7 +21,7 @@ class HttpException extends \RuntimeException implements HttpExceptionInterface
private $statusCode;
private $headers;
public function __construct(int $statusCode, string $message = null, \Exception $previous = null, array $headers = array(), ?int $code = 0)
public function __construct(int $statusCode, string $message = null, \Exception $previous = null, array $headers = [], ?int $code = 0)
{
$this->statusCode = $statusCode;
$this->headers = $headers;

View File

@@ -22,7 +22,7 @@ class LengthRequiredHttpException extends HttpException
* @param int $code The internal exception code
* @param array $headers
*/
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = array())
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = [])
{
parent::__construct(411, $message, $previous, $headers, $code);
}

View File

@@ -23,7 +23,7 @@ class MethodNotAllowedHttpException extends HttpException
* @param int $code The internal exception code
* @param array $headers
*/
public function __construct(array $allow, string $message = null, \Exception $previous = null, ?int $code = 0, array $headers = array())
public function __construct(array $allow, string $message = null, \Exception $previous = null, ?int $code = 0, array $headers = [])
{
$headers['Allow'] = strtoupper(implode(', ', $allow));

View File

@@ -22,7 +22,7 @@ class NotAcceptableHttpException extends HttpException
* @param int $code The internal exception code
* @param array $headers
*/
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = array())
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = [])
{
parent::__construct(406, $message, $previous, $headers, $code);
}

View File

@@ -22,7 +22,7 @@ class NotFoundHttpException extends HttpException
* @param int $code The internal exception code
* @param array $headers
*/
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = array())
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = [])
{
parent::__construct(404, $message, $previous, $headers, $code);
}

View File

@@ -22,7 +22,7 @@ class PreconditionFailedHttpException extends HttpException
* @param int $code The internal exception code
* @param array $headers
*/
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = array())
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = [])
{
parent::__construct(412, $message, $previous, $headers, $code);
}

View File

@@ -24,7 +24,7 @@ class PreconditionRequiredHttpException extends HttpException
* @param int $code The internal exception code
* @param array $headers
*/
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = array())
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = [])
{
parent::__construct(428, $message, $previous, $headers, $code);
}

View File

@@ -23,7 +23,7 @@ class ServiceUnavailableHttpException extends HttpException
* @param int $code The internal exception code
* @param array $headers
*/
public function __construct($retryAfter = null, string $message = null, \Exception $previous = null, ?int $code = 0, array $headers = array())
public function __construct($retryAfter = null, string $message = null, \Exception $previous = null, ?int $code = 0, array $headers = [])
{
if ($retryAfter) {
$headers['Retry-After'] = $retryAfter;

View File

@@ -25,7 +25,7 @@ class TooManyRequestsHttpException extends HttpException
* @param int $code The internal exception code
* @param array $headers
*/
public function __construct($retryAfter = null, string $message = null, \Exception $previous = null, ?int $code = 0, array $headers = array())
public function __construct($retryAfter = null, string $message = null, \Exception $previous = null, ?int $code = 0, array $headers = [])
{
if ($retryAfter) {
$headers['Retry-After'] = $retryAfter;

View File

@@ -23,7 +23,7 @@ class UnauthorizedHttpException extends HttpException
* @param int $code The internal exception code
* @param array $headers
*/
public function __construct(string $challenge, string $message = null, \Exception $previous = null, ?int $code = 0, array $headers = array())
public function __construct(string $challenge, string $message = null, \Exception $previous = null, ?int $code = 0, array $headers = [])
{
$headers['WWW-Authenticate'] = $challenge;

View File

@@ -22,7 +22,7 @@ class UnprocessableEntityHttpException extends HttpException
* @param int $code The internal exception code
* @param array $headers
*/
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = array())
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = [])
{
parent::__construct(422, $message, $previous, $headers, $code);
}

View File

@@ -22,7 +22,7 @@ class UnsupportedMediaTypeHttpException extends HttpException
* @param int $code The internal exception code
* @param array $headers
*/
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = array())
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = [])
{
parent::__construct(415, $message, $previous, $headers, $code);
}

View File

@@ -59,7 +59,7 @@ abstract class AbstractSurrogateFragmentRenderer extends RoutableFragmentRendere
*
* @see Symfony\Component\HttpKernel\HttpCache\SurrogateInterface
*/
public function render($uri, Request $request, array $options = array())
public function render($uri, Request $request, array $options = [])
{
if (!$this->surrogate || !$this->surrogate->hasSurrogateCapability($request)) {
if ($uri instanceof ControllerReference && $this->containsNonScalars($uri->attributes)) {

View File

@@ -29,7 +29,7 @@ use Symfony\Component\HttpKernel\Controller\ControllerReference;
class FragmentHandler
{
private $debug;
private $renderers = array();
private $renderers = [];
private $requestStack;
/**
@@ -37,7 +37,7 @@ class FragmentHandler
* @param FragmentRendererInterface[] $renderers An array of FragmentRendererInterface instances
* @param bool $debug Whether the debug mode is enabled or not
*/
public function __construct(RequestStack $requestStack, array $renderers = array(), bool $debug = false)
public function __construct(RequestStack $requestStack, array $renderers = [], bool $debug = false)
{
$this->requestStack = $requestStack;
foreach ($renderers as $renderer) {
@@ -70,7 +70,7 @@ class FragmentHandler
* @throws \InvalidArgumentException when the renderer does not exist
* @throws \LogicException when no master request is being handled
*/
public function render($uri, $renderer = 'inline', array $options = array())
public function render($uri, $renderer = 'inline', array $options = [])
{
if (!isset($options['ignore_errors'])) {
$options['ignore_errors'] = !$this->debug;

View File

@@ -31,7 +31,7 @@ interface FragmentRendererInterface
*
* @return Response A Response instance
*/
public function render($uri, Request $request, array $options = array());
public function render($uri, Request $request, array $options = []);
/**
* Gets the name of the strategy.

View File

@@ -81,7 +81,7 @@ class HIncludeFragmentRenderer extends RoutableFragmentRenderer
* * id: An optional hx:include tag id attribute
* * attributes: An optional array of hx:include tag attributes
*/
public function render($uri, Request $request, array $options = array())
public function render($uri, Request $request, array $options = [])
{
if ($uri instanceof ControllerReference) {
if (null === $this->signer) {
@@ -102,7 +102,7 @@ class HIncludeFragmentRenderer extends RoutableFragmentRenderer
$content = $template;
}
$attributes = isset($options['attributes']) && \is_array($options['attributes']) ? $options['attributes'] : array();
$attributes = isset($options['attributes']) && \is_array($options['attributes']) ? $options['attributes'] : [];
if (isset($options['id']) && $options['id']) {
$attributes['id'] = $options['id'];
}

View File

@@ -43,7 +43,7 @@ class InlineFragmentRenderer extends RoutableFragmentRenderer
*
* * alt: an alternative URI to render in case of an error
*/
public function render($uri, Request $request, array $options = array())
public function render($uri, Request $request, array $options = [])
{
$reference = null;
if ($uri instanceof ControllerReference) {
@@ -54,10 +54,10 @@ class InlineFragmentRenderer extends RoutableFragmentRenderer
// want that as we want to preserve objects (so we manually set Request attributes
// below instead)
$attributes = $reference->attributes;
$reference->attributes = array();
$reference->attributes = [];
// The request format and locale might have been overridden by the user
foreach (array('_format', '_locale') as $key) {
foreach (['_format', '_locale'] as $key) {
if (isset($attributes[$key])) {
$reference->attributes[$key] = $attributes[$key];
}
@@ -80,7 +80,7 @@ class InlineFragmentRenderer extends RoutableFragmentRenderer
return SubRequestHandler::handle($this->kernel, $subRequest, HttpKernelInterface::SUB_REQUEST, false);
} catch (\Exception $e) {
// we dispatch the exception event to trigger the logging
// the response that comes back is simply ignored
// the response that comes back is ignored
if (isset($options['ignore_errors']) && $options['ignore_errors'] && $this->dispatcher) {
$event = new GetResponseForExceptionEvent($this->kernel, $request, HttpKernelInterface::SUB_REQUEST, $e);
@@ -113,7 +113,7 @@ class InlineFragmentRenderer extends RoutableFragmentRenderer
unset($server['HTTP_IF_MODIFIED_SINCE']);
unset($server['HTTP_IF_NONE_MATCH']);
$subRequest = Request::create($uri, 'get', array(), $cookies, array(), $server);
$subRequest = Request::create($uri, 'get', [], $cookies, [], $server);
if ($request->headers->has('Surrogate-Capability')) {
$subRequest->headers->set('Surrogate-Capability', $request->headers->get('Surrogate-Capability'));
}

View File

@@ -24,16 +24,16 @@ use Symfony\Component\HttpKernel\HttpKernelInterface;
abstract class AbstractSurrogate implements SurrogateInterface
{
protected $contentTypes;
protected $phpEscapeMap = array(
array('<?', '<%', '<s', '<S'),
array('<?php echo "<?"; ?>', '<?php echo "<%"; ?>', '<?php echo "<s"; ?>', '<?php echo "<S"; ?>'),
);
protected $phpEscapeMap = [
['<?', '<%', '<s', '<S'],
['<?php echo "<?"; ?>', '<?php echo "<%"; ?>', '<?php echo "<s"; ?>', '<?php echo "<S"; ?>'],
];
/**
* @param array $contentTypes An array of content-type that should be parsed for Surrogate information
* (default: text/html, text/xml, application/xhtml+xml, and application/xml)
*/
public function __construct(array $contentTypes = array('text/html', 'text/xml', 'application/xhtml+xml', 'application/xml'))
public function __construct(array $contentTypes = ['text/html', 'text/xml', 'application/xhtml+xml', 'application/xml'])
{
$this->contentTypes = $contentTypes;
}
@@ -90,7 +90,7 @@ abstract class AbstractSurrogate implements SurrogateInterface
*/
public function handle(HttpCache $cache, $uri, $alt, $ignoreErrors)
{
$subRequest = Request::create($uri, Request::METHOD_GET, array(), $cache->getRequest()->cookies->all(), array(), $cache->getRequest()->server->all());
$subRequest = Request::create($uri, Request::METHOD_GET, [], $cache->getRequest()->cookies->all(), [], $cache->getRequest()->server->all());
try {
$response = $cache->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true);

View File

@@ -85,7 +85,7 @@ class Esi extends AbstractSurrogate
$i = 1;
while (isset($chunks[$i])) {
$options = array();
$options = [];
preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER);
foreach ($matches as $set) {
$options[$set[1]] = $set[2];

View File

@@ -32,8 +32,8 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
private $request;
private $surrogate;
private $surrogateCacheStrategy;
private $options = array();
private $traces = array();
private $options = [];
private $traces = [];
/**
* Constructor.
@@ -70,24 +70,24 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
* This setting is overridden by the stale-if-error HTTP Cache-Control extension
* (see RFC 5861).
*/
public function __construct(HttpKernelInterface $kernel, StoreInterface $store, SurrogateInterface $surrogate = null, array $options = array())
public function __construct(HttpKernelInterface $kernel, StoreInterface $store, SurrogateInterface $surrogate = null, array $options = [])
{
$this->store = $store;
$this->kernel = $kernel;
$this->surrogate = $surrogate;
// needed in case there is a fatal error because the backend is too slow to respond
register_shutdown_function(array($this->store, 'cleanup'));
register_shutdown_function([$this->store, 'cleanup']);
$this->options = array_merge(array(
$this->options = array_merge([
'debug' => false,
'default_ttl' => 0,
'private_headers' => array('Authorization', 'Cookie'),
'private_headers' => ['Authorization', 'Cookie'],
'allow_reload' => false,
'allow_revalidate' => false,
'stale_while_revalidate' => 2,
'stale_if_error' => 60,
), $options);
], $options);
}
/**
@@ -117,7 +117,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
*/
public function getLog()
{
$log = array();
$log = [];
foreach ($this->traces as $request => $traces) {
$log[] = sprintf('%s: %s', $request, implode(', ', $traces));
}
@@ -164,7 +164,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
{
// FIXME: catch exceptions and implement a 500 error page here? -> in Varnish, there is a built-in error page mechanism
if (HttpKernelInterface::MASTER_REQUEST === $type) {
$this->traces = array();
$this->traces = [];
// Keep a clone of the original request for surrogates so they can access it.
// We must clone here to get a separate instance because the application will modify the request during
// the application flow (we know it always does because we do ourselves by setting REMOTE_ADDR to 127.0.0.1
@@ -175,7 +175,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
}
}
$this->traces[$this->getTraceKey($request)] = array();
$this->traces[$this->getTraceKey($request)] = [];
if (!$request->isMethodSafe(false)) {
$response = $this->invalidate($request, $catch);
@@ -260,9 +260,9 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
$this->store->invalidate($request);
// As per the RFC, invalidate Location and Content-Location URLs if present
foreach (array('Location', 'Content-Location') as $header) {
foreach (['Location', 'Content-Location'] as $header) {
if ($uri = $response->headers->get($header)) {
$subRequest = Request::create($uri, 'get', array(), array(), array(), $request->server->all());
$subRequest = Request::create($uri, 'get', [], [], [], $request->server->all());
$this->store->invalidate($subRequest);
}
@@ -357,7 +357,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
// Add our cached etag validator to the environment.
// We keep the etags from the client to handle the case when the client
// has a different private valid entry which is not cached here.
$cachedEtags = $entry->getEtag() ? array($entry->getEtag()) : array();
$cachedEtags = $entry->getEtag() ? [$entry->getEtag()] : [];
$requestEtags = $request->getETags();
if ($etags = array_unique(array_merge($cachedEtags, $requestEtags))) {
$subRequest->headers->set('if_none_match', implode(', ', $etags));
@@ -377,7 +377,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
$entry = clone $entry;
$entry->headers->remove('Date');
foreach (array('Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified') as $name) {
foreach (['Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified'] as $name) {
if ($response->headers->has($name)) {
$entry->headers->set($name, $response->headers->get($name));
}
@@ -448,7 +448,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
$response = SubRequestHandler::handle($this->kernel, $request, HttpKernelInterface::MASTER_REQUEST, $catch);
// we don't implement the stale-if-error on Requests, which is nonetheless part of the RFC
if (null !== $entry && \in_array($response->getStatusCode(), array(500, 502, 503, 504))) {
if (null !== $entry && \in_array($response->getStatusCode(), [500, 502, 503, 504])) {
if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) {
$age = $this->options['stale_if_error'];
}

View File

@@ -5,10 +5,6 @@
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This code is partially based on the Rack-Cache library by Ryan Tomayko,
* which is released under the MIT license.
* (based on commit 02d2b48d75bcb63cf1c0c7149c077ad256542801)
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
@@ -28,30 +24,69 @@ use Symfony\Component\HttpFoundation\Response;
*/
class ResponseCacheStrategy implements ResponseCacheStrategyInterface
{
private $cacheable = true;
/**
* Cache-Control headers that are sent to the final response if they appear in ANY of the responses.
*/
private static $overrideDirectives = ['private', 'no-cache', 'no-store', 'no-transform', 'must-revalidate', 'proxy-revalidate'];
/**
* Cache-Control headers that are sent to the final response if they appear in ALL of the responses.
*/
private static $inheritDirectives = ['public', 'immutable'];
private $embeddedResponses = 0;
private $ttls = array();
private $maxAges = array();
private $isNotCacheableResponseEmbedded = false;
private $age = 0;
private $flagDirectives = [
'no-cache' => null,
'no-store' => null,
'no-transform' => null,
'must-revalidate' => null,
'proxy-revalidate' => null,
'public' => null,
'private' => null,
'immutable' => null,
];
private $ageDirectives = [
'max-age' => null,
's-maxage' => null,
'expires' => null,
];
/**
* {@inheritdoc}
*/
public function add(Response $response)
{
if (!$response->isFresh() || !$response->isCacheable()) {
$this->cacheable = false;
} else {
$maxAge = $response->getMaxAge();
$this->ttls[] = $response->getTtl();
$this->maxAges[] = $maxAge;
++$this->embeddedResponses;
if (null === $maxAge) {
$this->isNotCacheableResponseEmbedded = true;
foreach (self::$overrideDirectives as $directive) {
if ($response->headers->hasCacheControlDirective($directive)) {
$this->flagDirectives[$directive] = true;
}
}
++$this->embeddedResponses;
foreach (self::$inheritDirectives as $directive) {
if (false !== $this->flagDirectives[$directive]) {
$this->flagDirectives[$directive] = $response->headers->hasCacheControlDirective($directive);
}
}
$age = $response->getAge();
$this->age = max($this->age, $age);
if ($this->willMakeFinalResponseUncacheable($response)) {
$this->isNotCacheableResponseEmbedded = true;
return;
}
$this->storeRelativeAgeDirective('max-age', $response->headers->getCacheControlDirective('max-age'), $age);
$this->storeRelativeAgeDirective('s-maxage', $response->headers->getCacheControlDirective('s-maxage') ?: $response->headers->getCacheControlDirective('max-age'), $age);
$expires = $response->getExpires();
$expires = null !== $expires ? $expires->format('U') - $response->getDate()->format('U') : null;
$this->storeRelativeAgeDirective('expires', $expires >= 0 ? $expires : null, 0);
}
/**
@@ -64,33 +99,124 @@ class ResponseCacheStrategy implements ResponseCacheStrategyInterface
return;
}
// Remove validation related headers in order to avoid browsers using
// their own cache, because some of the response content comes from
// at least one embedded response (which likely has a different caching strategy).
if ($response->isValidateable()) {
$response->setEtag(null);
$response->setLastModified(null);
}
// Remove validation related headers of the master response,
// because some of the response content comes from at least
// one embedded response (which likely has a different caching strategy).
$response->setEtag(null);
$response->setLastModified(null);
if (!$response->isFresh() || !$response->isCacheable()) {
$this->cacheable = false;
}
$this->add($response);
if (!$this->cacheable) {
$response->headers->set('Cache-Control', 'no-cache, must-revalidate');
$response->headers->set('Age', $this->age);
if ($this->isNotCacheableResponseEmbedded) {
$response->setExpires($response->getDate());
if ($this->flagDirectives['no-store']) {
$response->headers->set('Cache-Control', 'no-cache, no-store, must-revalidate');
} else {
$response->headers->set('Cache-Control', 'no-cache, must-revalidate');
}
return;
}
$this->ttls[] = $response->getTtl();
$this->maxAges[] = $response->getMaxAge();
$flags = array_filter($this->flagDirectives);
if ($this->isNotCacheableResponseEmbedded) {
$response->headers->removeCacheControlDirective('s-maxage');
} elseif (null !== $maxAge = min($this->maxAges)) {
$response->setSharedMaxAge($maxAge);
$response->headers->set('Age', $maxAge - min($this->ttls));
if (isset($flags['must-revalidate'])) {
$flags['no-cache'] = true;
}
$response->headers->set('Cache-Control', implode(', ', array_keys($flags)));
$maxAge = null;
$sMaxage = null;
if (\is_numeric($this->ageDirectives['max-age'])) {
$maxAge = $this->ageDirectives['max-age'] + $this->age;
$response->headers->addCacheControlDirective('max-age', $maxAge);
}
if (\is_numeric($this->ageDirectives['s-maxage'])) {
$sMaxage = $this->ageDirectives['s-maxage'] + $this->age;
if ($maxAge !== $sMaxage) {
$response->headers->addCacheControlDirective('s-maxage', $sMaxage);
}
}
if (\is_numeric($this->ageDirectives['expires'])) {
$date = clone $response->getDate();
$date->modify('+'.($this->ageDirectives['expires'] + $this->age).' seconds');
$response->setExpires($date);
}
}
/**
* RFC2616, Section 13.4.
*
* @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4
*
* @return bool
*/
private function willMakeFinalResponseUncacheable(Response $response)
{
// RFC2616: A response received with a status code of 200, 203, 300, 301 or 410
// MAY be stored by a cache […] unless a cache-control directive prohibits caching.
if ($response->headers->hasCacheControlDirective('no-cache')
|| $response->headers->getCacheControlDirective('no-store')
) {
return true;
}
// Last-Modified and Etag headers cannot be merged, they render the response uncacheable
// by default (except if the response also has max-age etc.).
if (\in_array($response->getStatusCode(), [200, 203, 300, 301, 410])
&& null === $response->getLastModified()
&& null === $response->getEtag()
) {
return false;
}
// RFC2616: A response received with any other status code (e.g. status codes 302 and 307)
// MUST NOT be returned in a reply to a subsequent request unless there are
// cache-control directives or another header(s) that explicitly allow it.
$cacheControl = ['max-age', 's-maxage', 'must-revalidate', 'proxy-revalidate', 'public', 'private'];
foreach ($cacheControl as $key) {
if ($response->headers->hasCacheControlDirective($key)) {
return false;
}
}
if ($response->headers->has('Expires')) {
return false;
}
return true;
}
/**
* Store lowest max-age/s-maxage/expires for the final response.
*
* The response might have been stored in cache a while ago. To keep things comparable,
* we have to subtract the age so that the value is normalized for an age of 0.
*
* If the value is lower than the currently stored value, we update the value, to keep a rolling
* minimal value of each instruction. If the value is NULL, the directive will not be set on the final response.
*
* @param string $directive
* @param int|null $value
* @param int $age
*/
private function storeRelativeAgeDirective($directive, $value, $age)
{
if (null === $value) {
$this->ageDirectives[$directive] = false;
}
if (false !== $this->ageDirectives[$directive]) {
$value -= $age;
$this->ageDirectives[$directive] = null !== $this->ageDirectives[$directive] ? min($this->ageDirectives[$directive], $value) : $value;
}
$response->setMaxAge(0);
}
}

View File

@@ -70,7 +70,7 @@ class Ssi extends AbstractSurrogate
$i = 1;
while (isset($chunks[$i])) {
$options = array();
$options = [];
preg_match_all('/(virtual)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER);
foreach ($matches as $set) {
$options[$set[1]] = $set[2];

View File

@@ -38,7 +38,7 @@ class Store implements StoreInterface
throw new \RuntimeException(sprintf('Unable to create the store directory (%s).', $this->root));
}
$this->keyCache = new \SplObjectStorage();
$this->locks = array();
$this->locks = [];
}
/**
@@ -52,7 +52,7 @@ class Store implements StoreInterface
fclose($lock);
}
$this->locks = array();
$this->locks = [];
}
/**
@@ -190,11 +190,11 @@ class Store implements StoreInterface
}
// read existing cache entries, remove non-varying, and add this one to the list
$entries = array();
$entries = [];
$vary = $response->headers->get('vary');
foreach ($this->getMetadata($key) as $entry) {
if (!isset($entry[1]['vary'][0])) {
$entry[1]['vary'] = array('');
$entry[1]['vary'] = [''];
}
if ($entry[1]['vary'][0] != $vary || !$this->requestsMatch($vary, $entry[0], $storedEnv)) {
@@ -205,7 +205,7 @@ class Store implements StoreInterface
$headers = $this->persistResponse($response);
unset($headers['age']);
array_unshift($entries, array($storedEnv, $headers));
array_unshift($entries, [$storedEnv, $headers]);
if (false === $this->save($key, serialize($entries))) {
throw new \RuntimeException('Unable to store the metadata.');
@@ -234,13 +234,13 @@ class Store implements StoreInterface
$modified = false;
$key = $this->getCacheKey($request);
$entries = array();
$entries = [];
foreach ($this->getMetadata($key) as $entry) {
$response = $this->restoreResponse($entry[1]);
if ($response->isFresh()) {
$response->expire();
$modified = true;
$entries[] = array($entry[0], $this->persistResponse($response));
$entries[] = [$entry[0], $this->persistResponse($response)];
} else {
$entries[] = $entry;
}
@@ -291,7 +291,7 @@ class Store implements StoreInterface
private function getMetadata($key)
{
if (!$entries = $this->load($key)) {
return array();
return [];
}
return unserialize($entries);
@@ -462,7 +462,7 @@ class Store implements StoreInterface
private function persistResponse(Response $response)
{
$headers = $response->headers->all();
$headers['X-Status'] = array($response->getStatusCode());
$headers['X-Status'] = [$response->getStatusCode()];
return $headers;
}
@@ -481,7 +481,7 @@ class Store implements StoreInterface
unset($headers['X-Status']);
if (null !== $body) {
$headers['X-Body-File'] = array($body);
$headers['X-Body-File'] = [$body];
}
return new Response($body, $status, $headers);

View File

@@ -32,13 +32,13 @@ class SubRequestHandler
// remove untrusted values
$remoteAddr = $request->server->get('REMOTE_ADDR');
if (!IpUtils::checkIp($remoteAddr, $trustedProxies)) {
$trustedHeaders = array(
$trustedHeaders = [
'FORWARDED' => $trustedHeaderSet & Request::HEADER_FORWARDED,
'X_FORWARDED_FOR' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_FOR,
'X_FORWARDED_HOST' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_HOST,
'X_FORWARDED_PROTO' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_PROTO,
'X_FORWARDED_PORT' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_PORT,
);
];
foreach (array_filter($trustedHeaders) as $name => $key) {
$request->headers->remove($name);
$request->server->remove('HTTP_'.$name);
@@ -46,8 +46,8 @@ class SubRequestHandler
}
// compute trusted values, taking any trusted proxies into account
$trustedIps = array();
$trustedValues = array();
$trustedIps = [];
$trustedValues = [];
foreach (array_reverse($request->getClientIps()) as $ip) {
$trustedIps[] = $ip;
$trustedValues[] = sprintf('for="%s"', $ip);
@@ -78,7 +78,7 @@ class SubRequestHandler
// ensure 127.0.0.1 is set as trusted proxy
if (!IpUtils::checkIp('127.0.0.1', $trustedProxies)) {
Request::setTrustedProxies(array_merge($trustedProxies, array('127.0.0.1')), Request::getTrustedHeaderSet());
Request::setTrustedProxies(array_merge($trustedProxies, ['127.0.0.1']), Request::getTrustedHeaderSet());
}
try {

View File

@@ -260,7 +260,7 @@ class HttpKernel implements HttpKernelInterface, TerminableInterface
}
if (\is_array($var)) {
$a = array();
$a = [];
foreach ($var as $k => $v) {
$a[] = sprintf('%s => ...', $k);
}

View File

@@ -52,7 +52,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
/**
* @var BundleInterface[]
*/
protected $bundles = array();
protected $bundles = [];
protected $container;
/**
@@ -73,11 +73,11 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
private $requestStackSize = 0;
private $resetServices = false;
const VERSION = '4.2.2';
const VERSION_ID = 40202;
const VERSION = '4.2.8';
const VERSION_ID = 40208;
const MAJOR_VERSION = 4;
const MINOR_VERSION = 2;
const RELEASE_VERSION = 2;
const RELEASE_VERSION = 8;
const EXTRA_VERSION = '';
const END_OF_MAINTENANCE = '07/2019';
@@ -258,7 +258,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
$isResource = 0 === strpos($path, 'Resources') && null !== $dir;
$overridePath = substr($path, 9);
$bundle = $this->getBundle($bundleName);
$files = array();
$files = [];
if ($isResource && file_exists($file = $dir.'/'.$bundle->getName().$overridePath)) {
$files[] = $file;
@@ -409,7 +409,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
*/
public function getAnnotatedClassesToCompile(): array
{
return array();
return [];
}
/**
@@ -420,7 +420,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
protected function initializeBundles()
{
// init bundles
$this->bundles = array();
$this->bundles = [];
foreach ($this->registerBundles() as $bundle) {
$name = $bundle->getName();
if (isset($this->bundles[$name])) {
@@ -447,7 +447,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
protected function getContainerClass()
{
$class = \get_class($this);
$class = 'c' === $class[0] && 0 === strpos($class, "class@anonymous\0") ? get_parent_class($class).ContainerBuilder::hash($class) : $class;
$class = 'c' === $class[0] && 0 === strpos($class, "class@anonymous\0") ? get_parent_class($class).str_replace('.', '_', ContainerBuilder::hash($class)) : $class;
return $this->name.str_replace('\\', '_', $class).ucfirst($this->environment).($this->debug ? 'Debug' : '').'Container';
}
@@ -498,7 +498,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
}
if ($this->debug) {
$collectedLogs = array();
$collectedLogs = [];
$previousHandler = \defined('PHPUNIT_COMPOSER_INSTALL');
$previousHandler = $previousHandler ?: set_error_handler(function ($type, $message, $file, $line) use (&$collectedLogs, &$previousHandler) {
if (E_USER_DEPRECATED !== $type && E_DEPRECATED !== $type) {
@@ -522,19 +522,19 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
// Remove frames added by DebugClassLoader.
for ($i = \count($backtrace) - 2; 0 < $i; --$i) {
if (DebugClassLoader::class === ($backtrace[$i]['class'] ?? null)) {
$backtrace = array($backtrace[$i + 1]);
$backtrace = [$backtrace[$i + 1]];
break;
}
}
$collectedLogs[$message] = array(
$collectedLogs[$message] = [
'type' => $type,
'message' => $message,
'file' => $file,
'line' => $line,
'trace' => array($backtrace[0]),
'trace' => [$backtrace[0]],
'count' => 1,
);
];
});
}
@@ -571,7 +571,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
// Because concurrent requests might still be using them,
// old container files are not removed immediately,
// but on a next dump of the container.
static $legacyContainers = array();
static $legacyContainers = [];
$oldContainerDir = \dirname($oldContainer->getFileName());
$legacyContainers[$oldContainerDir.'.legacy'] = true;
foreach (glob(\dirname($oldContainerDir).\DIRECTORY_SEPARATOR.'*.legacy') as $legacyContainer) {
@@ -595,18 +595,18 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
*/
protected function getKernelParameters()
{
$bundles = array();
$bundlesMetadata = array();
$bundles = [];
$bundlesMetadata = [];
foreach ($this->bundles as $name => $bundle) {
$bundles[$name] = \get_class($bundle);
$bundlesMetadata[$name] = array(
$bundlesMetadata[$name] = [
'path' => $bundle->getPath(),
'namespace' => $bundle->getNamespace(),
);
];
}
return array(
return [
/*
* @deprecated since Symfony 4.2, use kernel.project_dir instead
*/
@@ -624,7 +624,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
'kernel.bundles_metadata' => $bundlesMetadata,
'kernel.charset' => $this->getCharset(),
'kernel.container_class' => $this->getContainerClass(),
);
];
}
/**
@@ -636,7 +636,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
*/
protected function buildContainer()
{
foreach (array('cache' => $this->warmupDir ?: $this->getCacheDir(), 'logs' => $this->getLogDir()) as $name => $dir) {
foreach (['cache' => $this->warmupDir ?: $this->getCacheDir(), 'logs' => $this->getLogDir()] as $name => $dir) {
if (!is_dir($dir)) {
if (false === @mkdir($dir, 0777, true) && !is_dir($dir)) {
throw new \RuntimeException(sprintf("Unable to create the %s directory (%s)\n", $name, $dir));
@@ -664,7 +664,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
*/
protected function prepareContainer(ContainerBuilder $container)
{
$extensions = array();
$extensions = [];
foreach ($this->bundles as $bundle) {
if ($extension = $bundle->getContainerExtension()) {
$container->registerExtension($extension);
@@ -726,14 +726,14 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
$dumper->setProxyDumper(new ProxyDumper());
}
$content = $dumper->dump(array(
$content = $dumper->dump([
'class' => $class,
'base_class' => $baseClass,
'file' => $cache->getPath(),
'as_files' => true,
'debug' => $this->debug,
'build_time' => $container->hasParameter('kernel.container_build_time') ? $container->getParameter('kernel.container_build_time') : time(),
));
]);
$rootCode = array_pop($content);
$dir = \dirname($cache->getPath()).'/';
@@ -759,7 +759,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
protected function getContainerLoader(ContainerInterface $container)
{
$locator = new FileLocator($this);
$resolver = new LoaderResolver(array(
$resolver = new LoaderResolver([
new XmlFileLoader($container, $locator),
new YamlFileLoader($container, $locator),
new IniFileLoader($container, $locator),
@@ -767,7 +767,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
new GlobFileLoader($container, $locator),
new DirectoryLoader($container, $locator),
new ClosureLoader($container),
));
]);
return new DelegatingLoader($resolver);
}
@@ -811,8 +811,8 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
}
// replace multiple new lines with a single newline
$rawChunk .= preg_replace(array('/\n{2,}/S'), "\n", $token[1]);
} elseif (\in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
$rawChunk .= preg_replace(['/\n{2,}/S'], "\n", $token[1]);
} elseif (\in_array($token[0], [T_COMMENT, T_DOC_COMMENT])) {
$ignoreSpace = true;
} else {
$rawChunk .= $token[1];
@@ -835,12 +835,12 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
public function serialize()
{
return serialize(array($this->environment, $this->debug));
return serialize([$this->environment, $this->debug]);
}
public function unserialize($data)
{
list($environment, $debug) = unserialize($data, array('allowed_classes' => false));
list($environment, $debug) = unserialize($data, ['allowed_classes' => false]);
$this->__construct($environment, $debug);
}

View File

@@ -22,7 +22,7 @@ use Psr\Log\LogLevel;
*/
class Logger extends AbstractLogger
{
private static $levels = array(
private static $levels = [
LogLevel::DEBUG => 0,
LogLevel::INFO => 1,
LogLevel::NOTICE => 2,
@@ -31,7 +31,7 @@ class Logger extends AbstractLogger
LogLevel::CRITICAL => 5,
LogLevel::ALERT => 6,
LogLevel::EMERGENCY => 7,
);
];
private $minLevelIndex;
private $formatter;
@@ -40,7 +40,7 @@ class Logger extends AbstractLogger
public function __construct(string $minLevel = null, $output = 'php://stderr', callable $formatter = null)
{
if (null === $minLevel) {
$minLevel = LogLevel::WARNING;
$minLevel = 'php://stdout' === $output || 'php://stderr' === $output ? LogLevel::CRITICAL : LogLevel::WARNING;
if (isset($_ENV['SHELL_VERBOSITY']) || isset($_SERVER['SHELL_VERBOSITY'])) {
switch ((int) (isset($_ENV['SHELL_VERBOSITY']) ? $_ENV['SHELL_VERBOSITY'] : $_SERVER['SHELL_VERBOSITY'])) {
@@ -57,7 +57,7 @@ class Logger extends AbstractLogger
}
$this->minLevelIndex = self::$levels[$minLevel];
$this->formatter = $formatter ?: array($this, 'format');
$this->formatter = $formatter ?: [$this, 'format'];
if (false === $this->handle = \is_resource($output) ? $output : @fopen($output, 'a')) {
throw new InvalidArgumentException(sprintf('Unable to open "%s".', $output));
}
@@ -66,7 +66,7 @@ class Logger extends AbstractLogger
/**
* {@inheritdoc}
*/
public function log($level, $message, array $context = array())
public function log($level, $message, array $context = [])
{
if (!isset(self::$levels[$level])) {
throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $level));
@@ -83,7 +83,7 @@ class Logger extends AbstractLogger
private function format(string $level, string $message, array $context): string
{
if (false !== strpos($message, '{')) {
$replacements = array();
$replacements = [];
foreach ($context as $key => $val) {
if (null === $val || is_scalar($val) || (\is_object($val) && method_exists($val, '__toString'))) {
$replacements["{{$key}}"] = $val;

View File

@@ -52,13 +52,13 @@ class FileProfilerStorage implements ProfilerStorageInterface
$file = $this->getIndexFilename();
if (!file_exists($file)) {
return array();
return [];
}
$file = fopen($file, 'r');
fseek($file, 0, SEEK_END);
$result = array();
$result = [];
while (\count($result) < $limit && $line = $this->readLineFromFile($file)) {
$values = str_getcsv($line);
list($csvToken, $csvIp, $csvMethod, $csvUrl, $csvTime, $csvParent, $csvStatusCode) = $values;
@@ -76,7 +76,7 @@ class FileProfilerStorage implements ProfilerStorageInterface
continue;
}
$result[$csvToken] = array(
$result[$csvToken] = [
'token' => $csvToken,
'ip' => $csvIp,
'method' => $csvMethod,
@@ -84,7 +84,7 @@ class FileProfilerStorage implements ProfilerStorageInterface
'time' => $csvTime,
'parent' => $csvParent,
'status_code' => $csvStatusCode,
);
];
}
fclose($file);
@@ -149,7 +149,7 @@ class FileProfilerStorage implements ProfilerStorageInterface
}, $profile->getChildren()));
// Store profile
$data = array(
$data = [
'token' => $profileToken,
'parent' => $parentToken,
'children' => $childrenToken,
@@ -159,7 +159,7 @@ class FileProfilerStorage implements ProfilerStorageInterface
'url' => $profile->getUrl(),
'time' => $profile->getTime(),
'status_code' => $profile->getStatusCode(),
);
];
if (false === file_put_contents($file, serialize($data))) {
return false;
@@ -171,7 +171,7 @@ class FileProfilerStorage implements ProfilerStorageInterface
return false;
}
fputcsv($file, array(
fputcsv($file, [
$profile->getToken(),
$profile->getIp(),
$profile->getMethod(),
@@ -179,7 +179,7 @@ class FileProfilerStorage implements ProfilerStorageInterface
$profile->getTime(),
$profile->getParentToken(),
$profile->getStatusCode(),
));
]);
fclose($file);
}

View File

@@ -25,7 +25,7 @@ class Profile
/**
* @var DataCollectorInterface[]
*/
private $collectors = array();
private $collectors = [];
private $ip;
private $method;
@@ -41,7 +41,7 @@ class Profile
/**
* @var Profile[]
*/
private $children = array();
private $children = [];
public function __construct(string $token)
{
@@ -201,7 +201,7 @@ class Profile
*/
public function setChildren(array $children)
{
$this->children = array();
$this->children = [];
foreach ($children as $child) {
$this->addChild($child);
}
@@ -262,7 +262,7 @@ class Profile
*/
public function setCollectors(array $collectors)
{
$this->collectors = array();
$this->collectors = [];
foreach ($collectors as $collector) {
$this->addCollector($collector);
}
@@ -290,6 +290,6 @@ class Profile
public function __sleep()
{
return array('token', 'parent', 'children', 'collectors', 'ip', 'method', 'url', 'time', 'statusCode');
return ['token', 'parent', 'children', 'collectors', 'ip', 'method', 'url', 'time', 'statusCode'];
}
}

View File

@@ -31,7 +31,7 @@ class Profiler implements ResetInterface
/**
* @var DataCollectorInterface[]
*/
private $collectors = array();
private $collectors = [];
private $logger;
private $initiallyEnabled = true;
@@ -101,7 +101,7 @@ class Profiler implements ResetInterface
}
if (!($ret = $this->storage->write($profile)) && null !== $this->logger) {
$this->logger->warning('Unable to store the profiler information.', array('configured_storage' => \get_class($this->storage)));
$this->logger->warning('Unable to store the profiler information.', ['configured_storage' => \get_class($this->storage)]);
}
return $ret;
@@ -196,9 +196,9 @@ class Profiler implements ResetInterface
*
* @param DataCollectorInterface[] $collectors An array of collectors
*/
public function set(array $collectors = array())
public function set(array $collectors = [])
{
$this->collectors = array();
$this->collectors = [];
foreach ($collectors as $collector) {
$this->add($collector);
}

View File

@@ -51,21 +51,7 @@
<div id="next">
<h2>What's next?</h2>
<p>
<svg id="icon-book" version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="-12.5 9 64 64" enable-background="new -12.5 9 64 64" xml:space="preserve">
<path fill="#AAA" d="M6.8,40.8c2.4,0.8,4.5-0.7,4.9-2.5c0.2-1.2-0.3-2.1-1.3-3.2l-0.8-0.8c-0.4-0.5-0.6-1.3-0.2-1.9
c0.4-0.5,0.9-0.8,1.8-0.5c1.3,0.4,1.9,1.3,2.9,2.2c-0.4,1.4-0.7,2.9-0.9,4.2l-0.2,1c-0.7,4-1.3,6.2-2.7,7.5
c-0.3,0.3-0.7,0.5-1.3,0.6c-0.3,0-0.4-0.3-0.4-0.3c0-0.3,0.2-0.3,0.3-0.4c0.2-0.1,0.5-0.3,0.4-0.8c0-0.7-0.6-1.3-1.3-1.3
c-0.6,0-1.4,0.6-1.4,1.7s1,1.9,2.4,1.8c0.8,0,2.5-0.3,4.2-2.5c2-2.5,2.5-5.4,2.9-7.4l0.5-2.8c0.3,0,0.5,0.1,0.8,0.1
c2.4,0.1,3.7-1.3,3.7-2.3c0-0.6-0.3-1.2-0.9-1.2c-0.4,0-0.8,0.3-1,0.8c-0.1,0.6,0.8,1.1,0.1,1.5c-0.5,0.3-1.4,0.6-2.7,0.4l0.3-1.3
c0.5-2.6,1-5.7,3.2-5.8c0.2,0,0.8,0,0.8,0.4c0,0.2,0,0.2-0.2,0.5c-0.2,0.3-0.3,0.4-0.2,0.7c0,0.7,0.5,1.1,1.2,1.1
c0.9,0,1.2-1,1.2-1.4c0-1.2-1.2-1.8-2.6-1.8c-1.5,0.1-2.8,0.9-3.7,2.1c-1.1,1.3-1.8,2.9-2.3,4.5c-0.9-0.8-1.6-1.8-3.1-2.3
c-1.1-0.7-2.3-0.5-3.4,0.3c-0.5,0.4-0.8,1-1,1.6c-0.4,1.5,0.4,2.9,0.8,3.4l0.9,1c0.2,0.2,0.6,0.8,0.4,1.5c-0.3,0.8-1.2,1.3-2.1,1
c-0.4-0.2-1-0.5-0.9-0.9c0.1-0.2,0.2-0.3,0.3-0.5s0.1-0.3,0.1-0.3c0.2-0.6-0.1-1.4-0.7-1.6c-0.6-0.2-1.2,0-1.3,0.8
C4.3,38.4,4.7,40,6.8,40.8z M46.1,20.9c0-4.2-3.2-7.5-7.1-7.5h-3.8C34.8,10.8,32.7,9,30.2,9L-2.3,9.1c-2.8,0.1-4.9,2.4-4.9,5.4
L-7,58.6c0,4.8,8.1,13.9,11.6,14.1l34.7-0.1c3.9,0,7-3.4,7-7.6L46.1,20.9z M-0.3,36.4c0-8.6,6.5-15.6,14.5-15.6
c8,0,14.5,7,14.5,15.6S22.1,52,14.2,52C6.1,52-0.3,45-0.3,36.4z M42.1,65.1c0,1.8-1.5,3.1-3.1,3.1H4.6c-0.7,0-3-1.8-4.5-4.4h30.4
c2.8,0,5-2.4,5-5.4V17.9h3.7c1.6,0,2.9,1.4,2.9,3.1V65.1L42.1,65.1z"/>
</svg>
<svg id="icon-book" xmlns="http://www.w3.org/2000/svg" viewBox="-12.5 9 64 64"><path fill="#AAA" d="M6.8 40.8c2.4.8 4.5-.7 4.9-2.5.2-1.2-.3-2.1-1.3-3.2l-.8-.8c-.4-.5-.6-1.3-.2-1.9.4-.5.9-.8 1.8-.5 1.3.4 1.9 1.3 2.9 2.2-.4 1.4-.7 2.9-.9 4.2l-.2 1c-.7 4-1.3 6.2-2.7 7.5-.3.3-.7.5-1.3.6-.3 0-.4-.3-.4-.3 0-.3.2-.3.3-.4.2-.1.5-.3.4-.8 0-.7-.6-1.3-1.3-1.3-.6 0-1.4.6-1.4 1.7s1 1.9 2.4 1.8c.8 0 2.5-.3 4.2-2.5 2-2.5 2.5-5.4 2.9-7.4l.5-2.8c.3 0 .5.1.8.1 2.4.1 3.7-1.3 3.7-2.3 0-.6-.3-1.2-.9-1.2-.4 0-.8.3-1 .8-.1.6.8 1.1.1 1.5-.5.3-1.4.6-2.7.4l.3-1.3c.5-2.6 1-5.7 3.2-5.8.2 0 .8 0 .8.4 0 .2 0 .2-.2.5s-.3.4-.2.7c0 .7.5 1.1 1.2 1.1.9 0 1.2-1 1.2-1.4 0-1.2-1.2-1.8-2.6-1.8-1.5.1-2.8.9-3.7 2.1-1.1 1.3-1.8 2.9-2.3 4.5-.9-.8-1.6-1.8-3.1-2.3-1.1-.7-2.3-.5-3.4.3-.5.4-.8 1-1 1.6-.4 1.5.4 2.9.8 3.4l.9 1c.2.2.6.8.4 1.5-.3.8-1.2 1.3-2.1 1-.4-.2-1-.5-.9-.9.1-.2.2-.3.3-.5s.1-.3.1-.3c.2-.6-.1-1.4-.7-1.6-.6-.2-1.2 0-1.3.8 0 .7.4 2.3 2.5 3.1zm39.3-19.9c0-4.2-3.2-7.5-7.1-7.5h-3.8c-.4-2.6-2.5-4.4-5-4.4l-32.5.1c-2.8.1-4.9 2.4-4.9 5.4l.2 44.1c0 4.8 8.1 13.9 11.6 14.1l34.7-.1c3.9 0 7-3.4 7-7.6l-.2-44.1zM-.3 36.4c0-8.6 6.5-15.6 14.5-15.6s14.5 7 14.5 15.6S22.1 52 14.2 52C6.1 52-.3 45-.3 36.4zm42.4 28.7c0 1.8-1.5 3.1-3.1 3.1H4.6c-.7 0-3-1.8-4.5-4.4h30.4c2.8 0 5-2.4 5-5.4V17.9h3.7c1.6 0 2.9 1.4 2.9 3.1v44.1z"/></svg>
Read the documentation to learn
<a href="https://symfony.com/doc/<?php echo $docVersion; ?>/page_creation.html">

View File

@@ -35,7 +35,7 @@ class ChainCacheClearerTest extends TestCase
->expects($this->once())
->method('clear');
$chainClearer = new ChainCacheClearer(array($clearer));
$chainClearer = new ChainCacheClearer([$clearer]);
$chainClearer->clear(self::$cacheDir);
}

View File

@@ -24,7 +24,7 @@ class Psr6CacheClearerTest extends TestCase
->expects($this->once())
->method('clear');
(new Psr6CacheClearer(array('pool' => $pool)))->clear('');
(new Psr6CacheClearer(['pool' => $pool]))->clear('');
}
public function testClearPool()
@@ -34,7 +34,7 @@ class Psr6CacheClearerTest extends TestCase
->expects($this->once())
->method('clear');
(new Psr6CacheClearer(array('pool' => $pool)))->clearPool('pool');
(new Psr6CacheClearer(['pool' => $pool]))->clearPool('pool');
}
/**

View File

@@ -34,7 +34,7 @@ class CacheWarmerAggregateTest extends TestCase
$warmer
->expects($this->once())
->method('warmUp');
$aggregate = new CacheWarmerAggregate(array($warmer));
$aggregate = new CacheWarmerAggregate([$warmer]);
$aggregate->warmUp(self::$cacheDir);
}
@@ -48,7 +48,7 @@ class CacheWarmerAggregateTest extends TestCase
->expects($this->once())
->method('warmUp');
$aggregate = new CacheWarmerAggregate(array($warmer));
$aggregate = new CacheWarmerAggregate([$warmer]);
$aggregate->enableOptionalWarmers();
$aggregate->warmUp(self::$cacheDir);
}
@@ -64,7 +64,7 @@ class CacheWarmerAggregateTest extends TestCase
->expects($this->never())
->method('warmUp');
$aggregate = new CacheWarmerAggregate(array($warmer));
$aggregate = new CacheWarmerAggregate([$warmer]);
$aggregate->warmUp(self::$cacheDir);
}

View File

@@ -70,7 +70,7 @@ class ClientTest extends TestCase
$response->headers->setCookie($cookie2 = new Cookie('foo1', 'bar1', \DateTime::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true, false, null));
$domResponse = $m->invoke($client, $response);
$this->assertSame((string) $cookie1, $domResponse->getHeader('Set-Cookie'));
$this->assertSame(array((string) $cookie1, (string) $cookie2), $domResponse->getHeader('Set-Cookie', false));
$this->assertSame([(string) $cookie1, (string) $cookie2], $domResponse->getHeader('Set-Cookie', false));
}
public function testFilterResponseSupportsStreamedResponses()
@@ -99,14 +99,14 @@ class ClientTest extends TestCase
$kernel = new TestHttpKernel();
$client = new Client($kernel);
$files = array(
array('tmp_name' => $source, 'name' => 'original', 'type' => 'mime/original', 'size' => null, 'error' => UPLOAD_ERR_OK),
$files = [
['tmp_name' => $source, 'name' => 'original', 'type' => 'mime/original', 'size' => null, 'error' => UPLOAD_ERR_OK],
new UploadedFile($source, 'original', 'mime/original', UPLOAD_ERR_OK, true),
);
];
$file = null;
foreach ($files as $file) {
$client->request('POST', '/', array(), array('foo' => $file));
$client->request('POST', '/', [], ['foo' => $file]);
$files = $client->getRequest()->files->all();
@@ -130,9 +130,9 @@ class ClientTest extends TestCase
$kernel = new TestHttpKernel();
$client = new Client($kernel);
$file = array('tmp_name' => '', 'name' => '', 'type' => '', 'size' => 0, 'error' => UPLOAD_ERR_NO_FILE);
$file = ['tmp_name' => '', 'name' => '', 'type' => '', 'size' => 0, 'error' => UPLOAD_ERR_NO_FILE];
$client->request('POST', '/', array(), array('foo' => $file));
$client->request('POST', '/', [], ['foo' => $file]);
$files = $client->getRequest()->files->all();
@@ -149,8 +149,8 @@ class ClientTest extends TestCase
$file = $this
->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile')
->setConstructorArgs(array($source, 'original', 'mime/original', UPLOAD_ERR_OK, true))
->setMethods(array('getSize', 'getClientSize'))
->setConstructorArgs([$source, 'original', 'mime/original', UPLOAD_ERR_OK, true])
->setMethods(['getSize', 'getClientSize'])
->getMock()
;
/* should be modified when the getClientSize will be removed */
@@ -163,7 +163,7 @@ class ClientTest extends TestCase
->will($this->returnValue(INF))
;
$client->request('POST', '/', array(), array($file));
$client->request('POST', '/', [], [$file]);
$files = $client->getRequest()->files->all();

View File

@@ -23,86 +23,86 @@ class ServiceValueResolverTest extends TestCase
{
public function testDoNotSupportWhenControllerDoNotExists()
{
$resolver = new ServiceValueResolver(new ServiceLocator(array()));
$resolver = new ServiceValueResolver(new ServiceLocator([]));
$argument = new ArgumentMetadata('dummy', DummyService::class, false, false, null);
$request = $this->requestWithAttributes(array('_controller' => 'my_controller'));
$request = $this->requestWithAttributes(['_controller' => 'my_controller']);
$this->assertFalse($resolver->supports($request, $argument));
}
public function testExistingController()
{
$resolver = new ServiceValueResolver(new ServiceLocator(array(
$resolver = new ServiceValueResolver(new ServiceLocator([
'App\\Controller\\Mine::method' => function () {
return new ServiceLocator(array(
return new ServiceLocator([
'dummy' => function () {
return new DummyService();
},
));
]);
},
)));
]));
$request = $this->requestWithAttributes(array('_controller' => 'App\\Controller\\Mine::method'));
$request = $this->requestWithAttributes(['_controller' => 'App\\Controller\\Mine::method']);
$argument = new ArgumentMetadata('dummy', DummyService::class, false, false, null);
$this->assertTrue($resolver->supports($request, $argument));
$this->assertYieldEquals(array(new DummyService()), $resolver->resolve($request, $argument));
$this->assertYieldEquals([new DummyService()], $resolver->resolve($request, $argument));
}
public function testExistingControllerWithATrailingBackSlash()
{
$resolver = new ServiceValueResolver(new ServiceLocator(array(
$resolver = new ServiceValueResolver(new ServiceLocator([
'App\\Controller\\Mine::method' => function () {
return new ServiceLocator(array(
return new ServiceLocator([
'dummy' => function () {
return new DummyService();
},
));
]);
},
)));
]));
$request = $this->requestWithAttributes(array('_controller' => '\\App\\Controller\\Mine::method'));
$request = $this->requestWithAttributes(['_controller' => '\\App\\Controller\\Mine::method']);
$argument = new ArgumentMetadata('dummy', DummyService::class, false, false, null);
$this->assertTrue($resolver->supports($request, $argument));
$this->assertYieldEquals(array(new DummyService()), $resolver->resolve($request, $argument));
$this->assertYieldEquals([new DummyService()], $resolver->resolve($request, $argument));
}
public function testExistingControllerWithMethodNameStartUppercase()
{
$resolver = new ServiceValueResolver(new ServiceLocator(array(
$resolver = new ServiceValueResolver(new ServiceLocator([
'App\\Controller\\Mine::method' => function () {
return new ServiceLocator(array(
return new ServiceLocator([
'dummy' => function () {
return new DummyService();
},
));
]);
},
)));
$request = $this->requestWithAttributes(array('_controller' => 'App\\Controller\\Mine::Method'));
]));
$request = $this->requestWithAttributes(['_controller' => 'App\\Controller\\Mine::Method']);
$argument = new ArgumentMetadata('dummy', DummyService::class, false, false, null);
$this->assertTrue($resolver->supports($request, $argument));
$this->assertYieldEquals(array(new DummyService()), $resolver->resolve($request, $argument));
$this->assertYieldEquals([new DummyService()], $resolver->resolve($request, $argument));
}
public function testControllerNameIsAnArray()
{
$resolver = new ServiceValueResolver(new ServiceLocator(array(
$resolver = new ServiceValueResolver(new ServiceLocator([
'App\\Controller\\Mine::method' => function () {
return new ServiceLocator(array(
return new ServiceLocator([
'dummy' => function () {
return new DummyService();
},
));
]);
},
)));
]));
$request = $this->requestWithAttributes(array('_controller' => array('App\\Controller\\Mine', 'method')));
$request = $this->requestWithAttributes(['_controller' => ['App\\Controller\\Mine', 'method']]);
$argument = new ArgumentMetadata('dummy', DummyService::class, false, false, null);
$this->assertTrue($resolver->supports($request, $argument));
$this->assertYieldEquals(array(new DummyService()), $resolver->resolve($request, $argument));
$this->assertYieldEquals([new DummyService()], $resolver->resolve($request, $argument));
}
/**
@@ -119,7 +119,7 @@ class ServiceValueResolverTest extends TestCase
$container->compile();
$request = $this->requestWithAttributes(array('_controller' => array(DummyController::class, 'index')));
$request = $this->requestWithAttributes(['_controller' => [DummyController::class, 'index']]);
$argument = new ArgumentMetadata('dummy', DummyService::class, false, false, null);
$container->get('argument_resolver.service')->resolve($request, $argument)->current();
}
@@ -137,7 +137,7 @@ class ServiceValueResolverTest extends TestCase
private function assertYieldEquals(array $expected, \Generator $generator)
{
$args = array();
$args = [];
foreach ($generator as $arg) {
$args[] = $arg;
}

View File

@@ -40,33 +40,33 @@ class ArgumentResolverTest extends TestCase
public function testDefaultState()
{
$this->assertEquals(self::$resolver, new ArgumentResolver());
$this->assertNotEquals(self::$resolver, new ArgumentResolver(null, array(new RequestAttributeValueResolver())));
$this->assertNotEquals(self::$resolver, new ArgumentResolver(null, [new RequestAttributeValueResolver()]));
}
public function testGetArguments()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = array(new self(), 'controllerWithFoo');
$controller = [new self(), 'controllerWithFoo'];
$this->assertEquals(array('foo'), self::$resolver->getArguments($request, $controller), '->getArguments() returns an array of arguments for the controller method');
$this->assertEquals(['foo'], self::$resolver->getArguments($request, $controller), '->getArguments() returns an array of arguments for the controller method');
}
public function testGetArgumentsReturnsEmptyArrayWhenNoArguments()
{
$request = Request::create('/');
$controller = array(new self(), 'controllerWithoutArguments');
$controller = [new self(), 'controllerWithoutArguments'];
$this->assertEquals(array(), self::$resolver->getArguments($request, $controller), '->getArguments() returns an empty array if the method takes no arguments');
$this->assertEquals([], self::$resolver->getArguments($request, $controller), '->getArguments() returns an empty array if the method takes no arguments');
}
public function testGetArgumentsUsesDefaultValue()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = array(new self(), 'controllerWithFooAndDefaultBar');
$controller = [new self(), 'controllerWithFooAndDefaultBar'];
$this->assertEquals(array('foo', null), self::$resolver->getArguments($request, $controller), '->getArguments() uses default values if present');
$this->assertEquals(['foo', null], self::$resolver->getArguments($request, $controller), '->getArguments() uses default values if present');
}
public function testGetArgumentsOverrideDefaultValueByRequestAttribute()
@@ -74,9 +74,9 @@ class ArgumentResolverTest extends TestCase
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', 'bar');
$controller = array(new self(), 'controllerWithFooAndDefaultBar');
$controller = [new self(), 'controllerWithFooAndDefaultBar'];
$this->assertEquals(array('foo', 'bar'), self::$resolver->getArguments($request, $controller), '->getArguments() overrides default values if provided in the request attributes');
$this->assertEquals(['foo', 'bar'], self::$resolver->getArguments($request, $controller), '->getArguments() overrides default values if provided in the request attributes');
}
public function testGetArgumentsFromClosure()
@@ -85,7 +85,7 @@ class ArgumentResolverTest extends TestCase
$request->attributes->set('foo', 'foo');
$controller = function ($foo) {};
$this->assertEquals(array('foo'), self::$resolver->getArguments($request, $controller));
$this->assertEquals(['foo'], self::$resolver->getArguments($request, $controller));
}
public function testGetArgumentsUsesDefaultValueFromClosure()
@@ -94,7 +94,7 @@ class ArgumentResolverTest extends TestCase
$request->attributes->set('foo', 'foo');
$controller = function ($foo, $bar = 'bar') {};
$this->assertEquals(array('foo', 'bar'), self::$resolver->getArguments($request, $controller));
$this->assertEquals(['foo', 'bar'], self::$resolver->getArguments($request, $controller));
}
public function testGetArgumentsFromInvokableObject()
@@ -103,12 +103,12 @@ class ArgumentResolverTest extends TestCase
$request->attributes->set('foo', 'foo');
$controller = new self();
$this->assertEquals(array('foo', null), self::$resolver->getArguments($request, $controller));
$this->assertEquals(['foo', null], self::$resolver->getArguments($request, $controller));
// Test default bar overridden by request attribute
$request->attributes->set('bar', 'bar');
$this->assertEquals(array('foo', 'bar'), self::$resolver->getArguments($request, $controller));
$this->assertEquals(['foo', 'bar'], self::$resolver->getArguments($request, $controller));
}
public function testGetArgumentsFromFunctionName()
@@ -118,7 +118,7 @@ class ArgumentResolverTest extends TestCase
$request->attributes->set('foobar', 'foobar');
$controller = __NAMESPACE__.'\controller_function';
$this->assertEquals(array('foo', 'foobar'), self::$resolver->getArguments($request, $controller));
$this->assertEquals(['foo', 'foobar'], self::$resolver->getArguments($request, $controller));
}
public function testGetArgumentsFailsOnUnresolvedValue()
@@ -126,7 +126,7 @@ class ArgumentResolverTest extends TestCase
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('foobar', 'foobar');
$controller = array(new self(), 'controllerWithFooBarFoobar');
$controller = [new self(), 'controllerWithFooBarFoobar'];
try {
self::$resolver->getArguments($request, $controller);
@@ -139,27 +139,27 @@ class ArgumentResolverTest extends TestCase
public function testGetArgumentsInjectsRequest()
{
$request = Request::create('/');
$controller = array(new self(), 'controllerWithRequest');
$controller = [new self(), 'controllerWithRequest'];
$this->assertEquals(array($request), self::$resolver->getArguments($request, $controller), '->getArguments() injects the request');
$this->assertEquals([$request], self::$resolver->getArguments($request, $controller), '->getArguments() injects the request');
}
public function testGetArgumentsInjectsExtendingRequest()
{
$request = ExtendingRequest::create('/');
$controller = array(new self(), 'controllerWithExtendingRequest');
$controller = [new self(), 'controllerWithExtendingRequest'];
$this->assertEquals(array($request), self::$resolver->getArguments($request, $controller), '->getArguments() injects the request when extended');
$this->assertEquals([$request], self::$resolver->getArguments($request, $controller), '->getArguments() injects the request when extended');
}
public function testGetVariadicArguments()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', array('foo', 'bar'));
$controller = array(new VariadicController(), 'action');
$request->attributes->set('bar', ['foo', 'bar']);
$controller = [new VariadicController(), 'action'];
$this->assertEquals(array('foo', 'foo', 'bar'), self::$resolver->getArguments($request, $controller));
$this->assertEquals(['foo', 'foo', 'bar'], self::$resolver->getArguments($request, $controller));
}
/**
@@ -170,7 +170,7 @@ class ArgumentResolverTest extends TestCase
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', 'foo');
$controller = array(new VariadicController(), 'action');
$controller = [new VariadicController(), 'action'];
self::$resolver->getArguments($request, $controller);
}
@@ -182,7 +182,7 @@ class ArgumentResolverTest extends TestCase
{
$factory = new ArgumentMetadataFactory();
$valueResolver = $this->getMockBuilder(ArgumentValueResolverInterface::class)->getMock();
$resolver = new ArgumentResolver($factory, array($valueResolver));
$resolver = new ArgumentResolver($factory, [$valueResolver]);
$valueResolver->expects($this->any())->method('supports')->willReturn(true);
$valueResolver->expects($this->any())->method('resolve')->willReturn('foo');
@@ -190,7 +190,7 @@ class ArgumentResolverTest extends TestCase
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', 'foo');
$controller = array($this, 'controllerWithFooAndDefaultBar');
$controller = [$this, 'controllerWithFooAndDefaultBar'];
$resolver->getArguments($request, $controller);
}
@@ -200,7 +200,7 @@ class ArgumentResolverTest extends TestCase
public function testIfExceptionIsThrownWhenMissingAnArgument()
{
$request = Request::create('/');
$controller = array($this, 'controllerWithFoo');
$controller = [$this, 'controllerWithFoo'];
self::$resolver->getArguments($request, $controller);
}
@@ -211,18 +211,18 @@ class ArgumentResolverTest extends TestCase
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', new \stdClass());
$request->attributes->set('mandatory', 'mandatory');
$controller = array(new NullableController(), 'action');
$controller = [new NullableController(), 'action'];
$this->assertEquals(array('foo', new \stdClass(), 'value', 'mandatory'), self::$resolver->getArguments($request, $controller));
$this->assertEquals(['foo', new \stdClass(), 'value', 'mandatory'], self::$resolver->getArguments($request, $controller));
}
public function testGetNullableArgumentsWithDefaults()
{
$request = Request::create('/');
$request->attributes->set('mandatory', 'mandatory');
$controller = array(new NullableController(), 'action');
$controller = [new NullableController(), 'action'];
$this->assertEquals(array(null, null, 'value', 'mandatory'), self::$resolver->getArguments($request, $controller));
$this->assertEquals([null, null, 'value', 'mandatory'], self::$resolver->getArguments($request, $controller));
}
public function testGetSessionArguments()
@@ -230,9 +230,9 @@ class ArgumentResolverTest extends TestCase
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/');
$request->setSession($session);
$controller = array($this, 'controllerWithSession');
$controller = [$this, 'controllerWithSession'];
$this->assertEquals(array($session), self::$resolver->getArguments($request, $controller));
$this->assertEquals([$session], self::$resolver->getArguments($request, $controller));
}
public function testGetSessionArgumentsWithExtendedSession()
@@ -240,9 +240,9 @@ class ArgumentResolverTest extends TestCase
$session = new ExtendingSession(new MockArraySessionStorage());
$request = Request::create('/');
$request->setSession($session);
$controller = array($this, 'controllerWithExtendingSession');
$controller = [$this, 'controllerWithExtendingSession'];
$this->assertEquals(array($session), self::$resolver->getArguments($request, $controller));
$this->assertEquals([$session], self::$resolver->getArguments($request, $controller));
}
public function testGetSessionArgumentsWithInterface()
@@ -250,9 +250,9 @@ class ArgumentResolverTest extends TestCase
$session = $this->getMockBuilder(SessionInterface::class)->getMock();
$request = Request::create('/');
$request->setSession($session);
$controller = array($this, 'controllerWithSessionInterface');
$controller = [$this, 'controllerWithSessionInterface'];
$this->assertEquals(array($session), self::$resolver->getArguments($request, $controller));
$this->assertEquals([$session], self::$resolver->getArguments($request, $controller));
}
/**
@@ -263,7 +263,7 @@ class ArgumentResolverTest extends TestCase
$session = $this->getMockBuilder(SessionInterface::class)->getMock();
$request = Request::create('/');
$request->setSession($session);
$controller = array($this, 'controllerWithExtendingSession');
$controller = [$this, 'controllerWithExtendingSession'];
self::$resolver->getArguments($request, $controller);
}
@@ -276,7 +276,7 @@ class ArgumentResolverTest extends TestCase
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/');
$request->setSession($session);
$controller = array($this, 'controllerWithExtendingSession');
$controller = [$this, 'controllerWithExtendingSession'];
self::$resolver->getArguments($request, $controller);
}
@@ -287,7 +287,7 @@ class ArgumentResolverTest extends TestCase
public function testGetSessionMissMatchOnNull()
{
$request = Request::create('/');
$controller = array($this, 'controllerWithExtendingSession');
$controller = [$this, 'controllerWithExtendingSession'];
self::$resolver->getArguments($request, $controller);
}

View File

@@ -137,12 +137,12 @@ class ContainerControllerResolverTest extends ControllerResolverTest
$container->expects($this->atLeastOnce())
->method('getRemovedIds')
->with()
->will($this->returnValue(array(ControllerTestService::class => true)))
->will($this->returnValue([ControllerTestService::class => true]))
;
$resolver = $this->createControllerResolver(null, $container);
$request = Request::create('/');
$request->attributes->set('_controller', array(ControllerTestService::class, 'action'));
$request->attributes->set('_controller', [ControllerTestService::class, 'action']);
$resolver->getController($request);
}
@@ -165,7 +165,7 @@ class ContainerControllerResolverTest extends ControllerResolverTest
$container->expects($this->atLeastOnce())
->method('getRemovedIds')
->with()
->will($this->returnValue(array('app.my_controller' => true)))
->will($this->returnValue(['app.my_controller' => true]))
;
$resolver = $this->createControllerResolver(null, $container);
@@ -178,23 +178,23 @@ class ContainerControllerResolverTest extends ControllerResolverTest
public function getUndefinedControllers()
{
$tests = parent::getUndefinedControllers();
$tests[0] = array('foo', \InvalidArgumentException::class, 'Controller "foo" does neither exist as service nor as class');
$tests[1] = array('oof::bar', \InvalidArgumentException::class, 'Controller "oof" does neither exist as service nor as class');
$tests[2] = array(array('oof', 'bar'), \InvalidArgumentException::class, 'Controller "oof" does neither exist as service nor as class');
$tests[] = array(
array(ControllerTestService::class, 'action'),
$tests[0] = ['foo', \InvalidArgumentException::class, 'Controller "foo" does neither exist as service nor as class'];
$tests[1] = ['oof::bar', \InvalidArgumentException::class, 'Controller "oof" does neither exist as service nor as class'];
$tests[2] = [['oof', 'bar'], \InvalidArgumentException::class, 'Controller "oof" does neither exist as service nor as class'];
$tests[] = [
[ControllerTestService::class, 'action'],
\InvalidArgumentException::class,
'Controller "Symfony\Component\HttpKernel\Tests\Controller\ControllerTestService" has required constructor arguments and does not exist in the container. Did you forget to define such a service?',
);
$tests[] = array(
];
$tests[] = [
ControllerTestService::class.'::action',
\InvalidArgumentException::class, 'Controller "Symfony\Component\HttpKernel\Tests\Controller\ControllerTestService" has required constructor arguments and does not exist in the container. Did you forget to define such a service?',
);
$tests[] = array(
];
$tests[] = [
InvokableControllerService::class,
\InvalidArgumentException::class,
'Controller "Symfony\Component\HttpKernel\Tests\Controller\InvokableControllerService" has required constructor arguments and does not exist in the container. Did you forget to define such a service?',
);
];
return $tests;
}

View File

@@ -55,9 +55,9 @@ class ControllerResolverTest extends TestCase
$object = new ControllerTest();
$request = Request::create('/');
$request->attributes->set('_controller', array($object, 'publicAction'));
$request->attributes->set('_controller', [$object, 'publicAction']);
$controller = $resolver->getController($request);
$this->assertSame(array($object, 'publicAction'), $controller);
$this->assertSame([$object, 'publicAction'], $controller);
}
public function testGetControllerWithClassAndMethodAsArray()
@@ -65,7 +65,7 @@ class ControllerResolverTest extends TestCase
$resolver = $this->createControllerResolver();
$request = Request::create('/');
$request->attributes->set('_controller', array(ControllerTest::class, 'publicAction'));
$request->attributes->set('_controller', [ControllerTest::class, 'publicAction']);
$controller = $resolver->getController($request);
$this->assertInstanceOf(ControllerTest::class, $controller[0]);
$this->assertSame('publicAction', $controller[1]);
@@ -145,12 +145,12 @@ class ControllerResolverTest extends TestCase
public function getStaticControllers()
{
return array(
array(TestAbstractController::class.'::staticAction', 'foo'),
array(array(TestAbstractController::class, 'staticAction'), 'foo'),
array(PrivateConstructorController::class.'::staticAction', 'bar'),
array(array(PrivateConstructorController::class, 'staticAction'), 'bar'),
);
return [
[TestAbstractController::class.'::staticAction', 'foo'],
[[TestAbstractController::class, 'staticAction'], 'foo'],
[PrivateConstructorController::class.'::staticAction', 'bar'],
[[PrivateConstructorController::class, 'staticAction'], 'bar'],
];
}
/**
@@ -175,22 +175,22 @@ class ControllerResolverTest extends TestCase
{
$controller = new ControllerTest();
return array(
array('foo', \Error::class, 'Class \'foo\' not found'),
array('oof::bar', \Error::class, 'Class \'oof\' not found'),
array(array('oof', 'bar'), \Error::class, 'Class \'oof\' not found'),
array('Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::staticsAction', \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Expected method "staticsAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest", did you mean "staticAction"?'),
array('Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::privateAction', \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Method "privateAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest" should be public and non-abstract'),
array('Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::protectedAction', \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Method "protectedAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest" should be public and non-abstract'),
array('Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::undefinedAction', \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Expected method "undefinedAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest". Available methods: "publicAction", "staticAction"'),
array('Symfony\Component\HttpKernel\Tests\Controller\ControllerTest', \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Controller class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest" cannot be called without a method name. You need to implement "__invoke" or use one of the available methods: "publicAction", "staticAction".'),
array(array($controller, 'staticsAction'), \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Expected method "staticsAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest", did you mean "staticAction"?'),
array(array($controller, 'privateAction'), \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Method "privateAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest" should be public and non-abstract'),
array(array($controller, 'protectedAction'), \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Method "protectedAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest" should be public and non-abstract'),
array(array($controller, 'undefinedAction'), \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Expected method "undefinedAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest". Available methods: "publicAction", "staticAction"'),
array($controller, \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Controller class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest" cannot be called without a method name. You need to implement "__invoke" or use one of the available methods: "publicAction", "staticAction".'),
array(array('a' => 'foo', 'b' => 'bar'), \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Invalid array callable, expected array(controller, method).'),
);
return [
['foo', \Error::class, 'Class \'foo\' not found'],
['oof::bar', \Error::class, 'Class \'oof\' not found'],
[['oof', 'bar'], \Error::class, 'Class \'oof\' not found'],
['Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::staticsAction', \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Expected method "staticsAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest", did you mean "staticAction"?'],
['Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::privateAction', \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Method "privateAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest" should be public and non-abstract'],
['Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::protectedAction', \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Method "protectedAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest" should be public and non-abstract'],
['Symfony\Component\HttpKernel\Tests\Controller\ControllerTest::undefinedAction', \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Expected method "undefinedAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest". Available methods: "publicAction", "staticAction"'],
['Symfony\Component\HttpKernel\Tests\Controller\ControllerTest', \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Controller class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest" cannot be called without a method name. You need to implement "__invoke" or use one of the available methods: "publicAction", "staticAction".'],
[[$controller, 'staticsAction'], \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Expected method "staticsAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest", did you mean "staticAction"?'],
[[$controller, 'privateAction'], \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Method "privateAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest" should be public and non-abstract'],
[[$controller, 'protectedAction'], \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Method "protectedAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest" should be public and non-abstract'],
[[$controller, 'undefinedAction'], \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Expected method "undefinedAction" on class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest". Available methods: "publicAction", "staticAction"'],
[$controller, \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Controller class "Symfony\Component\HttpKernel\Tests\Controller\ControllerTest" cannot be called without a method name. You need to implement "__invoke" or use one of the available methods: "publicAction", "staticAction".'],
[['a' => 'foo', 'b' => 'bar'], \InvalidArgumentException::class, 'The controller for URI "/" is not callable. Invalid array callable, expected [controller, method].'],
];
}
protected function createControllerResolver(LoggerInterface $logger = null)

View File

@@ -33,88 +33,88 @@ class ArgumentMetadataFactoryTest extends TestCase
public function testSignature1()
{
$arguments = $this->factory->createArgumentMetadata(array($this, 'signature1'));
$arguments = $this->factory->createArgumentMetadata([$this, 'signature1']);
$this->assertEquals(array(
$this->assertEquals([
new ArgumentMetadata('foo', self::class, false, false, null),
new ArgumentMetadata('bar', 'array', false, false, null),
new ArgumentMetadata('baz', 'callable', false, false, null),
), $arguments);
], $arguments);
}
public function testSignature2()
{
$arguments = $this->factory->createArgumentMetadata(array($this, 'signature2'));
$arguments = $this->factory->createArgumentMetadata([$this, 'signature2']);
$this->assertEquals(array(
$this->assertEquals([
new ArgumentMetadata('foo', self::class, false, true, null, true),
new ArgumentMetadata('bar', __NAMESPACE__.'\FakeClassThatDoesNotExist', false, true, null, true),
new ArgumentMetadata('baz', 'Fake\ImportedAndFake', false, true, null, true),
), $arguments);
], $arguments);
}
public function testSignature3()
{
$arguments = $this->factory->createArgumentMetadata(array($this, 'signature3'));
$arguments = $this->factory->createArgumentMetadata([$this, 'signature3']);
$this->assertEquals(array(
$this->assertEquals([
new ArgumentMetadata('bar', __NAMESPACE__.'\FakeClassThatDoesNotExist', false, false, null),
new ArgumentMetadata('baz', 'Fake\ImportedAndFake', false, false, null),
), $arguments);
], $arguments);
}
public function testSignature4()
{
$arguments = $this->factory->createArgumentMetadata(array($this, 'signature4'));
$arguments = $this->factory->createArgumentMetadata([$this, 'signature4']);
$this->assertEquals(array(
$this->assertEquals([
new ArgumentMetadata('foo', null, false, true, 'default'),
new ArgumentMetadata('bar', null, false, true, 500),
new ArgumentMetadata('baz', null, false, true, array()),
), $arguments);
new ArgumentMetadata('baz', null, false, true, []),
], $arguments);
}
public function testSignature5()
{
$arguments = $this->factory->createArgumentMetadata(array($this, 'signature5'));
$arguments = $this->factory->createArgumentMetadata([$this, 'signature5']);
$this->assertEquals(array(
$this->assertEquals([
new ArgumentMetadata('foo', 'array', false, true, null, true),
new ArgumentMetadata('bar', null, false, false, null),
), $arguments);
], $arguments);
}
public function testVariadicSignature()
{
$arguments = $this->factory->createArgumentMetadata(array(new VariadicController(), 'action'));
$arguments = $this->factory->createArgumentMetadata([new VariadicController(), 'action']);
$this->assertEquals(array(
$this->assertEquals([
new ArgumentMetadata('foo', null, false, false, null),
new ArgumentMetadata('bar', null, true, false, null),
), $arguments);
], $arguments);
}
public function testBasicTypesSignature()
{
$arguments = $this->factory->createArgumentMetadata(array(new BasicTypesController(), 'action'));
$arguments = $this->factory->createArgumentMetadata([new BasicTypesController(), 'action']);
$this->assertEquals(array(
$this->assertEquals([
new ArgumentMetadata('foo', 'string', false, false, null),
new ArgumentMetadata('bar', 'int', false, false, null),
new ArgumentMetadata('baz', 'float', false, false, null),
), $arguments);
], $arguments);
}
public function testNullableTypesSignature()
{
$arguments = $this->factory->createArgumentMetadata(array(new NullableController(), 'action'));
$arguments = $this->factory->createArgumentMetadata([new NullableController(), 'action']);
$this->assertEquals(array(
$this->assertEquals([
new ArgumentMetadata('foo', 'string', false, false, null, true),
new ArgumentMetadata('bar', \stdClass::class, false, false, null, true),
new ArgumentMetadata('baz', 'string', false, true, 'value', true),
new ArgumentMetadata('mandatory', null, false, false, null, true),
), $arguments);
], $arguments);
}
private function signature1(self $foo, array $bar, callable $baz)
@@ -129,7 +129,7 @@ class ArgumentMetadataFactoryTest extends TestCase
{
}
private function signature4($foo = 'default', $bar = 500, $baz = array())
private function signature4($foo = 'default', $bar = 500, $baz = [])
{
}

View File

@@ -67,7 +67,7 @@ class KernelForTest extends Kernel
public function getBundles()
{
return array();
return [];
}
public function registerContainerConfiguration(LoaderInterface $loader)

View File

@@ -30,7 +30,7 @@ class DataCollectorTest extends TestCase
public function testCloneVarExistingFilePath()
{
$c = new CloneVarDataCollector(array($filePath = tempnam(sys_get_temp_dir(), 'clone_var_data_collector_')));
$c = new CloneVarDataCollector([$filePath = tempnam(sys_get_temp_dir(), 'clone_var_data_collector_')]);
$c->collect(new Request(), new Response());
$this->assertSame($filePath, $c->getData()[0]);

View File

@@ -26,7 +26,7 @@ class DumpDataCollectorTest extends TestCase
{
public function testDump()
{
$data = new Data(array(array(123)));
$data = new Data([[123]]);
$collector = new DumpDataCollector();
@@ -41,15 +41,15 @@ class DumpDataCollectorTest extends TestCase
$dump[0]['data'] = preg_replace('/^.*?<pre/', '<pre', $dump[0]['data']);
$dump[0]['data'] = preg_replace('/sf-dump-\d+/', 'sf-dump', $dump[0]['data']);
$xDump = array(
array(
$xDump = [
[
'data' => "<pre class=sf-dump id=sf-dump data-indent-pad=\" \"><span class=sf-dump-num>123</span>\n</pre><script>Sfdump(\"sf-dump\")</script>\n",
'name' => 'DumpDataCollectorTest.php',
'file' => __FILE__,
'line' => $line,
'fileExcerpt' => false,
),
);
],
];
$this->assertEquals($xDump, $dump);
$this->assertStringMatchesFormat('a:3:{i:0;a:5:{s:4:"data";%c:39:"Symfony\Component\VarDumper\Cloner\Data":%a', $collector->serialize());
@@ -59,7 +59,7 @@ class DumpDataCollectorTest extends TestCase
public function testDumpWithServerConnection()
{
$data = new Data(array(array(123)));
$data = new Data([[123]]);
// Server is up, server dumper is used
$serverDumper = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock();
@@ -77,7 +77,7 @@ class DumpDataCollectorTest extends TestCase
public function testCollectDefault()
{
$data = new Data(array(array(123)));
$data = new Data([[123]]);
$collector = new DumpDataCollector();
@@ -95,7 +95,7 @@ class DumpDataCollectorTest extends TestCase
public function testCollectHtml()
{
$data = new Data(array(array(123)));
$data = new Data([[123]]);
$collector = new DumpDataCollector(null, 'test://%f:%l');
@@ -123,7 +123,7 @@ EOTXT;
public function testFlush()
{
$data = new Data(array(array(456)));
$data = new Data([[456]]);
$collector = new DumpDataCollector();
$collector->dump($data);
$line = __LINE__ - 1;
@@ -136,7 +136,7 @@ EOTXT;
public function testFlushNothingWhenDataDumperIsProvided()
{
$data = new Data(array(array(456)));
$data = new Data([[456]]);
$dumper = new CliDumper('php://output');
$collector = new DumpDataCollector(null, null, null, null, $dumper);

View File

@@ -25,24 +25,24 @@ class LoggerDataCollectorTest extends TestCase
{
$logger = $this
->getMockBuilder('Symfony\Component\HttpKernel\Log\DebugLoggerInterface')
->setMethods(array('countErrors', 'getLogs', 'clear'))
->setMethods(['countErrors', 'getLogs', 'clear'])
->getMock();
$logger->expects($this->once())->method('countErrors')->will($this->returnValue('foo'));
$logger->expects($this->exactly(2))->method('getLogs')->will($this->returnValue(array()));
$logger->expects($this->exactly(2))->method('getLogs')->will($this->returnValue([]));
$c = new LoggerDataCollector($logger, __DIR__.'/');
$c->lateCollect();
$compilerLogs = $c->getCompilerLogs()->getValue('message');
$this->assertSame(array(
array('message' => 'Removed service "Psr\Container\ContainerInterface"; reason: private alias.'),
array('message' => 'Removed service "Symfony\Component\DependencyInjection\ContainerInterface"; reason: private alias.'),
), $compilerLogs['Symfony\Component\DependencyInjection\Compiler\RemovePrivateAliasesPass']);
$this->assertSame([
['message' => 'Removed service "Psr\Container\ContainerInterface"; reason: private alias.'],
['message' => 'Removed service "Symfony\Component\DependencyInjection\ContainerInterface"; reason: private alias.'],
], $compilerLogs['Symfony\Component\DependencyInjection\Compiler\RemovePrivateAliasesPass']);
$this->assertSame(array(
array('message' => 'Some custom logging message'),
array('message' => 'With ending :'),
), $compilerLogs['Unknown Compiler Pass']);
$this->assertSame([
['message' => 'Some custom logging message'],
['message' => 'With ending :'],
], $compilerLogs['Unknown Compiler Pass']);
}
public function testWithMasterRequest()
@@ -53,10 +53,10 @@ class LoggerDataCollectorTest extends TestCase
$logger = $this
->getMockBuilder(DebugLoggerInterface::class)
->setMethods(array('countErrors', 'getLogs', 'clear'))
->setMethods(['countErrors', 'getLogs', 'clear'])
->getMock();
$logger->expects($this->once())->method('countErrors')->with(null);
$logger->expects($this->exactly(2))->method('getLogs')->with(null)->will($this->returnValue(array()));
$logger->expects($this->exactly(2))->method('getLogs')->with(null)->will($this->returnValue([]));
$c = new LoggerDataCollector($logger, __DIR__.'/', $stack);
@@ -74,10 +74,10 @@ class LoggerDataCollectorTest extends TestCase
$logger = $this
->getMockBuilder(DebugLoggerInterface::class)
->setMethods(array('countErrors', 'getLogs', 'clear'))
->setMethods(['countErrors', 'getLogs', 'clear'])
->getMock();
$logger->expects($this->once())->method('countErrors')->with($subRequest);
$logger->expects($this->exactly(2))->method('getLogs')->with($subRequest)->will($this->returnValue(array()));
$logger->expects($this->exactly(2))->method('getLogs')->with($subRequest)->will($this->returnValue([]));
$c = new LoggerDataCollector($logger, __DIR__.'/', $stack);
@@ -92,7 +92,7 @@ class LoggerDataCollectorTest extends TestCase
{
$logger = $this
->getMockBuilder('Symfony\Component\HttpKernel\Log\DebugLoggerInterface')
->setMethods(array('countErrors', 'getLogs', 'clear'))
->setMethods(['countErrors', 'getLogs', 'clear'])
->getMock();
$logger->expects($this->once())->method('countErrors')->will($this->returnValue($nb));
$logger->expects($this->exactly(2))->method('getLogs')->will($this->returnValue($logs));
@@ -106,7 +106,7 @@ class LoggerDataCollectorTest extends TestCase
$logs = array_map(function ($v) {
if (isset($v['context']['exception'])) {
$e = &$v['context']['exception'];
$e = isset($e["\0*\0message"]) ? array($e["\0*\0message"], $e["\0*\0severity"]) : array($e["\0Symfony\Component\Debug\Exception\SilencedErrorContext\0severity"]);
$e = isset($e["\0*\0message"]) ? [$e["\0*\0message"], $e["\0*\0severity"]] : [$e["\0Symfony\Component\Debug\Exception\SilencedErrorContext\0severity"]];
}
return $v;
@@ -124,7 +124,7 @@ class LoggerDataCollectorTest extends TestCase
{
$logger = $this
->getMockBuilder('Symfony\Component\HttpKernel\Log\DebugLoggerInterface')
->setMethods(array('countErrors', 'getLogs', 'clear'))
->setMethods(['countErrors', 'getLogs', 'clear'])
->getMock();
$logger->expects($this->once())->method('clear');
@@ -134,55 +134,55 @@ class LoggerDataCollectorTest extends TestCase
public function getCollectTestData()
{
yield 'simple log' => array(
yield 'simple log' => [
1,
array(array('message' => 'foo', 'context' => array(), 'priority' => 100, 'priorityName' => 'DEBUG')),
array(array('message' => 'foo', 'context' => array(), 'priority' => 100, 'priorityName' => 'DEBUG')),
[['message' => 'foo', 'context' => [], 'priority' => 100, 'priorityName' => 'DEBUG']],
[['message' => 'foo', 'context' => [], 'priority' => 100, 'priorityName' => 'DEBUG']],
0,
0,
);
];
yield 'log with a context' => array(
yield 'log with a context' => [
1,
array(array('message' => 'foo', 'context' => array('foo' => 'bar'), 'priority' => 100, 'priorityName' => 'DEBUG')),
array(array('message' => 'foo', 'context' => array('foo' => 'bar'), 'priority' => 100, 'priorityName' => 'DEBUG')),
[['message' => 'foo', 'context' => ['foo' => 'bar'], 'priority' => 100, 'priorityName' => 'DEBUG']],
[['message' => 'foo', 'context' => ['foo' => 'bar'], 'priority' => 100, 'priorityName' => 'DEBUG']],
0,
0,
);
];
if (!class_exists(SilencedErrorContext::class)) {
return;
}
yield 'logs with some deprecations' => array(
yield 'logs with some deprecations' => [
1,
array(
array('message' => 'foo3', 'context' => array('exception' => new \ErrorException('warning', 0, E_USER_WARNING)), 'priority' => 100, 'priorityName' => 'DEBUG'),
array('message' => 'foo', 'context' => array('exception' => new \ErrorException('deprecated', 0, E_DEPRECATED)), 'priority' => 100, 'priorityName' => 'DEBUG'),
array('message' => 'foo2', 'context' => array('exception' => new \ErrorException('deprecated', 0, E_USER_DEPRECATED)), 'priority' => 100, 'priorityName' => 'DEBUG'),
),
array(
array('message' => 'foo3', 'context' => array('exception' => array('warning', E_USER_WARNING)), 'priority' => 100, 'priorityName' => 'DEBUG'),
array('message' => 'foo', 'context' => array('exception' => array('deprecated', E_DEPRECATED)), 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => false),
array('message' => 'foo2', 'context' => array('exception' => array('deprecated', E_USER_DEPRECATED)), 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => false),
),
[
['message' => 'foo3', 'context' => ['exception' => new \ErrorException('warning', 0, E_USER_WARNING)], 'priority' => 100, 'priorityName' => 'DEBUG'],
['message' => 'foo', 'context' => ['exception' => new \ErrorException('deprecated', 0, E_DEPRECATED)], 'priority' => 100, 'priorityName' => 'DEBUG'],
['message' => 'foo2', 'context' => ['exception' => new \ErrorException('deprecated', 0, E_USER_DEPRECATED)], 'priority' => 100, 'priorityName' => 'DEBUG'],
],
[
['message' => 'foo3', 'context' => ['exception' => ['warning', E_USER_WARNING]], 'priority' => 100, 'priorityName' => 'DEBUG'],
['message' => 'foo', 'context' => ['exception' => ['deprecated', E_DEPRECATED]], 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => false],
['message' => 'foo2', 'context' => ['exception' => ['deprecated', E_USER_DEPRECATED]], 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => false],
],
2,
0,
array(100 => array('count' => 3, 'name' => 'DEBUG')),
);
[100 => ['count' => 3, 'name' => 'DEBUG']],
];
yield 'logs with some silent errors' => array(
yield 'logs with some silent errors' => [
1,
array(
array('message' => 'foo3', 'context' => array('exception' => new \ErrorException('warning', 0, E_USER_WARNING)), 'priority' => 100, 'priorityName' => 'DEBUG'),
array('message' => 'foo3', 'context' => array('exception' => new SilencedErrorContext(E_USER_WARNING, __FILE__, __LINE__)), 'priority' => 100, 'priorityName' => 'DEBUG'),
),
array(
array('message' => 'foo3', 'context' => array('exception' => array('warning', E_USER_WARNING)), 'priority' => 100, 'priorityName' => 'DEBUG'),
array('message' => 'foo3', 'context' => array('exception' => array(E_USER_WARNING)), 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => true),
),
[
['message' => 'foo3', 'context' => ['exception' => new \ErrorException('warning', 0, E_USER_WARNING)], 'priority' => 100, 'priorityName' => 'DEBUG'],
['message' => 'foo3', 'context' => ['exception' => new SilencedErrorContext(E_USER_WARNING, __FILE__, __LINE__)], 'priority' => 100, 'priorityName' => 'DEBUG'],
],
[
['message' => 'foo3', 'context' => ['exception' => ['warning', E_USER_WARNING]], 'priority' => 100, 'priorityName' => 'DEBUG'],
['message' => 'foo3', 'context' => ['exception' => [E_USER_WARNING]], 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => true],
],
0,
1,
);
];
}
}

View File

@@ -39,21 +39,21 @@ class MemoryDataCollectorTest extends TestCase
public function getBytesConversionTestData()
{
return array(
array('2k', 2048),
array('2 k', 2048),
array('8m', 8 * 1024 * 1024),
array('+2 k', 2048),
array('+2???k', 2048),
array('0x10', 16),
array('0xf', 15),
array('010', 8),
array('+0x10 k', 16 * 1024),
array('1g', 1024 * 1024 * 1024),
array('1G', 1024 * 1024 * 1024),
array('-1', -1),
array('0', 0),
array('2mk', 2048), // the unit must be the last char, so in this case 'k', not 'm'
);
return [
['2k', 2048],
['2 k', 2048],
['8m', 8 * 1024 * 1024],
['+2 k', 2048],
['+2???k', 2048],
['0x10', 16],
['0xf', 15],
['010', 8],
['+0x10 k', 16 * 1024],
['1g', 1024 * 1024 * 1024],
['1G', 1024 * 1024 * 1024],
['-1', -1],
['0', 0],
['2mk', 2048], // the unit must be the last char, so in this case 'k', not 'm'
];
}
}

View File

@@ -48,8 +48,8 @@ class RequestDataCollectorTest extends TestCase
$this->assertInstanceOf(ParameterBag::class, $c->getResponseCookies());
$this->assertSame('html', $c->getFormat());
$this->assertEquals('foobar', $c->getRoute());
$this->assertEquals(array('name' => 'foo'), $c->getRouteParams());
$this->assertSame(array(), $c->getSessionAttributes());
$this->assertEquals(['name' => 'foo'], $c->getRouteParams());
$this->assertSame([], $c->getSessionAttributes());
$this->assertSame('en', $c->getLocale());
$this->assertContains(__FILE__, $attributes->get('resource'));
$this->assertSame('stdClass', $attributes->get('object')->getType());
@@ -62,13 +62,13 @@ class RequestDataCollectorTest extends TestCase
public function testCollectWithoutRouteParams()
{
$request = $this->createRequest(array());
$request = $this->createRequest([]);
$c = new RequestDataCollector();
$c->collect($request, $this->createResponse());
$c->lateCollect();
$this->assertEquals(array(), $c->getRouteParams());
$this->assertEquals([], $c->getRouteParams());
}
/**
@@ -94,95 +94,95 @@ class RequestDataCollectorTest extends TestCase
$r3 = new \ReflectionClass($this);
// test name, callable, expected
return array(
array(
return [
[
'"Regular" callable',
array($this, 'testControllerInspection'),
array(
[$this, 'testControllerInspection'],
[
'class' => __NAMESPACE__.'\RequestDataCollectorTest',
'method' => 'testControllerInspection',
'file' => __FILE__,
'line' => $r1->getStartLine(),
),
),
],
],
array(
[
'Closure',
function () { return 'foo'; },
array(
[
'class' => __NAMESPACE__.'\{closure}',
'method' => null,
'file' => __FILE__,
'line' => __LINE__ - 5,
),
),
],
],
array(
[
'Static callback as string',
__NAMESPACE__.'\RequestDataCollectorTest::staticControllerMethod',
array(
[
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => 'staticControllerMethod',
'file' => __FILE__,
'line' => $r2->getStartLine(),
),
),
],
],
array(
[
'Static callable with instance',
array($this, 'staticControllerMethod'),
array(
[$this, 'staticControllerMethod'],
[
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => 'staticControllerMethod',
'file' => __FILE__,
'line' => $r2->getStartLine(),
),
),
],
],
array(
[
'Static callable with class name',
array('Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest', 'staticControllerMethod'),
array(
['Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest', 'staticControllerMethod'],
[
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => 'staticControllerMethod',
'file' => __FILE__,
'line' => $r2->getStartLine(),
),
),
],
],
array(
[
'Callable with instance depending on __call()',
array($this, 'magicMethod'),
array(
[$this, 'magicMethod'],
[
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => 'magicMethod',
'file' => 'n/a',
'line' => 'n/a',
),
),
],
],
array(
[
'Callable with class name depending on __callStatic()',
array('Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest', 'magicMethod'),
array(
['Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest', 'magicMethod'],
[
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => 'magicMethod',
'file' => 'n/a',
'line' => 'n/a',
),
),
],
],
array(
[
'Invokable controller',
$this,
array(
[
'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
'method' => null,
'file' => __FILE__,
'line' => $r3->getStartLine(),
),
),
);
],
],
];
}
public function testItIgnoresInvalidCallables()
@@ -199,9 +199,9 @@ class RequestDataCollectorTest extends TestCase
public function testItAddsRedirectedAttributesWhenRequestContainsSpecificCookie()
{
$request = $this->createRequest();
$request->cookies->add(array(
$request->cookies->add([
'sf_redirect' => '{}',
));
]);
$kernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock();
@@ -235,9 +235,9 @@ class RequestDataCollectorTest extends TestCase
$request = $this->createRequest();
$request->attributes->set('_redirected', true);
$request->cookies->add(array(
$request->cookies->add([
'sf_redirect' => '{"method": "POST"}',
));
]);
$c->collect($request, $response = $this->createResponse());
$c->lateCollect();
@@ -248,7 +248,7 @@ class RequestDataCollectorTest extends TestCase
$this->assertNull($cookie->getValue());
}
protected function createRequest($routeParams = array('name' => 'foo'))
protected function createRequest($routeParams = ['name' => 'foo'])
{
$request = Request::create('http://test.com/foo?bar=baz');
$request->attributes->set('foo', 'bar');

View File

@@ -15,6 +15,7 @@ use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\TimeDataCollector;
use Symfony\Component\Stopwatch\Stopwatch;
/**
* @group time-sensitive
@@ -51,5 +52,6 @@ class TimeDataCollectorTest extends TestCase
$c->collect($request, new Response());
$this->assertEquals(123456000, $c->getStartTime());
$this->assertSame(\class_exists(Stopwatch::class, false), $c->isStopwatchInstalled());
}
}

View File

@@ -31,7 +31,7 @@ class TraceableEventDispatcherTest extends TestCase
$kernel->terminate($request, $response);
$events = $stopwatch->getSectionEvents($response->headers->get('X-Debug-Token'));
$this->assertEquals(array(
$this->assertEquals([
'__section__',
'kernel.request',
'kernel.controller',
@@ -39,13 +39,13 @@ class TraceableEventDispatcherTest extends TestCase
'controller',
'kernel.response',
'kernel.terminate',
), array_keys($events));
], array_keys($events));
}
public function testStopwatchCheckControllerOnRequestEvent()
{
$stopwatch = $this->getMockBuilder('Symfony\Component\Stopwatch\Stopwatch')
->setMethods(array('isStarted'))
->setMethods(['isStarted'])
->getMock();
$stopwatch->expects($this->once())
->method('isStarted')
@@ -61,7 +61,7 @@ class TraceableEventDispatcherTest extends TestCase
public function testStopwatchStopControllerOnRequestEvent()
{
$stopwatch = $this->getMockBuilder('Symfony\Component\Stopwatch\Stopwatch')
->setMethods(array('isStarted', 'stop', 'stopSection'))
->setMethods(['isStarted', 'stop', 'stopSection'])
->getMock();
$stopwatch->expects($this->once())
->method('isStarted')
@@ -114,7 +114,7 @@ class TraceableEventDispatcherTest extends TestCase
$controllerResolver = $this->getMockBuilder('Symfony\Component\HttpKernel\Controller\ControllerResolverInterface')->getMock();
$controllerResolver->expects($this->once())->method('getController')->will($this->returnValue($controller));
$argumentResolver = $this->getMockBuilder('Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface')->getMock();
$argumentResolver->expects($this->once())->method('getArguments')->will($this->returnValue(array()));
$argumentResolver->expects($this->once())->method('getArguments')->will($this->returnValue([]));
return new HttpKernel($dispatcher, $controllerResolver, new RequestStack(), $argumentResolver);
}

View File

@@ -24,76 +24,76 @@ class AddAnnotatedClassesToCachePassTest extends TestCase
$r->setAccessible(true);
$expand = $r->getClosure($pass);
$this->assertSame('Foo', $expand(array('Foo'), array())[0]);
$this->assertSame('Foo', $expand(array('\\Foo'), array())[0]);
$this->assertSame('Foo', $expand(array('Foo'), array('\\Foo'))[0]);
$this->assertSame('Foo', $expand(array('Foo'), array('Foo'))[0]);
$this->assertSame('Foo', $expand(array('\\Foo'), array('\\Foo\\Bar'))[0]);
$this->assertSame('Foo', $expand(array('Foo'), array('\\Foo\\Bar'))[0]);
$this->assertSame('Foo', $expand(array('\\Foo'), array('\\Foo\\Bar\\Acme'))[0]);
$this->assertSame('Foo', $expand(['Foo'], [])[0]);
$this->assertSame('Foo', $expand(['\\Foo'], [])[0]);
$this->assertSame('Foo', $expand(['Foo'], ['\\Foo'])[0]);
$this->assertSame('Foo', $expand(['Foo'], ['Foo'])[0]);
$this->assertSame('Foo', $expand(['\\Foo'], ['\\Foo\\Bar'])[0]);
$this->assertSame('Foo', $expand(['Foo'], ['\\Foo\\Bar'])[0]);
$this->assertSame('Foo', $expand(['\\Foo'], ['\\Foo\\Bar\\Acme'])[0]);
$this->assertSame('Foo\\Bar', $expand(array('Foo\\'), array('\\Foo\\Bar'))[0]);
$this->assertSame('Foo\\Bar\\Acme', $expand(array('Foo\\'), array('\\Foo\\Bar\\Acme'))[0]);
$this->assertEmpty($expand(array('Foo\\'), array('\\Foo')));
$this->assertSame('Foo\\Bar', $expand(['Foo\\'], ['\\Foo\\Bar'])[0]);
$this->assertSame('Foo\\Bar\\Acme', $expand(['Foo\\'], ['\\Foo\\Bar\\Acme'])[0]);
$this->assertEmpty($expand(['Foo\\'], ['\\Foo']));
$this->assertSame('Acme\\Foo\\Bar', $expand(array('**\\Foo\\'), array('\\Acme\\Foo\\Bar'))[0]);
$this->assertEmpty($expand(array('**\\Foo\\'), array('\\Foo\\Bar')));
$this->assertEmpty($expand(array('**\\Foo\\'), array('\\Acme\\Foo')));
$this->assertEmpty($expand(array('**\\Foo\\'), array('\\Foo')));
$this->assertSame('Acme\\Foo\\Bar', $expand(['**\\Foo\\'], ['\\Acme\\Foo\\Bar'])[0]);
$this->assertEmpty($expand(['**\\Foo\\'], ['\\Foo\\Bar']));
$this->assertEmpty($expand(['**\\Foo\\'], ['\\Acme\\Foo']));
$this->assertEmpty($expand(['**\\Foo\\'], ['\\Foo']));
$this->assertSame('Acme\\Foo', $expand(array('**\\Foo'), array('\\Acme\\Foo'))[0]);
$this->assertEmpty($expand(array('**\\Foo'), array('\\Acme\\Foo\\AcmeBundle')));
$this->assertEmpty($expand(array('**\\Foo'), array('\\Acme\\FooBar\\AcmeBundle')));
$this->assertSame('Acme\\Foo', $expand(['**\\Foo'], ['\\Acme\\Foo'])[0]);
$this->assertEmpty($expand(['**\\Foo'], ['\\Acme\\Foo\\AcmeBundle']));
$this->assertEmpty($expand(['**\\Foo'], ['\\Acme\\FooBar\\AcmeBundle']));
$this->assertSame('Foo\\Acme\\Bar', $expand(array('Foo\\*\\Bar'), array('\\Foo\\Acme\\Bar'))[0]);
$this->assertEmpty($expand(array('Foo\\*\\Bar'), array('\\Foo\\Acme\\Bundle\\Bar')));
$this->assertSame('Foo\\Acme\\Bar', $expand(['Foo\\*\\Bar'], ['\\Foo\\Acme\\Bar'])[0]);
$this->assertEmpty($expand(['Foo\\*\\Bar'], ['\\Foo\\Acme\\Bundle\\Bar']));
$this->assertSame('Foo\\Acme\\Bar', $expand(array('Foo\\**\\Bar'), array('\\Foo\\Acme\\Bar'))[0]);
$this->assertSame('Foo\\Acme\\Bundle\\Bar', $expand(array('Foo\\**\\Bar'), array('\\Foo\\Acme\\Bundle\\Bar'))[0]);
$this->assertSame('Foo\\Acme\\Bar', $expand(['Foo\\**\\Bar'], ['\\Foo\\Acme\\Bar'])[0]);
$this->assertSame('Foo\\Acme\\Bundle\\Bar', $expand(['Foo\\**\\Bar'], ['\\Foo\\Acme\\Bundle\\Bar'])[0]);
$this->assertSame('Acme\\Bar', $expand(array('*\\Bar'), array('\\Acme\\Bar'))[0]);
$this->assertEmpty($expand(array('*\\Bar'), array('\\Bar')));
$this->assertEmpty($expand(array('*\\Bar'), array('\\Foo\\Acme\\Bar')));
$this->assertSame('Acme\\Bar', $expand(['*\\Bar'], ['\\Acme\\Bar'])[0]);
$this->assertEmpty($expand(['*\\Bar'], ['\\Bar']));
$this->assertEmpty($expand(['*\\Bar'], ['\\Foo\\Acme\\Bar']));
$this->assertSame('Foo\\Acme\\Bar', $expand(array('**\\Bar'), array('\\Foo\\Acme\\Bar'))[0]);
$this->assertSame('Foo\\Acme\\Bundle\\Bar', $expand(array('**\\Bar'), array('\\Foo\\Acme\\Bundle\\Bar'))[0]);
$this->assertEmpty($expand(array('**\\Bar'), array('\\Bar')));
$this->assertSame('Foo\\Acme\\Bar', $expand(['**\\Bar'], ['\\Foo\\Acme\\Bar'])[0]);
$this->assertSame('Foo\\Acme\\Bundle\\Bar', $expand(['**\\Bar'], ['\\Foo\\Acme\\Bundle\\Bar'])[0]);
$this->assertEmpty($expand(['**\\Bar'], ['\\Bar']));
$this->assertSame('Foo\\Bar', $expand(array('Foo\\*'), array('\\Foo\\Bar'))[0]);
$this->assertEmpty($expand(array('Foo\\*'), array('\\Foo\\Acme\\Bar')));
$this->assertSame('Foo\\Bar', $expand(['Foo\\*'], ['\\Foo\\Bar'])[0]);
$this->assertEmpty($expand(['Foo\\*'], ['\\Foo\\Acme\\Bar']));
$this->assertSame('Foo\\Bar', $expand(array('Foo\\**'), array('\\Foo\\Bar'))[0]);
$this->assertSame('Foo\\Acme\\Bar', $expand(array('Foo\\**'), array('\\Foo\\Acme\\Bar'))[0]);
$this->assertSame('Foo\\Bar', $expand(['Foo\\**'], ['\\Foo\\Bar'])[0]);
$this->assertSame('Foo\\Acme\\Bar', $expand(['Foo\\**'], ['\\Foo\\Acme\\Bar'])[0]);
$this->assertSame(array('Foo\\Bar'), $expand(array('Foo\\*'), array('Foo\\Bar', 'Foo\\BarTest')));
$this->assertSame(array('Foo\\Bar', 'Foo\\BarTest'), $expand(array('Foo\\*', 'Foo\\*Test'), array('Foo\\Bar', 'Foo\\BarTest')));
$this->assertSame(['Foo\\Bar'], $expand(['Foo\\*'], ['Foo\\Bar', 'Foo\\BarTest']));
$this->assertSame(['Foo\\Bar', 'Foo\\BarTest'], $expand(['Foo\\*', 'Foo\\*Test'], ['Foo\\Bar', 'Foo\\BarTest']));
$this->assertSame(
'Acme\\FooBundle\\Controller\\DefaultController',
$expand(array('**Bundle\\Controller\\'), array('\\Acme\\FooBundle\\Controller\\DefaultController'))[0]
$expand(['**Bundle\\Controller\\'], ['\\Acme\\FooBundle\\Controller\\DefaultController'])[0]
);
$this->assertSame(
'FooBundle\\Controller\\DefaultController',
$expand(array('**Bundle\\Controller\\'), array('\\FooBundle\\Controller\\DefaultController'))[0]
$expand(['**Bundle\\Controller\\'], ['\\FooBundle\\Controller\\DefaultController'])[0]
);
$this->assertSame(
'Acme\\FooBundle\\Controller\\Bar\\DefaultController',
$expand(array('**Bundle\\Controller\\'), array('\\Acme\\FooBundle\\Controller\\Bar\\DefaultController'))[0]
$expand(['**Bundle\\Controller\\'], ['\\Acme\\FooBundle\\Controller\\Bar\\DefaultController'])[0]
);
$this->assertSame(
'Bundle\\Controller\\Bar\\DefaultController',
$expand(array('**Bundle\\Controller\\'), array('\\Bundle\\Controller\\Bar\\DefaultController'))[0]
$expand(['**Bundle\\Controller\\'], ['\\Bundle\\Controller\\Bar\\DefaultController'])[0]
);
$this->assertSame(
'Acme\\Bundle\\Controller\\Bar\\DefaultController',
$expand(array('**Bundle\\Controller\\'), array('\\Acme\\Bundle\\Controller\\Bar\\DefaultController'))[0]
$expand(['**Bundle\\Controller\\'], ['\\Acme\\Bundle\\Controller\\Bar\\DefaultController'])[0]
);
$this->assertSame('Foo\\Bar', $expand(array('Foo\\Bar'), array())[0]);
$this->assertSame('Foo\\Acme\\Bar', $expand(array('Foo\\**'), array('\\Foo\\Acme\\Bar'))[0]);
$this->assertSame('Foo\\Bar', $expand(['Foo\\Bar'], [])[0]);
$this->assertSame('Foo\\Acme\\Bar', $expand(['Foo\\**'], ['\\Foo\\Acme\\Bar'])[0]);
}
}

Some files were not shown because too many files have changed in this diff Show More