diff --git a/composer.json b/composer.json
index 45e97455b279b..da8e66b784de0 100644
--- a/composer.json
+++ b/composer.json
@@ -49,7 +49,7 @@
"symfony/polyfill-mbstring": "~1.0",
"symfony/polyfill-php72": "~1.5",
"symfony/polyfill-php73": "^1.11",
- "symfony/polyfill-php80": "^1.15",
+ "symfony/polyfill-php80": "^1.16",
"symfony/polyfill-php81": "^1.22"
},
"replace": {
diff --git a/src/Symfony/Bridge/Doctrine/DependencyInjection/AbstractDoctrineExtension.php b/src/Symfony/Bridge/Doctrine/DependencyInjection/AbstractDoctrineExtension.php
index 41f241f1c0a20..383462ca95ee7 100644
--- a/src/Symfony/Bridge/Doctrine/DependencyInjection/AbstractDoctrineExtension.php
+++ b/src/Symfony/Bridge/Doctrine/DependencyInjection/AbstractDoctrineExtension.php
@@ -228,7 +228,7 @@ protected function registerMappingDrivers($objectManager, ContainerBuilder $cont
]);
}
$mappingDriverDef->setPublic(false);
- if (false !== strpos($mappingDriverDef->getClass(), 'yml') || false !== strpos($mappingDriverDef->getClass(), 'xml')) {
+ if (str_contains($mappingDriverDef->getClass(), 'yml') || str_contains($mappingDriverDef->getClass(), 'xml')) {
$mappingDriverDef->setArguments([array_flip($driverPaths)]);
$mappingDriverDef->addMethodCall('setGlobalBasename', ['mapping']);
}
diff --git a/src/Symfony/Bridge/Doctrine/PropertyInfo/DoctrineExtractor.php b/src/Symfony/Bridge/Doctrine/PropertyInfo/DoctrineExtractor.php
index a0459aa970903..879e87979499c 100644
--- a/src/Symfony/Bridge/Doctrine/PropertyInfo/DoctrineExtractor.php
+++ b/src/Symfony/Bridge/Doctrine/PropertyInfo/DoctrineExtractor.php
@@ -68,7 +68,7 @@ public function getProperties($class, array $context = [])
if ($metadata instanceof ClassMetadataInfo && class_exists(\Doctrine\ORM\Mapping\Embedded::class) && $metadata->embeddedClasses) {
$properties = array_filter($properties, function ($property) {
- return false === strpos($property, '.');
+ return !str_contains($property, '.');
});
$properties = array_merge($properties, array_keys($metadata->embeddedClasses));
diff --git a/src/Symfony/Bridge/Doctrine/Security/User/EntityUserProvider.php b/src/Symfony/Bridge/Doctrine/Security/User/EntityUserProvider.php
index 5dd3889e8eb15..213af6f36a235 100644
--- a/src/Symfony/Bridge/Doctrine/Security/User/EntityUserProvider.php
+++ b/src/Symfony/Bridge/Doctrine/Security/User/EntityUserProvider.php
@@ -144,7 +144,7 @@ private function getClass(): string
if (null === $this->class) {
$class = $this->classOrAlias;
- if (false !== strpos($class, ':')) {
+ if (str_contains($class, ':')) {
$class = $this->getClassMetadata()->getName();
}
diff --git a/src/Symfony/Bridge/Doctrine/Validator/DoctrineLoader.php b/src/Symfony/Bridge/Doctrine/Validator/DoctrineLoader.php
index ca9eb4fab168c..f0f9a95652399 100644
--- a/src/Symfony/Bridge/Doctrine/Validator/DoctrineLoader.php
+++ b/src/Symfony/Bridge/Doctrine/Validator/DoctrineLoader.php
@@ -104,7 +104,7 @@ public function loadClassMetadata(ClassMetadata $metadata): bool
}
if (null === $lengthConstraint) {
- if (isset($mapping['originalClass']) && false === strpos($mapping['declaredField'], '.')) {
+ if (isset($mapping['originalClass']) && !str_contains($mapping['declaredField'], '.')) {
$metadata->addPropertyConstraint($mapping['declaredField'], new Valid());
$loaded = true;
} elseif (property_exists($className, $mapping['fieldName'])) {
diff --git a/src/Symfony/Bridge/Doctrine/composer.json b/src/Symfony/Bridge/Doctrine/composer.json
index 17a83e7d12e7c..0da77033b3334 100644
--- a/src/Symfony/Bridge/Doctrine/composer.json
+++ b/src/Symfony/Bridge/Doctrine/composer.json
@@ -21,6 +21,7 @@
"doctrine/persistence": "^1.3|^2",
"symfony/polyfill-ctype": "~1.8",
"symfony/polyfill-mbstring": "~1.0",
+ "symfony/polyfill-php80": "^1.16",
"symfony/service-contracts": "^1.1|^2"
},
"require-dev": {
diff --git a/src/Symfony/Bridge/Monolog/Command/ServerLogCommand.php b/src/Symfony/Bridge/Monolog/Command/ServerLogCommand.php
index 977be786e5b71..0e5fddc222875 100644
--- a/src/Symfony/Bridge/Monolog/Command/ServerLogCommand.php
+++ b/src/Symfony/Bridge/Monolog/Command/ServerLogCommand.php
@@ -96,7 +96,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
'multiline' => OutputInterface::VERBOSITY_DEBUG <= $output->getVerbosity(),
]));
- if (false === strpos($host = $input->getOption('host'), '://')) {
+ if (!str_contains($host = $input->getOption('host'), '://')) {
$host = 'tcp://'.$host;
}
diff --git a/src/Symfony/Bridge/Monolog/Formatter/ConsoleFormatter.php b/src/Symfony/Bridge/Monolog/Formatter/ConsoleFormatter.php
index d232d68cd9404..4b87c264e4d5a 100644
--- a/src/Symfony/Bridge/Monolog/Formatter/ConsoleFormatter.php
+++ b/src/Symfony/Bridge/Monolog/Formatter/ConsoleFormatter.php
@@ -163,7 +163,7 @@ private function replacePlaceHolder(array $record): array
{
$message = $record['message'];
- if (false === strpos($message, '{')) {
+ if (!str_contains($message, '{')) {
return $record;
}
diff --git a/src/Symfony/Bridge/Monolog/Handler/ServerLogHandler.php b/src/Symfony/Bridge/Monolog/Handler/ServerLogHandler.php
index 4b92b088f7dac..8101178d66c03 100644
--- a/src/Symfony/Bridge/Monolog/Handler/ServerLogHandler.php
+++ b/src/Symfony/Bridge/Monolog/Handler/ServerLogHandler.php
@@ -32,7 +32,7 @@ public function __construct(string $host, $level = Logger::DEBUG, bool $bubble =
{
parent::__construct($level, $bubble);
- if (false === strpos($host, '://')) {
+ if (!str_contains($host, '://')) {
$host = 'tcp://'.$host;
}
diff --git a/src/Symfony/Bridge/Monolog/composer.json b/src/Symfony/Bridge/Monolog/composer.json
index fee9fe256ab73..613b619b450ed 100644
--- a/src/Symfony/Bridge/Monolog/composer.json
+++ b/src/Symfony/Bridge/Monolog/composer.json
@@ -19,7 +19,8 @@
"php": ">=7.1.3",
"monolog/monolog": "^1.25.1",
"symfony/service-contracts": "^1.1|^2",
- "symfony/http-kernel": "^4.3"
+ "symfony/http-kernel": "^4.3",
+ "symfony/polyfill-php80": "^1.16"
},
"require-dev": {
"symfony/console": "^3.4|^4.0|^5.0",
diff --git a/src/Symfony/Bridge/ProxyManager/LazyProxy/PhpDumper/LazyLoadingValueHolderGenerator.php b/src/Symfony/Bridge/ProxyManager/LazyProxy/PhpDumper/LazyLoadingValueHolderGenerator.php
index 141147a64c00b..d665070f02454 100644
--- a/src/Symfony/Bridge/ProxyManager/LazyProxy/PhpDumper/LazyLoadingValueHolderGenerator.php
+++ b/src/Symfony/Bridge/ProxyManager/LazyProxy/PhpDumper/LazyLoadingValueHolderGenerator.php
@@ -28,12 +28,12 @@ public function generate(\ReflectionClass $originalClass, ClassGenerator $classG
parent::generate($originalClass, $classGenerator, $proxyOptions);
foreach ($classGenerator->getMethods() as $method) {
- if (0 === strpos($originalClass->getFilename(), __FILE__)) {
+ if (str_starts_with($originalClass->getFilename(), __FILE__)) {
$method->setBody(str_replace(var_export($originalClass->name, true), '__CLASS__', $method->getBody()));
}
}
- if (0 === strpos($originalClass->getFilename(), __FILE__)) {
+ if (str_starts_with($originalClass->getFilename(), __FILE__)) {
$interfaces = $classGenerator->getImplementedInterfaces();
array_pop($interfaces);
$classGenerator->setImplementedInterfaces(array_merge($interfaces, $originalClass->getInterfaceNames()));
diff --git a/src/Symfony/Bridge/ProxyManager/composer.json b/src/Symfony/Bridge/ProxyManager/composer.json
index c96e2b7b772fc..09692b8c89d74 100644
--- a/src/Symfony/Bridge/ProxyManager/composer.json
+++ b/src/Symfony/Bridge/ProxyManager/composer.json
@@ -19,7 +19,8 @@
"php": ">=7.1.3",
"composer/package-versions-deprecated": "^1.8",
"friendsofphp/proxy-manager-lts": "^1.0.2",
- "symfony/dependency-injection": "^4.0|^5.0"
+ "symfony/dependency-injection": "^4.0|^5.0",
+ "symfony/polyfill-php80": "^1.16"
},
"require-dev": {
"symfony/config": "^3.4|^4.0|^5.0"
diff --git a/src/Symfony/Bridge/Twig/Command/DebugCommand.php b/src/Symfony/Bridge/Twig/Command/DebugCommand.php
index 966532b422f43..a6a1e9a2cebde 100644
--- a/src/Symfony/Bridge/Twig/Command/DebugCommand.php
+++ b/src/Symfony/Bridge/Twig/Command/DebugCommand.php
@@ -225,7 +225,7 @@ private function displayGeneralText(SymfonyStyle $io, string $filter = null)
foreach ($types as $index => $type) {
$items = [];
foreach ($this->twig->{'get'.ucfirst($type)}() as $name => $entity) {
- if (!$filter || false !== strpos($name, $filter)) {
+ if (!$filter || str_contains($name, $filter)) {
$items[$name] = $name.$this->getPrettyMetadata($type, $entity, $decorated);
}
}
@@ -259,7 +259,7 @@ private function displayGeneralJson(SymfonyStyle $io, ?string $filter)
$data = [];
foreach ($types as $type) {
foreach ($this->twig->{'get'.ucfirst($type)}() as $name => $entity) {
- if (!$filter || false !== strpos($name, $filter)) {
+ if (!$filter || str_contains($name, $filter)) {
$data[$type][$name] = $this->getMetadata($type, $entity);
}
}
@@ -409,7 +409,7 @@ private function findWrongBundleOverrides(): array
$folders = glob($this->rootDir.'/Resources/*/views', \GLOB_ONLYDIR);
$relativePath = ltrim(substr($this->rootDir.\DIRECTORY_SEPARATOR.'Resources/', \strlen($this->projectDir)), \DIRECTORY_SEPARATOR);
$bundleNames = array_reduce($folders, function ($carry, $absolutePath) use ($relativePath) {
- if (0 === strpos($absolutePath, $this->projectDir)) {
+ if (str_starts_with($absolutePath, $this->projectDir)) {
$name = basename(\dirname($absolutePath));
$path = ltrim($relativePath.$name, \DIRECTORY_SEPARATOR);
$carry[$name] = $path;
@@ -425,7 +425,7 @@ private function findWrongBundleOverrides(): array
$folders = glob($this->twigDefaultPath.'/bundles/*', \GLOB_ONLYDIR);
$relativePath = ltrim(substr($this->twigDefaultPath.'/bundles/', \strlen($this->projectDir)), \DIRECTORY_SEPARATOR);
$bundleNames = array_reduce($folders, function ($carry, $absolutePath) use ($relativePath) {
- if (0 === strpos($absolutePath, $this->projectDir)) {
+ if (str_starts_with($absolutePath, $this->projectDir)) {
$name = basename($absolutePath);
$path = ltrim($relativePath.$name, \DIRECTORY_SEPARATOR);
$carry[$name] = $path;
@@ -555,7 +555,7 @@ private function findAlternatives(string $name, array $collection): array
$alternatives = [];
foreach ($collection as $item) {
$lev = levenshtein($name, $item);
- if ($lev <= \strlen($name) / 3 || false !== strpos($item, $name)) {
+ if ($lev <= \strlen($name) / 3 || str_contains($item, $name)) {
$alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev : $lev;
}
}
@@ -569,7 +569,7 @@ private function findAlternatives(string $name, array $collection): array
private function getRelativePath(string $path): string
{
- if (null !== $this->projectDir && 0 === strpos($path, $this->projectDir)) {
+ if (null !== $this->projectDir && str_starts_with($path, $this->projectDir)) {
return ltrim(substr($path, \strlen($this->projectDir)), \DIRECTORY_SEPARATOR);
}
diff --git a/src/Symfony/Bridge/Twig/Extension/CodeExtension.php b/src/Symfony/Bridge/Twig/Extension/CodeExtension.php
index 7f60b542bff40..54b43caca2cb3 100644
--- a/src/Symfony/Bridge/Twig/Extension/CodeExtension.php
+++ b/src/Symfony/Bridge/Twig/Extension/CodeExtension.php
@@ -71,7 +71,7 @@ public function abbrClass($class)
public function abbrMethod($method)
{
- if (false !== strpos($method, '::')) {
+ if (str_contains($method, '::')) {
[$class, $method] = explode('::', $method, 2);
$result = sprintf('%s::%s()', $this->abbrClass($class), $method);
} elseif ('Closure' === $method) {
@@ -219,7 +219,7 @@ public function getFileRelative(string $file): ?string
{
$file = str_replace('\\', '/', $file);
- if (null !== $this->projectDir && 0 === strpos($file, $this->projectDir)) {
+ if (null !== $this->projectDir && str_starts_with($file, $this->projectDir)) {
return ltrim(substr($file, \strlen($this->projectDir)), '/');
}
@@ -238,7 +238,7 @@ public function formatFileFromText($text)
*/
public function formatLogMessage(string $message, array $context): string
{
- if ($context && false !== strpos($message, '{')) {
+ if ($context && str_contains($message, '{')) {
$replacements = [];
foreach ($context as $key => $val) {
if (is_scalar($val)) {
diff --git a/src/Symfony/Bridge/Twig/composer.json b/src/Symfony/Bridge/Twig/composer.json
index 3fbb6b7eb4afd..14c737127e13b 100644
--- a/src/Symfony/Bridge/Twig/composer.json
+++ b/src/Symfony/Bridge/Twig/composer.json
@@ -17,6 +17,7 @@
],
"require": {
"php": ">=7.1.3",
+ "symfony/polyfill-php80": "^1.16",
"symfony/translation-contracts": "^1.1|^2",
"twig/twig": "^1.43|^2.13|^3.0.4"
},
diff --git a/src/Symfony/Bundle/DebugBundle/DependencyInjection/DebugExtension.php b/src/Symfony/Bundle/DebugBundle/DependencyInjection/DebugExtension.php
index 2528cce5b83a7..7b8e6234709da 100644
--- a/src/Symfony/Bundle/DebugBundle/DependencyInjection/DebugExtension.php
+++ b/src/Symfony/Bundle/DebugBundle/DependencyInjection/DebugExtension.php
@@ -59,7 +59,7 @@ public function load(array $configs, ContainerBuilder $container)
$container->getDefinition('var_dumper.command.server_dump')
->setClass(ServerDumpPlaceholderCommand::class)
;
- } elseif (0 === strpos($config['dump_destination'], 'tcp://')) {
+ } elseif (str_starts_with($config['dump_destination'], 'tcp://')) {
$container->getDefinition('debug.dump_listener')
->replaceArgument(2, new Reference('var_dumper.server_connection'))
;
diff --git a/src/Symfony/Bundle/DebugBundle/composer.json b/src/Symfony/Bundle/DebugBundle/composer.json
index 6837f656ae163..bae6358b2c005 100644
--- a/src/Symfony/Bundle/DebugBundle/composer.json
+++ b/src/Symfony/Bundle/DebugBundle/composer.json
@@ -19,6 +19,7 @@
"php": ">=7.1.3",
"ext-xml": "*",
"symfony/http-kernel": "^3.4|^4.0|^5.0",
+ "symfony/polyfill-php80": "^1.16",
"symfony/twig-bridge": "^3.4|^4.0|^5.0",
"symfony/var-dumper": "^4.1.1|^5.0"
},
diff --git a/src/Symfony/Bundle/FrameworkBundle/Client.php b/src/Symfony/Bundle/FrameworkBundle/Client.php
index ee95a9ae7b793..174b024e21c79 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Client.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Client.php
@@ -167,7 +167,7 @@ protected function getScript($request)
$requires = '';
foreach (get_declared_classes() as $class) {
- if (0 === strpos($class, 'ComposerAutoloaderInit')) {
+ if (str_starts_with($class, 'ComposerAutoloaderInit')) {
$r = new \ReflectionClass($class);
$file = \dirname($r->getFileName(), 2).'/autoload.php';
if (file_exists($file)) {
diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php
index d396b3543b317..908858019b371 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php
@@ -142,7 +142,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
}
$mount = implode(' ', $mount).'/';
- if (0 === strpos($realCacheDir, $mount)) {
+ if (str_starts_with($realCacheDir, $mount)) {
$io->note('For better performances, you should move the cache and log directories to a non-shared folder of the VM.');
$oldCacheDir = false;
break;
diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/ContainerDebugCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/ContainerDebugCommand.php
index 668205287097c..c75ba398a67a4 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Command/ContainerDebugCommand.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Command/ContainerDebugCommand.php
@@ -270,7 +270,7 @@ private function findServiceIdsContaining(ContainerBuilder $builder, string $nam
$serviceIds = $builder->getServiceIds();
$foundServiceIds = $foundServiceIdsIgnoringBackslashes = [];
foreach ($serviceIds as $serviceId) {
- if (!$showHidden && 0 === strpos($serviceId, '.')) {
+ if (!$showHidden && str_starts_with($serviceId, '.')) {
continue;
}
if (false !== stripos(str_replace('\\', '', $serviceId), $name)) {
@@ -295,7 +295,7 @@ public function filterToServiceTypes(string $serviceId): bool
}
// if the id has a \, assume it is a class
- if (false !== strpos($serviceId, '\\')) {
+ if (str_contains($serviceId, '\\')) {
return true;
}
diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/ContainerLintCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/ContainerLintCommand.php
index e89a1273c3407..8225825ae360d 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Command/ContainerLintCommand.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Command/ContainerLintCommand.php
@@ -104,7 +104,7 @@ private function getContainerBuilder(): ContainerBuilder
$skippedIds = [];
foreach ($container->getServiceIds() as $serviceId) {
- if (0 === strpos($serviceId, '.errored.')) {
+ if (str_starts_with($serviceId, '.errored.')) {
$skippedIds[$serviceId] = true;
}
}
diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/DebugAutowiringCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/DebugAutowiringCommand.php
index 79ac2dd8f8c98..b5023749a3078 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Command/DebugAutowiringCommand.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Command/DebugAutowiringCommand.php
@@ -80,7 +80,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
if ($search = $input->getArgument('search')) {
$serviceIds = array_filter($serviceIds, function ($serviceId) use ($search) {
- return false !== stripos(str_replace('\\', '', $serviceId), $search) && 0 !== strpos($serviceId, '.');
+ return false !== stripos(str_replace('\\', '', $serviceId), $search) && !str_starts_with($serviceId, '.');
});
if (empty($serviceIds)) {
@@ -104,7 +104,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
foreach ($serviceIds as $serviceId) {
$text = [];
$resolvedServiceId = $serviceId;
- if (0 !== strpos($serviceId, $previousId)) {
+ if (!str_starts_with($serviceId, $previousId)) {
$text[] = '';
if ('' !== $description = Descriptor::getClassDescription($serviceId, $resolvedServiceId)) {
if (isset($hasAlias[$serviceId])) {
diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/XliffLintCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/XliffLintCommand.php
index 0b5bb061d66e2..a52177acc0471 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Command/XliffLintCommand.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Command/XliffLintCommand.php
@@ -37,7 +37,7 @@ public function __construct()
};
$isReadableProvider = function ($fileOrDirectory, $default) {
- return 0 === strpos($fileOrDirectory, '@') || $default($fileOrDirectory);
+ return str_starts_with($fileOrDirectory, '@') || $default($fileOrDirectory);
};
parent::__construct(null, $directoryIteratorProvider, $isReadableProvider);
diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/YamlLintCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/YamlLintCommand.php
index 1163ff1c28fb1..86787361aa274 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Command/YamlLintCommand.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Command/YamlLintCommand.php
@@ -36,7 +36,7 @@ public function __construct()
};
$isReadableProvider = function ($fileOrDirectory, $default) {
- return 0 === strpos($fileOrDirectory, '@') || $default($fileOrDirectory);
+ return str_starts_with($fileOrDirectory, '@') || $default($fileOrDirectory);
};
parent::__construct(null, $directoryIteratorProvider, $isReadableProvider);
diff --git a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/JsonDescriptor.php b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/JsonDescriptor.php
index 039b3bd4f4c48..038ba3313d2e4 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/JsonDescriptor.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/JsonDescriptor.php
@@ -286,7 +286,7 @@ private function getCallableData($callable): array
$data['name'] = $callable[1];
$data['class'] = \get_class($callable[0]);
} else {
- if (0 !== strpos($callable[1], 'parent::')) {
+ if (!str_starts_with($callable[1], 'parent::')) {
$data['name'] = $callable[1];
$data['class'] = $callable[0];
$data['static'] = true;
@@ -304,7 +304,7 @@ private function getCallableData($callable): array
if (\is_string($callable)) {
$data['type'] = 'function';
- if (false === strpos($callable, '::')) {
+ if (!str_contains($callable, '::')) {
$data['name'] = $callable;
} else {
$callableParts = explode('::', $callable);
@@ -321,7 +321,7 @@ private function getCallableData($callable): array
$data['type'] = 'closure';
$r = new \ReflectionFunction($callable);
- if (false !== strpos($r->name, '{closure}')) {
+ if (str_contains($r->name, '{closure}')) {
return $data;
}
$data['name'] = $r->name;
diff --git a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/MarkdownDescriptor.php b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/MarkdownDescriptor.php
index 53485437a354a..a2360a094ee9a 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/MarkdownDescriptor.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/MarkdownDescriptor.php
@@ -300,7 +300,7 @@ protected function describeCallable($callable, array $options = [])
$string .= "\n".sprintf('- Name: `%s`', $callable[1]);
$string .= "\n".sprintf('- Class: `%s`', \get_class($callable[0]));
} else {
- if (0 !== strpos($callable[1], 'parent::')) {
+ if (!str_starts_with($callable[1], 'parent::')) {
$string .= "\n".sprintf('- Name: `%s`', $callable[1]);
$string .= "\n".sprintf('- Class: `%s`', $callable[0]);
$string .= "\n- Static: yes";
@@ -318,7 +318,7 @@ protected function describeCallable($callable, array $options = [])
if (\is_string($callable)) {
$string .= "\n- Type: `function`";
- if (false === strpos($callable, '::')) {
+ if (!str_contains($callable, '::')) {
$string .= "\n".sprintf('- Name: `%s`', $callable);
} else {
$callableParts = explode('::', $callable);
@@ -335,7 +335,7 @@ protected function describeCallable($callable, array $options = [])
$string .= "\n- Type: `closure`";
$r = new \ReflectionFunction($callable);
- if (false !== strpos($r->name, '{closure}')) {
+ if (str_contains($r->name, '{closure}')) {
return $this->write($string."\n");
}
$string .= "\n".sprintf('- Name: `%s`', $r->name);
diff --git a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/TextDescriptor.php b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/TextDescriptor.php
index c0cd375a94221..f287467d8221b 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/TextDescriptor.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/TextDescriptor.php
@@ -514,7 +514,7 @@ private function formatControllerLink($controller, string $anchorText): string
$r = new \ReflectionMethod($controller, '__invoke');
} elseif (!\is_string($controller)) {
return $anchorText;
- } elseif (false !== strpos($controller, '::')) {
+ } elseif (str_contains($controller, '::')) {
$r = new \ReflectionMethod($controller);
} else {
$r = new \ReflectionFunction($controller);
@@ -547,7 +547,7 @@ private function formatCallable($callable): string
if ($callable instanceof \Closure) {
$r = new \ReflectionFunction($callable);
- if (false !== strpos($r->name, '{closure}')) {
+ if (str_contains($r->name, '{closure}')) {
return 'Closure()';
}
if ($class = $r->getClosureScopeClass()) {
diff --git a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/XmlDescriptor.php b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/XmlDescriptor.php
index 2d56bbf0e25dc..66c441f14e069 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/XmlDescriptor.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/XmlDescriptor.php
@@ -469,7 +469,7 @@ private function getCallableDocument($callable): \DOMDocument
$callableXML->setAttribute('name', $callable[1]);
$callableXML->setAttribute('class', \get_class($callable[0]));
} else {
- if (0 !== strpos($callable[1], 'parent::')) {
+ if (!str_starts_with($callable[1], 'parent::')) {
$callableXML->setAttribute('name', $callable[1]);
$callableXML->setAttribute('class', $callable[0]);
$callableXML->setAttribute('static', 'true');
@@ -487,7 +487,7 @@ private function getCallableDocument($callable): \DOMDocument
if (\is_string($callable)) {
$callableXML->setAttribute('type', 'function');
- if (false === strpos($callable, '::')) {
+ if (!str_contains($callable, '::')) {
$callableXML->setAttribute('name', $callable);
} else {
$callableParts = explode('::', $callable);
@@ -504,7 +504,7 @@ private function getCallableDocument($callable): \DOMDocument
$callableXML->setAttribute('type', 'closure');
$r = new \ReflectionFunction($callable);
- if (false !== strpos($r->name, '{closure}')) {
+ if (str_contains($r->name, '{closure}')) {
return $dom;
}
$callableXML->setAttribute('name', $r->name);
diff --git a/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerNameParser.php b/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerNameParser.php
index 30668f8585536..34e4382ad8f96 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerNameParser.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerNameParser.php
@@ -107,7 +107,7 @@ public function build($controller)
$controllerName = $match[2];
$actionName = $match[3];
foreach ($this->kernel->getBundles() as $name => $bundle) {
- if (0 !== strpos($className, $bundle->getNamespace())) {
+ if (!str_starts_with($className, $bundle->getNamespace())) {
continue;
}
@@ -130,7 +130,7 @@ private function findAlternative(string $nonExistentBundleName): ?string
$shortest = null;
foreach ($bundleNames as $bundleName) {
// if there's a partial match, return it immediately
- if (false !== strpos($bundleName, $nonExistentBundleName)) {
+ if (str_contains($bundleName, $nonExistentBundleName)) {
return $bundleName;
}
diff --git a/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerResolver.php b/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerResolver.php
index 3c746b996ee9f..2883c80b1b0ba 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerResolver.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerResolver.php
@@ -51,7 +51,7 @@ public function __construct(ContainerInterface $container, $logger = null)
*/
protected function createController($controller)
{
- if ($this->parser && false === strpos($controller, '::') && 2 === substr_count($controller, ':')) {
+ if ($this->parser && !str_contains($controller, '::') && 2 === substr_count($controller, ':')) {
// controller in the a:b:c notation then
$deprecatedNotation = $controller;
$controller = $this->parser->parse($deprecatedNotation, false);
diff --git a/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php b/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php
index bbbdd9b1dd882..109e83b6967ba 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php
@@ -128,7 +128,7 @@ public function urlRedirectAction(Request $request, string $path, bool $permanen
}
if ($qs = $request->server->get('QUERY_STRING') ?: $request->getQueryString()) {
- if (false === strpos($path, '?')) {
+ if (!str_contains($path, '?')) {
$qs = '?'.$qs;
} else {
$qs = '&'.$qs;
diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/UnusedTagsPass.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/UnusedTagsPass.php
index fa5744a7f5e09..888a5ea8d64c1 100644
--- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/UnusedTagsPass.php
+++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/UnusedTagsPass.php
@@ -99,7 +99,7 @@ public function process(ContainerBuilder $container)
continue;
}
- if (false !== strpos($definedTag, $tag) || levenshtein($tag, $definedTag) <= \strlen($tag) / 3) {
+ if (str_contains($definedTag, $tag) || levenshtein($tag, $definedTag) <= \strlen($tag) / 3) {
$candidates[] = $definedTag;
}
}
diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php
index e63b10115cc14..cd9037e7c9fdc 100644
--- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php
+++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php
@@ -1266,7 +1266,7 @@ private function registerTranslatorConfiguration(array $config, ContainerBuilder
'scanned_directories' => $scannedDirectories = array_merge($dirs, $nonExistingDirs),
'cache_vary' => [
'scanned_directories' => array_map(static function (string $dir) use ($projectDir): string {
- return 0 === strpos($dir, $projectDir.'/') ? substr($dir, 1 + \strlen($projectDir)) : $dir;
+ return str_starts_with($dir, $projectDir.'/') ? substr($dir, 1 + \strlen($projectDir)) : $dir;
}, $scannedDirectories),
],
]
diff --git a/src/Symfony/Bundle/FrameworkBundle/EventListener/ResolveControllerNameSubscriber.php b/src/Symfony/Bundle/FrameworkBundle/EventListener/ResolveControllerNameSubscriber.php
index 1cd2abef4d0c8..ef146419013bc 100644
--- a/src/Symfony/Bundle/FrameworkBundle/EventListener/ResolveControllerNameSubscriber.php
+++ b/src/Symfony/Bundle/FrameworkBundle/EventListener/ResolveControllerNameSubscriber.php
@@ -55,7 +55,7 @@ public function __call(string $method, array $args)
$event = $args[0];
$controller = $event->getRequest()->attributes->get('_controller');
- if (\is_string($controller) && false === strpos($controller, '::') && 2 === substr_count($controller, ':')) {
+ if (\is_string($controller) && !str_contains($controller, '::') && 2 === substr_count($controller, ':')) {
// controller in the a:b:c notation then
$event->getRequest()->attributes->set('_controller', $parsedNotation = $this->parser->parse($controller, false));
diff --git a/src/Symfony/Bundle/FrameworkBundle/Routing/DelegatingLoader.php b/src/Symfony/Bundle/FrameworkBundle/Routing/DelegatingLoader.php
index 47ca299e54f4b..7276a387d4e01 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Routing/DelegatingLoader.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Routing/DelegatingLoader.php
@@ -95,7 +95,7 @@ public function load($resource, $type = null)
continue;
}
- if (false !== strpos($controller, '::')) {
+ if (str_contains($controller, '::')) {
continue;
}
diff --git a/src/Symfony/Bundle/FrameworkBundle/Secrets/DotenvVault.php b/src/Symfony/Bundle/FrameworkBundle/Secrets/DotenvVault.php
index a64a7449b2cae..3c1670feae02d 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Secrets/DotenvVault.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Secrets/DotenvVault.php
@@ -54,7 +54,7 @@ public function reveal(string $name): ?string
{
$this->lastMessage = null;
$this->validateName($name);
- $v = \is_string($_SERVER[$name] ?? null) && 0 !== strpos($name, 'HTTP_') ? $_SERVER[$name] : ($_ENV[$name] ?? null);
+ $v = \is_string($_SERVER[$name] ?? null) && !str_starts_with($name, 'HTTP_') ? $_SERVER[$name] : ($_ENV[$name] ?? null);
if (null === $v) {
$this->lastMessage = sprintf('Secret "%s" not found in "%s".', $name, $this->getPrettyPath($this->dotenvFile));
diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/CodeHelper.php b/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/CodeHelper.php
index d62126765d5ed..427bd41d0dee8 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/CodeHelper.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/CodeHelper.php
@@ -63,7 +63,7 @@ public function abbrClass($class)
public function abbrMethod($method)
{
- if (false !== strpos($method, '::')) {
+ if (str_contains($method, '::')) {
[$class, $method] = explode('::', $method, 2);
$result = sprintf('%s::%s()', $this->abbrClass($class), $method);
} elseif ('Closure' === $method) {
@@ -164,7 +164,7 @@ public function formatFile($file, $line, $text = null)
if (null === $text) {
$file = trim($file);
$fileStr = $file;
- if (0 === strpos($fileStr, $this->rootDir)) {
+ if (str_starts_with($fileStr, $this->rootDir)) {
$fileStr = str_replace(['\\', $this->rootDir], ['/', ''], $fileStr);
$fileStr = htmlspecialchars($fileStr, $flags, $this->charset);
$fileStr = sprintf('kernel.project_dir/%s', htmlspecialchars($this->rootDir, $flags, $this->charset), $fileStr);
diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/TemplateNameParser.php b/src/Symfony/Bundle/FrameworkBundle/Templating/TemplateNameParser.php
index 7dbdba3857689..e553b85f03ffa 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Templating/TemplateNameParser.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Templating/TemplateNameParser.php
@@ -50,11 +50,11 @@ public function parse($name)
// normalize name
$name = preg_replace('#/{2,}#', '/', str_replace('\\', '/', $name));
- if (false !== strpos($name, '..')) {
+ if (str_contains($name, '..')) {
throw new \RuntimeException(sprintf('Template name "%s" contains invalid characters.', $name));
}
- if (!preg_match('/^(?:([^:]*):([^:]*):)?(.+)\.([^\.]+)\.([^\.]+)$/', $name, $matches) || 0 === strpos($name, '@')) {
+ if (!preg_match('/^(?:([^:]*):([^:]*):)?(.+)\.([^\.]+)\.([^\.]+)$/', $name, $matches) || str_starts_with($name, '@')) {
return parent::parse($name);
}
diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/CachePoolsTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/CachePoolsTest.php
index fc5d64f4d2fed..b7f29a0857852 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/CachePoolsTest.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/CachePoolsTest.php
@@ -35,12 +35,12 @@ public function testRedisCachePools()
try {
$this->doTestCachePools(['root_config' => 'redis_config.yml', 'environment' => 'redis_cache'], RedisAdapter::class);
} catch (\PHPUnit\Framework\Error\Warning $e) {
- if (0 !== strpos($e->getMessage(), 'unable to connect to')) {
+ if (!str_starts_with($e->getMessage(), 'unable to connect to')) {
throw $e;
}
$this->markTestSkipped($e->getMessage());
} catch (InvalidArgumentException $e) {
- if (0 !== strpos($e->getMessage(), 'Redis connection ')) {
+ if (!str_starts_with($e->getMessage(), 'Redis connection ')) {
throw $e;
}
$this->markTestSkipped($e->getMessage());
@@ -58,7 +58,7 @@ public function testRedisCustomCachePools()
try {
$this->doTestCachePools(['root_config' => 'redis_custom_config.yml', 'environment' => 'custom_redis_cache'], RedisAdapter::class);
} catch (\PHPUnit\Framework\Error\Warning $e) {
- if (0 !== strpos($e->getMessage(), 'unable to connect to')) {
+ if (!str_starts_with($e->getMessage(), 'unable to connect to')) {
throw $e;
}
$this->markTestSkipped($e->getMessage());
diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/MainConfiguration.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/MainConfiguration.php
index a01c97b881aa7..da2cc10c96493 100644
--- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/MainConfiguration.php
+++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/MainConfiguration.php
@@ -226,7 +226,7 @@ private function addFirewallsSection(ArrayNodeDefinition $rootNode, array $facto
->beforeNormalization()
->ifArray()->then(function ($v) {
foreach ($v as $originalName => $cookieConfig) {
- if (false !== strpos($originalName, '-')) {
+ if (str_contains($originalName, '-')) {
$normalizedName = str_replace('-', '_', $originalName);
@trigger_error(sprintf('Normalization of cookie names is deprecated since Symfony 4.3. Starting from Symfony 5.0, the "%s" cookie configured in "logout.delete_cookies" will delete the "%s" cookie instead of the "%s" cookie.', $originalName, $originalName, $normalizedName), \E_USER_DEPRECATED);
@@ -304,7 +304,7 @@ private function addFirewallsSection(ArrayNodeDefinition $rootNode, array $facto
continue;
}
- if (false !== strpos($firewall[$k]['check_path'], '/') && !preg_match('#'.$firewall['pattern'].'#', $firewall[$k]['check_path'])) {
+ if (str_contains($firewall[$k]['check_path'], '/') && !preg_match('#'.$firewall['pattern'].'#', $firewall[$k]['check_path'])) {
throw new \LogicException(sprintf('The check_path "%s" for login method "%s" is not matched by the firewall pattern "%s".', $firewall[$k]['check_path'], $k, $firewall['pattern']));
}
}
diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php
index 1ccb9aacaeccb..b3cfbb9f88d71 100644
--- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php
+++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php
@@ -42,7 +42,7 @@ public function testUserProviders()
{
$container = $this->getContainer('container1');
- $providers = array_values(array_filter($container->getServiceIds(), function ($key) { return 0 === strpos($key, 'security.user.provider.concrete'); }));
+ $providers = array_values(array_filter($container->getServiceIds(), function ($key) { return str_starts_with($key, 'security.user.provider.concrete'); }));
$expectedProviders = [
'security.user.provider.concrete.default',
diff --git a/src/Symfony/Bundle/SecurityBundle/composer.json b/src/Symfony/Bundle/SecurityBundle/composer.json
index eb0ac43064c10..1106acfa008c6 100644
--- a/src/Symfony/Bundle/SecurityBundle/composer.json
+++ b/src/Symfony/Bundle/SecurityBundle/composer.json
@@ -21,6 +21,7 @@
"symfony/config": "^4.2|^5.0",
"symfony/dependency-injection": "^4.4|^5.0",
"symfony/http-kernel": "^4.4",
+ "symfony/polyfill-php80": "^1.16",
"symfony/security-core": "^4.4",
"symfony/security-csrf": "^4.2|^5.0",
"symfony/security-guard": "^4.2|^5.0",
diff --git a/src/Symfony/Bundle/TwigBundle/Command/LintCommand.php b/src/Symfony/Bundle/TwigBundle/Command/LintCommand.php
index 386653eb22d90..cb72bc4bf78a8 100644
--- a/src/Symfony/Bundle/TwigBundle/Command/LintCommand.php
+++ b/src/Symfony/Bundle/TwigBundle/Command/LintCommand.php
@@ -44,7 +44,7 @@ protected function configure()
protected function findFiles($filename): iterable
{
- if (0 === strpos($filename, '@')) {
+ if (str_starts_with($filename, '@')) {
$dir = $this->getApplication()->getKernel()->locateResource($filename);
return Finder::create()->files()->in($dir)->name('*.twig');
diff --git a/src/Symfony/Bundle/TwigBundle/DependencyInjection/Compiler/TwigEnvironmentPass.php b/src/Symfony/Bundle/TwigBundle/DependencyInjection/Compiler/TwigEnvironmentPass.php
index a17d3facb676c..45413dc93253d 100644
--- a/src/Symfony/Bundle/TwigBundle/DependencyInjection/Compiler/TwigEnvironmentPass.php
+++ b/src/Symfony/Bundle/TwigBundle/DependencyInjection/Compiler/TwigEnvironmentPass.php
@@ -43,7 +43,7 @@ public function process(ContainerBuilder $container)
$methodCall = ['addExtension', [$extension]];
$extensionClass = $container->getDefinition((string) $extension)->getClass();
- if (\is_string($extensionClass) && 0 === strpos($extensionClass, 'Symfony\Bridge\Twig\Extension')) {
+ if (\is_string($extensionClass) && str_starts_with($extensionClass, 'Symfony\Bridge\Twig\Extension')) {
$twigBridgeExtensionsMethodCalls[] = $methodCall;
} else {
$othersExtensionsMethodCalls[] = $methodCall;
diff --git a/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php
index cf0a70fc30186..3ec4bc3f1e3c5 100644
--- a/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php
+++ b/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php
@@ -92,9 +92,9 @@ private function addGlobalsSection(ArrayNodeDefinition $rootNode)
->prototype('array')
->normalizeKeys(false)
->beforeNormalization()
- ->ifTrue(function ($v) { return \is_string($v) && 0 === strpos($v, '@'); })
+ ->ifTrue(function ($v) { return \is_string($v) && str_starts_with($v, '@'); })
->then(function ($v) {
- if (0 === strpos($v, '@@')) {
+ if (str_starts_with($v, '@@')) {
return substr($v, 1);
}
diff --git a/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/TwigExtensionTest.php b/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/TwigExtensionTest.php
index 2abf9fb6e6f2f..84f08949c7248 100644
--- a/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/TwigExtensionTest.php
+++ b/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/TwigExtensionTest.php
@@ -186,7 +186,7 @@ public function testTwigLoaderPaths($format)
$def = $container->getDefinition('twig.loader.native_filesystem');
$paths = [];
foreach ($def->getMethodCalls() as $call) {
- if ('addPath' === $call[0] && false === strpos($call[1][0], 'Form')) {
+ if ('addPath' === $call[0] && !str_contains($call[1][0], 'Form')) {
$paths[] = $call[1];
}
}
@@ -221,7 +221,7 @@ public function testLegacyTwigLoaderPaths($format)
$def = $container->getDefinition('twig.loader.native_filesystem');
$paths = [];
foreach ($def->getMethodCalls() as $call) {
- if ('addPath' === $call[0] && false === strpos($call[1][0], 'Form')) {
+ if ('addPath' === $call[0] && !str_contains($call[1][0], 'Form')) {
$paths[] = $call[1];
}
}
diff --git a/src/Symfony/Bundle/WebProfilerBundle/EventListener/WebDebugToolbarListener.php b/src/Symfony/Bundle/WebProfilerBundle/EventListener/WebDebugToolbarListener.php
index a681f5d2427a6..cb47ff7398553 100644
--- a/src/Symfony/Bundle/WebProfilerBundle/EventListener/WebDebugToolbarListener.php
+++ b/src/Symfony/Bundle/WebProfilerBundle/EventListener/WebDebugToolbarListener.php
@@ -101,7 +101,7 @@ public function onKernelResponse(FilterResponseEvent $event)
if (self::DISABLED === $this->mode
|| !$response->headers->has('X-Debug-Token')
|| $response->isRedirection()
- || ($response->headers->has('Content-Type') && false === strpos($response->headers->get('Content-Type'), 'html'))
+ || ($response->headers->has('Content-Type') && !str_contains($response->headers->get('Content-Type'), 'html'))
|| 'html' !== $request->getRequestFormat()
|| false !== stripos($response->headers->get('Content-Disposition', ''), 'attachment;')
) {
diff --git a/src/Symfony/Bundle/WebProfilerBundle/Twig/WebProfilerExtension.php b/src/Symfony/Bundle/WebProfilerBundle/Twig/WebProfilerExtension.php
index 5e42a285f70d5..deace08e09fa4 100644
--- a/src/Symfony/Bundle/WebProfilerBundle/Twig/WebProfilerExtension.php
+++ b/src/Symfony/Bundle/WebProfilerBundle/Twig/WebProfilerExtension.php
@@ -98,7 +98,7 @@ public function dumpLog(Environment $env, $message, Data $context = null)
$message = twig_escape_filter($env, $message);
$message = preg_replace('/"(.*?)"/', '"$1"', $message);
- if (null === $context || false === strpos($message, '{')) {
+ if (null === $context || !str_contains($message, '{')) {
return ''.$message.'';
}
diff --git a/src/Symfony/Bundle/WebServerBundle/Command/ServerLogCommand.php b/src/Symfony/Bundle/WebServerBundle/Command/ServerLogCommand.php
index 586f0747f30ac..248b4ca0b7348 100644
--- a/src/Symfony/Bundle/WebServerBundle/Command/ServerLogCommand.php
+++ b/src/Symfony/Bundle/WebServerBundle/Command/ServerLogCommand.php
@@ -100,7 +100,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
'multiline' => OutputInterface::VERBOSITY_DEBUG <= $output->getVerbosity(),
]));
- if (false === strpos($host = $input->getOption('host'), '://')) {
+ if (!str_contains($host = $input->getOption('host'), '://')) {
$host = 'tcp://'.$host;
}
diff --git a/src/Symfony/Bundle/WebServerBundle/composer.json b/src/Symfony/Bundle/WebServerBundle/composer.json
index 6575a64bdf9d6..23aad7f95fc9a 100644
--- a/src/Symfony/Bundle/WebServerBundle/composer.json
+++ b/src/Symfony/Bundle/WebServerBundle/composer.json
@@ -22,6 +22,7 @@
"symfony/dependency-injection": "^3.4|^4.0|^5.0",
"symfony/http-kernel": "^3.4|^4.0|^5.0",
"symfony/polyfill-ctype": "~1.8",
+ "symfony/polyfill-php80": "^1.16",
"symfony/process": "^3.4.2|^4.0.2|^5.0"
},
"autoload": {
diff --git a/src/Symfony/Component/Asset/Package.php b/src/Symfony/Component/Asset/Package.php
index 799aaf75425ca..8a797644398bc 100644
--- a/src/Symfony/Component/Asset/Package.php
+++ b/src/Symfony/Component/Asset/Package.php
@@ -73,6 +73,6 @@ protected function getVersionStrategy()
*/
protected function isAbsoluteUrl($url)
{
- return false !== strpos($url, '://') || '//' === substr($url, 0, 2);
+ return str_contains($url, '://') || '//' === substr($url, 0, 2);
}
}
diff --git a/src/Symfony/Component/Asset/composer.json b/src/Symfony/Component/Asset/composer.json
index 2e04eb31c7228..c0281a78aa7f3 100644
--- a/src/Symfony/Component/Asset/composer.json
+++ b/src/Symfony/Component/Asset/composer.json
@@ -16,7 +16,8 @@
}
],
"require": {
- "php": ">=7.1.3"
+ "php": ">=7.1.3",
+ "symfony/polyfill-php80": "^1.16"
},
"suggest": {
"symfony/http-foundation": ""
diff --git a/src/Symfony/Component/BrowserKit/Client.php b/src/Symfony/Component/BrowserKit/Client.php
index e856aa818b779..06b55cd380281 100644
--- a/src/Symfony/Component/BrowserKit/Client.php
+++ b/src/Symfony/Component/BrowserKit/Client.php
@@ -662,7 +662,7 @@ public function restart()
protected function getAbsoluteUri($uri)
{
// already absolute?
- if (0 === strpos($uri, 'http://') || 0 === strpos($uri, 'https://')) {
+ if (str_starts_with($uri, 'http://') || str_starts_with($uri, 'https://')) {
return $uri;
}
@@ -676,7 +676,7 @@ protected function getAbsoluteUri($uri)
}
// protocol relative URL
- if (0 === strpos($uri, '//')) {
+ if (str_starts_with($uri, '//')) {
return parse_url($currentUri, \PHP_URL_SCHEME).':'.$uri;
}
diff --git a/src/Symfony/Component/BrowserKit/Cookie.php b/src/Symfony/Component/BrowserKit/Cookie.php
index 8b639af6e8672..f075f2c656945 100644
--- a/src/Symfony/Component/BrowserKit/Cookie.php
+++ b/src/Symfony/Component/BrowserKit/Cookie.php
@@ -132,7 +132,7 @@ public static function fromString($cookie, $url = null)
{
$parts = explode(';', $cookie);
- if (false === strpos($parts[0], '=')) {
+ if (!str_contains($parts[0], '=')) {
throw new \InvalidArgumentException(sprintf('The cookie string "%s" is not valid.', $parts[0]));
}
diff --git a/src/Symfony/Component/BrowserKit/CookieJar.php b/src/Symfony/Component/BrowserKit/CookieJar.php
index 5211e02322169..67b8a43e737ca 100644
--- a/src/Symfony/Component/BrowserKit/CookieJar.php
+++ b/src/Symfony/Component/BrowserKit/CookieJar.php
@@ -52,7 +52,7 @@ public function get($name, $path = '/', $domain = null)
}
foreach ($pathCookies as $cookiePath => $namedCookies) {
- if (0 !== strpos($path, $cookiePath)) {
+ if (!str_starts_with($path, $cookiePath)) {
continue;
}
if (isset($namedCookies[$name])) {
diff --git a/src/Symfony/Component/BrowserKit/HttpBrowser.php b/src/Symfony/Component/BrowserKit/HttpBrowser.php
index 6f5749c2642a8..e2d6477673e82 100644
--- a/src/Symfony/Component/BrowserKit/HttpBrowser.php
+++ b/src/Symfony/Component/BrowserKit/HttpBrowser.php
@@ -100,7 +100,7 @@ private function getHeaders(Request $request): array
foreach ($request->getServer() as $key => $value) {
$key = strtolower(str_replace('_', '-', $key));
$contentHeaders = ['content-length' => true, 'content-md5' => true, 'content-type' => true];
- if (0 === strpos($key, 'http-')) {
+ if (str_starts_with($key, 'http-')) {
$headers[substr($key, 5)] = $value;
} elseif (isset($contentHeaders[$key])) {
// CONTENT_* are not prefixed with HTTP_
diff --git a/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php b/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php
index fa6d366a7064d..040a095ab11ab 100644
--- a/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php
+++ b/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php
@@ -134,10 +134,10 @@ public static function createConnection($dsn, array $options = [])
if (!\is_string($dsn)) {
throw new InvalidArgumentException(sprintf('The "%s()" method expect argument #1 to be string, "%s" given.', __METHOD__, \gettype($dsn)));
}
- if (0 === strpos($dsn, 'redis:') || 0 === strpos($dsn, 'rediss:')) {
+ if (str_starts_with($dsn, 'redis:') || str_starts_with($dsn, 'rediss:')) {
return RedisAdapter::createConnection($dsn, $options);
}
- if (0 === strpos($dsn, 'memcached:')) {
+ if (str_starts_with($dsn, 'memcached:')) {
return MemcachedAdapter::createConnection($dsn, $options);
}
diff --git a/src/Symfony/Component/Cache/Adapter/RedisTagAwareAdapter.php b/src/Symfony/Component/Cache/Adapter/RedisTagAwareAdapter.php
index 6ac5f87a52ce9..c721f35d73d4e 100644
--- a/src/Symfony/Component/Cache/Adapter/RedisTagAwareAdapter.php
+++ b/src/Symfony/Component/Cache/Adapter/RedisTagAwareAdapter.php
@@ -88,7 +88,7 @@ public function __construct($redis, string $namespace = '', int $defaultLifetime
protected function doSave(array $values, int $lifetime, array $addTagData = [], array $delTagData = []): array
{
$eviction = $this->getRedisEvictionPolicy();
- if ('noeviction' !== $eviction && 0 !== strpos($eviction, 'volatile-')) {
+ if ('noeviction' !== $eviction && !str_starts_with($eviction, 'volatile-')) {
throw new LogicException(sprintf('Redis maxmemory-policy setting "%s" is *not* supported by RedisTagAwareAdapter, use "noeviction" or "volatile-*" eviction policies.', $eviction));
}
diff --git a/src/Symfony/Component/Cache/Adapter/TagAwareAdapter.php b/src/Symfony/Component/Cache/Adapter/TagAwareAdapter.php
index 23a0e87a74951..cfb7b17ea551e 100644
--- a/src/Symfony/Component/Cache/Adapter/TagAwareAdapter.php
+++ b/src/Symfony/Component/Cache/Adapter/TagAwareAdapter.php
@@ -237,7 +237,7 @@ public function clear(/*string $prefix = ''*/)
if ('' !== $prefix) {
foreach ($this->deferred as $key => $item) {
- if (0 === strpos($key, $prefix)) {
+ if (str_starts_with($key, $prefix)) {
unset($this->deferred[$key]);
}
}
diff --git a/src/Symfony/Component/Cache/Tests/Adapter/FilesystemAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/FilesystemAdapterTest.php
index 54264eeac5b42..87079a4eb6448 100644
--- a/src/Symfony/Component/Cache/Tests/Adapter/FilesystemAdapterTest.php
+++ b/src/Symfony/Component/Cache/Tests/Adapter/FilesystemAdapterTest.php
@@ -34,7 +34,7 @@ public static function rmdir(string $dir)
if (!file_exists($dir)) {
return;
}
- if (!$dir || 0 !== strpos(\dirname($dir), sys_get_temp_dir())) {
+ if (!$dir || !str_starts_with(\dirname($dir), sys_get_temp_dir())) {
throw new \Exception(__METHOD__."() operates only on subdirs of system's temp dir");
}
$children = new \RecursiveIteratorIterator(
diff --git a/src/Symfony/Component/Cache/Traits/ArrayTrait.php b/src/Symfony/Component/Cache/Traits/ArrayTrait.php
index 824f8659e35a2..2682eb146cd44 100644
--- a/src/Symfony/Component/Cache/Traits/ArrayTrait.php
+++ b/src/Symfony/Component/Cache/Traits/ArrayTrait.php
@@ -79,7 +79,7 @@ public function clear(/*string $prefix = ''*/)
if ('' !== $prefix) {
foreach ($this->values as $key => $value) {
- if (0 === strpos($key, $prefix)) {
+ if (str_starts_with($key, $prefix)) {
unset($this->values[$key], $this->expiries[$key]);
}
}
diff --git a/src/Symfony/Component/Cache/Traits/FilesystemCommonTrait.php b/src/Symfony/Component/Cache/Traits/FilesystemCommonTrait.php
index fe61f08c16740..e6d4676db2c16 100644
--- a/src/Symfony/Component/Cache/Traits/FilesystemCommonTrait.php
+++ b/src/Symfony/Component/Cache/Traits/FilesystemCommonTrait.php
@@ -58,7 +58,7 @@ protected function doClear($namespace)
$ok = true;
foreach ($this->scanHashDir($this->directory) as $file) {
- if ('' !== $namespace && 0 !== strpos($this->getFileKey($file), $namespace)) {
+ if ('' !== $namespace && !str_starts_with($this->getFileKey($file), $namespace)) {
continue;
}
@@ -98,7 +98,7 @@ private function write(string $file, string $data, int $expiresAt = null)
try {
$h = fopen($this->tmp, 'x');
} catch (\ErrorException $e) {
- if (false === strpos($e->getMessage(), 'File exists')) {
+ if (!str_contains($e->getMessage(), 'File exists')) {
throw $e;
}
diff --git a/src/Symfony/Component/Cache/Traits/MemcachedTrait.php b/src/Symfony/Component/Cache/Traits/MemcachedTrait.php
index 7b61e73a44727..f86cb1c7a2244 100644
--- a/src/Symfony/Component/Cache/Traits/MemcachedTrait.php
+++ b/src/Symfony/Component/Cache/Traits/MemcachedTrait.php
@@ -106,7 +106,7 @@ public static function createConnection($servers, array $options = [])
if (\is_array($dsn)) {
continue;
}
- if (0 !== strpos($dsn, 'memcached:')) {
+ if (!str_starts_with($dsn, 'memcached:')) {
throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: "%s" does not start with "memcached:".', $dsn));
}
$params = preg_replace_callback('#^memcached:(//)?(?:([^@]*+)@)?#', function ($m) use (&$username, &$password) {
diff --git a/src/Symfony/Component/Cache/Traits/RedisTrait.php b/src/Symfony/Component/Cache/Traits/RedisTrait.php
index 4d7b7c4b200ef..990678165624a 100644
--- a/src/Symfony/Component/Cache/Traits/RedisTrait.php
+++ b/src/Symfony/Component/Cache/Traits/RedisTrait.php
@@ -90,9 +90,9 @@ private function init($redis, string $namespace, int $defaultLifetime, ?Marshall
*/
public static function createConnection($dsn, array $options = [])
{
- if (0 === strpos($dsn, 'redis:')) {
+ if (str_starts_with($dsn, 'redis:')) {
$scheme = 'redis';
- } elseif (0 === strpos($dsn, 'rediss:')) {
+ } elseif (str_starts_with($dsn, 'rediss:')) {
$scheme = 'rediss';
} else {
throw new InvalidArgumentException(sprintf('Invalid Redis DSN: "%s" does not start with "redis:" or "rediss".', $dsn));
diff --git a/src/Symfony/Component/Cache/composer.json b/src/Symfony/Component/Cache/composer.json
index 0ebb28cda7086..e481d66a9d427 100644
--- a/src/Symfony/Component/Cache/composer.json
+++ b/src/Symfony/Component/Cache/composer.json
@@ -25,6 +25,7 @@
"psr/cache": "^1.0|^2.0",
"psr/log": "^1|^2|^3",
"symfony/cache-contracts": "^1.1.7|^2",
+ "symfony/polyfill-php80": "^1.16",
"symfony/service-contracts": "^1.1|^2",
"symfony/var-exporter": "^4.2|^5.0"
},
diff --git a/src/Symfony/Component/Config/Definition/ArrayNode.php b/src/Symfony/Component/Config/Definition/ArrayNode.php
index c6793a2b7efa6..34201709c2179 100644
--- a/src/Symfony/Component/Config/Definition/ArrayNode.php
+++ b/src/Symfony/Component/Config/Definition/ArrayNode.php
@@ -55,7 +55,7 @@ protected function preNormalize($value)
$normalized = [];
foreach ($value as $k => $v) {
- if (false !== strpos($k, '-') && false === strpos($k, '_') && !\array_key_exists($normalizedKey = str_replace('-', '_', $k), $value)) {
+ if (str_contains($k, '-') && !str_contains($k, '_') && !\array_key_exists($normalizedKey = str_replace('-', '_', $k), $value)) {
$normalized[$normalizedKey] = $v;
} else {
$normalized[$k] = $v;
diff --git a/src/Symfony/Component/Config/Definition/BaseNode.php b/src/Symfony/Component/Config/Definition/BaseNode.php
index 3b0ea0a98a403..209e3d265166e 100644
--- a/src/Symfony/Component/Config/Definition/BaseNode.php
+++ b/src/Symfony/Component/Config/Definition/BaseNode.php
@@ -47,7 +47,7 @@ abstract class BaseNode implements NodeInterface
*/
public function __construct(?string $name, NodeInterface $parent = null, string $pathSeparator = self::DEFAULT_PATH_SEPARATOR)
{
- if (false !== strpos($name = (string) $name, $pathSeparator)) {
+ if (str_contains($name = (string) $name, $pathSeparator)) {
throw new \InvalidArgumentException('The name must not contain ".'.$pathSeparator.'".');
}
@@ -514,7 +514,7 @@ private static function resolvePlaceholderValue($value)
}
foreach (self::$placeholderUniquePrefixes as $placeholderUniquePrefix) {
- if (0 === strpos($value, $placeholderUniquePrefix)) {
+ if (str_starts_with($value, $placeholderUniquePrefix)) {
return [];
}
}
diff --git a/src/Symfony/Component/Config/Loader/FileLoader.php b/src/Symfony/Component/Config/Loader/FileLoader.php
index 5ead5961f6ab3..8aef0ffba40ed 100644
--- a/src/Symfony/Component/Config/Loader/FileLoader.php
+++ b/src/Symfony/Component/Config/Loader/FileLoader.php
@@ -73,12 +73,12 @@ public function getLocator()
*/
public function import($resource, $type = null, $ignoreErrors = false, $sourceResource = null/*, $exclude = null*/)
{
- if (\func_num_args() < 5 && __CLASS__ !== static::class && 0 !== strpos(static::class, 'Symfony\Component\\') && __CLASS__ !== (new \ReflectionMethod($this, __FUNCTION__))->getDeclaringClass()->getName() && !$this instanceof \PHPUnit\Framework\MockObject\MockObject && !$this instanceof \Prophecy\Prophecy\ProphecySubjectInterface && !$this instanceof \Mockery\MockInterface) {
+ if (\func_num_args() < 5 && __CLASS__ !== static::class && !str_starts_with(static::class, 'Symfony\Component\\') && __CLASS__ !== (new \ReflectionMethod($this, __FUNCTION__))->getDeclaringClass()->getName() && !$this instanceof \PHPUnit\Framework\MockObject\MockObject && !$this instanceof \Prophecy\Prophecy\ProphecySubjectInterface && !$this instanceof \Mockery\MockInterface) {
@trigger_error(sprintf('The "%s()" method will have a new "$exclude = null" argument in version 5.0, not defining it is deprecated since Symfony 4.4.', __METHOD__), \E_USER_DEPRECATED);
}
$exclude = \func_num_args() >= 5 ? func_get_arg(4) : null;
- if (\is_string($resource) && \strlen($resource) !== ($i = strcspn($resource, '*?{[')) && false === strpos($resource, "\n")) {
+ if (\is_string($resource) && \strlen($resource) !== ($i = strcspn($resource, '*?{[')) && !str_contains($resource, "\n")) {
$excluded = [];
foreach ((array) $exclude as $pattern) {
foreach ($this->glob($pattern, true, $_, false, true) as $path => $info) {
@@ -88,7 +88,7 @@ public function import($resource, $type = null, $ignoreErrors = false, $sourceRe
}
$ret = [];
- $isSubpath = 0 !== $i && false !== strpos(substr($resource, 0, $i), '/');
+ $isSubpath = 0 !== $i && str_contains(substr($resource, 0, $i), '/');
foreach ($this->glob($resource, false, $_, $ignoreErrors || !$isSubpath, false, $excluded) as $path => $info) {
if (null !== $res = $this->doImport($path, 'glob' === $type ? null : $type, $ignoreErrors, $sourceResource)) {
$ret[] = $res;
@@ -112,7 +112,7 @@ protected function glob(string $pattern, bool $recursive, &$resource = null, boo
if (\strlen($pattern) === $i = strcspn($pattern, '*?{[')) {
$prefix = $pattern;
$pattern = '';
- } elseif (0 === $i || false === strpos(substr($pattern, 0, $i), '/')) {
+ } elseif (0 === $i || !str_contains(substr($pattern, 0, $i), '/')) {
$prefix = '.';
$pattern = '/'.$pattern;
} else {
diff --git a/src/Symfony/Component/Config/Resource/ComposerResource.php b/src/Symfony/Component/Config/Resource/ComposerResource.php
index eefce22a3f4fd..aee6f02b20979 100644
--- a/src/Symfony/Component/Config/Resource/ComposerResource.php
+++ b/src/Symfony/Component/Config/Resource/ComposerResource.php
@@ -55,7 +55,7 @@ private static function refresh()
self::$runtimeVendors = [];
foreach (get_declared_classes() as $class) {
- if ('C' === $class[0] && 0 === strpos($class, 'ComposerAutoloaderInit')) {
+ if ('C' === $class[0] && str_starts_with($class, 'ComposerAutoloaderInit')) {
$r = new \ReflectionClass($class);
$v = \dirname($r->getFileName(), 2);
if (file_exists($v.'/composer/installed.json')) {
diff --git a/src/Symfony/Component/Config/Resource/GlobResource.php b/src/Symfony/Component/Config/Resource/GlobResource.php
index f65a019befd2c..0b535682f4af3 100644
--- a/src/Symfony/Component/Config/Resource/GlobResource.php
+++ b/src/Symfony/Component/Config/Resource/GlobResource.php
@@ -110,10 +110,10 @@ public function getIterator()
$prefix = str_replace('\\', '/', $this->prefix);
$paths = null;
- if (0 !== strpos($this->prefix, 'phar://') && false === strpos($this->pattern, '/**/')) {
- if ($this->globBrace || false === strpos($this->pattern, '{')) {
+ if (!str_starts_with($this->prefix, 'phar://') && !str_contains($this->pattern, '/**/')) {
+ if ($this->globBrace || !str_contains($this->pattern, '{')) {
$paths = glob($this->prefix.$this->pattern, \GLOB_NOSORT | $this->globBrace);
- } elseif (false === strpos($this->pattern, '\\') || !preg_match('/\\\\[,{}]/', $this->pattern)) {
+ } elseif (!str_contains($this->pattern, '\\') || !preg_match('/\\\\[,{}]/', $this->pattern)) {
foreach ($this->expandGlob($this->pattern) as $p) {
$paths[] = glob($this->prefix.$p, \GLOB_NOSORT);
}
@@ -226,7 +226,7 @@ private function expandGlob(string $pattern): array
$j = 0;
foreach ($patterns as $i => $p) {
- if (false !== strpos($p, '{')) {
+ if (str_contains($p, '{')) {
$p = $this->expandGlob($p);
array_splice($paths, $i + $j, 1, $p);
$j += \count($p) - 1;
diff --git a/src/Symfony/Component/Config/Resource/ReflectionClassResource.php b/src/Symfony/Component/Config/Resource/ReflectionClassResource.php
index 051158b2413f3..c6082edc5c64b 100644
--- a/src/Symfony/Component/Config/Resource/ReflectionClassResource.php
+++ b/src/Symfony/Component/Config/Resource/ReflectionClassResource.php
@@ -83,7 +83,7 @@ private function loadFiles(\ReflectionClass $class)
$file = $class->getFileName();
if (false !== $file && file_exists($file)) {
foreach ($this->excludedVendors as $vendor) {
- if (0 === strpos($file, $vendor) && false !== strpbrk(substr($file, \strlen($vendor), 1), '/'.\DIRECTORY_SEPARATOR)) {
+ if (str_starts_with($file, $vendor) && false !== strpbrk(substr($file, \strlen($vendor), 1), '/'.\DIRECTORY_SEPARATOR)) {
$file = false;
break;
}
diff --git a/src/Symfony/Component/Config/Tests/Resource/ComposerResourceTest.php b/src/Symfony/Component/Config/Tests/Resource/ComposerResourceTest.php
index 6857c766d1347..10139f53a8dca 100644
--- a/src/Symfony/Component/Config/Tests/Resource/ComposerResourceTest.php
+++ b/src/Symfony/Component/Config/Tests/Resource/ComposerResourceTest.php
@@ -25,7 +25,7 @@ public function testGetVendor()
$found = false;
foreach ($res->getVendors() as $vendor) {
- if ($vendor && 0 === strpos($r->getFileName(), $vendor)) {
+ if ($vendor && str_starts_with($r->getFileName(), $vendor)) {
$found = true;
break;
}
diff --git a/src/Symfony/Component/Console/Application.php b/src/Symfony/Component/Console/Application.php
index ed6d00190ee83..15d537dacb3a6 100644
--- a/src/Symfony/Component/Console/Application.php
+++ b/src/Symfony/Component/Console/Application.php
@@ -877,7 +877,7 @@ private function doActuallyRenderThrowable(\Throwable $e, OutputInterface $outpu
$len = 0;
}
- if (false !== strpos($message, "@anonymous\0")) {
+ if (str_contains($message, "@anonymous\0")) {
$message = preg_replace_callback('/[a-zA-Z_\x7f-\xff][\\\\a-zA-Z0-9_\x7f-\xff]*+@anonymous\x00.*?\.php(?:0x?|:[0-9]++\$)[0-9a-fA-F]++/', function ($m) {
return class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0];
}, $message);
@@ -1155,7 +1155,7 @@ private function findAlternatives(string $name, iterable $collection): array
}
$lev = levenshtein($subname, $parts[$i]);
- if ($lev <= \strlen($subname) / 3 || '' !== $subname && false !== strpos($parts[$i], $subname)) {
+ if ($lev <= \strlen($subname) / 3 || '' !== $subname && str_contains($parts[$i], $subname)) {
$alternatives[$collectionName] = $exists ? $alternatives[$collectionName] + $lev : $lev;
} elseif ($exists) {
$alternatives[$collectionName] += $threshold;
@@ -1165,7 +1165,7 @@ private function findAlternatives(string $name, iterable $collection): array
foreach ($collection as $item) {
$lev = levenshtein($name, $item);
- if ($lev <= \strlen($name) / 3 || false !== strpos($item, $name)) {
+ if ($lev <= \strlen($name) / 3 || str_contains($item, $name)) {
$alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev : $lev;
}
}
diff --git a/src/Symfony/Component/Console/Command/Command.php b/src/Symfony/Component/Console/Command/Command.php
index 1e109b1949bb7..da9b9f6af1730 100644
--- a/src/Symfony/Component/Console/Command/Command.php
+++ b/src/Symfony/Component/Console/Command/Command.php
@@ -613,7 +613,7 @@ public function getSynopsis($short = false)
*/
public function addUsage($usage)
{
- if (0 !== strpos($usage, $this->name)) {
+ if (!str_starts_with($usage, $this->name)) {
$usage = sprintf('%s %s', $this->name, $usage);
}
diff --git a/src/Symfony/Component/Console/Formatter/OutputFormatter.php b/src/Symfony/Component/Console/Formatter/OutputFormatter.php
index b0355d811290f..0f969c7adb9b9 100644
--- a/src/Symfony/Component/Console/Formatter/OutputFormatter.php
+++ b/src/Symfony/Component/Console/Formatter/OutputFormatter.php
@@ -180,7 +180,7 @@ public function formatAndWrap(string $message, int $width)
$output .= $this->applyCurrentStyle(substr($message, $offset), $output, $width, $currentLineLength);
- if (false !== strpos($output, "\0")) {
+ if (str_contains($output, "\0")) {
return strtr($output, ["\0" => '\\', '\\<' => '<']);
}
diff --git a/src/Symfony/Component/Console/Helper/QuestionHelper.php b/src/Symfony/Component/Console/Helper/QuestionHelper.php
index 5c3ecc4e5babb..089de76bd63e0 100644
--- a/src/Symfony/Component/Console/Helper/QuestionHelper.php
+++ b/src/Symfony/Component/Console/Helper/QuestionHelper.php
@@ -311,7 +311,7 @@ private function autocomplete(OutputInterface $output, Question $question, $inpu
$matches = array_filter(
$autocomplete($ret),
function ($match) use ($ret) {
- return '' === $ret || 0 === strpos($match, $ret);
+ return '' === $ret || str_starts_with($match, $ret);
}
);
$numMatches = \count($matches);
@@ -348,7 +348,7 @@ function ($match) use ($ret) {
foreach ($autocomplete($ret) as $value) {
// If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
- if (0 === strpos($value, $tempRet)) {
+ if (str_starts_with($value, $tempRet)) {
$matches[$numMatches++] = $value;
}
}
@@ -377,7 +377,7 @@ function ($match) use ($ret) {
private function mostRecentlyEnteredValue(string $entered): string
{
// Determine the most recent value that the user entered
- if (false === strpos($entered, ',')) {
+ if (!str_contains($entered, ',')) {
return $entered;
}
diff --git a/src/Symfony/Component/Console/Input/ArgvInput.php b/src/Symfony/Component/Console/Input/ArgvInput.php
index 6d2946926fa7e..b63529509592c 100644
--- a/src/Symfony/Component/Console/Input/ArgvInput.php
+++ b/src/Symfony/Component/Console/Input/ArgvInput.php
@@ -75,7 +75,7 @@ protected function parse()
$this->parseArgument($token);
} elseif ($parseOptions && '--' == $token) {
$parseOptions = false;
- } elseif ($parseOptions && 0 === strpos($token, '--')) {
+ } elseif ($parseOptions && str_starts_with($token, '--')) {
$this->parseLongOption($token);
} elseif ($parseOptions && '-' === $token[0] && '-' !== $token) {
$this->parseShortOption($token);
@@ -243,7 +243,7 @@ public function getFirstArgument()
$isOption = false;
foreach ($this->tokens as $i => $token) {
if ($token && '-' === $token[0]) {
- if (false !== strpos($token, '=') || !isset($this->tokens[$i + 1])) {
+ if (str_contains($token, '=') || !isset($this->tokens[$i + 1])) {
continue;
}
@@ -285,8 +285,8 @@ public function hasParameterOption($values, $onlyParams = false)
// Options with values:
// For long options, test for '--option=' at beginning
// For short options, test for '-o' at beginning
- $leading = 0 === strpos($value, '--') ? $value.'=' : $value;
- if ($token === $value || '' !== $leading && 0 === strpos($token, $leading)) {
+ $leading = str_starts_with($value, '--') ? $value.'=' : $value;
+ if ($token === $value || '' !== $leading && str_starts_with($token, $leading)) {
return true;
}
}
@@ -316,8 +316,8 @@ public function getParameterOption($values, $default = false, $onlyParams = fals
// Options with values:
// For long options, test for '--option=' at beginning
// For short options, test for '-o' at beginning
- $leading = 0 === strpos($value, '--') ? $value.'=' : $value;
- if ('' !== $leading && 0 === strpos($token, $leading)) {
+ $leading = str_starts_with($value, '--') ? $value.'=' : $value;
+ if ('' !== $leading && str_starts_with($token, $leading)) {
return substr($token, \strlen($leading));
}
}
diff --git a/src/Symfony/Component/Console/Input/ArrayInput.php b/src/Symfony/Component/Console/Input/ArrayInput.php
index bf9a8a455a4c5..30bd2054a69db 100644
--- a/src/Symfony/Component/Console/Input/ArrayInput.php
+++ b/src/Symfony/Component/Console/Input/ArrayInput.php
@@ -133,9 +133,9 @@ protected function parse()
if ('--' === $key) {
return;
}
- if (0 === strpos($key, '--')) {
+ if (str_starts_with($key, '--')) {
$this->addLongOption(substr($key, 2), $value);
- } elseif (0 === strpos($key, '-')) {
+ } elseif (str_starts_with($key, '-')) {
$this->addShortOption(substr($key, 1), $value);
} else {
$this->addArgument($key, $value);
diff --git a/src/Symfony/Component/Console/Input/InputOption.php b/src/Symfony/Component/Console/Input/InputOption.php
index 710e9a8095efc..c40e0da3445fa 100644
--- a/src/Symfony/Component/Console/Input/InputOption.php
+++ b/src/Symfony/Component/Console/Input/InputOption.php
@@ -56,7 +56,7 @@ class InputOption
*/
public function __construct(string $name, $shortcut = null, int $mode = null, string $description = '', $default = null)
{
- if (0 === strpos($name, '--')) {
+ if (str_starts_with($name, '--')) {
$name = substr($name, 2);
}
diff --git a/src/Symfony/Component/Console/Logger/ConsoleLogger.php b/src/Symfony/Component/Console/Logger/ConsoleLogger.php
index 4a0315656574a..c9ee03561b355 100644
--- a/src/Symfony/Component/Console/Logger/ConsoleLogger.php
+++ b/src/Symfony/Component/Console/Logger/ConsoleLogger.php
@@ -104,7 +104,7 @@ public function hasErrored()
*/
private function interpolate(string $message, array $context): string
{
- if (false === strpos($message, '{')) {
+ if (!str_contains($message, '{')) {
return $message;
}
diff --git a/src/Symfony/Component/CssSelector/Parser/Parser.php b/src/Symfony/Component/CssSelector/Parser/Parser.php
index 963efb013eef5..d73489edfb481 100644
--- a/src/Symfony/Component/CssSelector/Parser/Parser.php
+++ b/src/Symfony/Component/CssSelector/Parser/Parser.php
@@ -79,7 +79,7 @@ public static function parseSeries(array $tokens): array
return [2, 0];
case 'n' === $joined:
return [1, 0];
- case false === strpos($joined, 'n'):
+ case !str_contains($joined, 'n'):
return [0, $int($joined)];
}
diff --git a/src/Symfony/Component/CssSelector/XPath/Translator.php b/src/Symfony/Component/CssSelector/XPath/Translator.php
index 13e1adacd583e..782aef458a9e1 100644
--- a/src/Symfony/Component/CssSelector/XPath/Translator.php
+++ b/src/Symfony/Component/CssSelector/XPath/Translator.php
@@ -63,11 +63,11 @@ public function __construct(ParserInterface $parser = null)
public static function getXpathLiteral(string $element): string
{
- if (false === strpos($element, "'")) {
+ if (!str_contains($element, "'")) {
return "'".$element."'";
}
- if (false === strpos($element, '"')) {
+ if (!str_contains($element, '"')) {
return '"'.$element.'"';
}
diff --git a/src/Symfony/Component/CssSelector/composer.json b/src/Symfony/Component/CssSelector/composer.json
index e17f6a048457e..e8ecfee7ac571 100644
--- a/src/Symfony/Component/CssSelector/composer.json
+++ b/src/Symfony/Component/CssSelector/composer.json
@@ -20,7 +20,8 @@
}
],
"require": {
- "php": ">=7.1.3"
+ "php": ">=7.1.3",
+ "symfony/polyfill-php80": "^1.16"
},
"autoload": {
"psr-4": { "Symfony\\Component\\CssSelector\\": "" },
diff --git a/src/Symfony/Component/Debug/DebugClassLoader.php b/src/Symfony/Component/Debug/DebugClassLoader.php
index a41cb768c4532..c4241714cc511 100644
--- a/src/Symfony/Component/Debug/DebugClassLoader.php
+++ b/src/Symfony/Component/Debug/DebugClassLoader.php
@@ -210,7 +210,7 @@ private function checkClass(string $class, string $file = null)
}
if (!$exists) {
- if (false !== strpos($class, '/')) {
+ if (str_contains($class, '/')) {
throw new \RuntimeException(sprintf('Trying to autoload a class with an invalid name "%s". Be careful that the namespace separator is "\" in PHP, not "/".', $class));
}
@@ -237,17 +237,17 @@ public function checkAnnotations(\ReflectionClass $refl, $class)
// Detect annotations on the class
if (false !== $doc = $refl->getDocComment()) {
foreach (['final', 'deprecated', 'internal'] as $annotation) {
- if (false !== strpos($doc, $annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$|\r?\n)#s', $doc, $notice)) {
+ if (str_contains($doc, $annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$|\r?\n)#s', $doc, $notice)) {
self::${$annotation}[$class] = isset($notice[1]) ? preg_replace('#\.?\r?\n( \*)? *(?= |\r?\n|$)#', '', $notice[1]) : '';
}
}
- if ($refl->isInterface() && false !== strpos($doc, 'method') && preg_match_all('#\n \* @method\s+(static\s+)?+(?:[\w\|&\[\]\\\]+\s+)?(\w+(?:\s*\([^\)]*\))?)+(.+?([[:punct:]]\s*)?)?(?=\r?\n \*(?: @|/$|\r?\n))#', $doc, $notice, \PREG_SET_ORDER)) {
+ if ($refl->isInterface() && str_contains($doc, 'method') && preg_match_all('#\n \* @method\s+(static\s+)?+(?:[\w\|&\[\]\\\]+\s+)?(\w+(?:\s*\([^\)]*\))?)+(.+?([[:punct:]]\s*)?)?(?=\r?\n \*(?: @|/$|\r?\n))#', $doc, $notice, \PREG_SET_ORDER)) {
foreach ($notice as $method) {
$static = '' !== $method[1];
$name = $method[2];
$description = $method[3] ?? null;
- if (false === strpos($name, '(')) {
+ if (!str_contains($name, '(')) {
$name .= '()';
}
if (null !== $description) {
@@ -369,14 +369,14 @@ public function checkAnnotations(\ReflectionClass $refl, $class)
$finalOrInternal = false;
foreach (['final', 'internal'] as $annotation) {
- if (false !== strpos($doc, $annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$|\r?\n)#s', $doc, $notice)) {
+ if (str_contains($doc, $annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$|\r?\n)#s', $doc, $notice)) {
$message = isset($notice[1]) ? preg_replace('#\.?\r?\n( \*)? *(?= |\r?\n|$)#', '', $notice[1]) : '';
self::${$annotation.'Methods'}[$class][$method->name] = [$class, $message];
$finalOrInternal = true;
}
}
- if ($finalOrInternal || $method->isConstructor() || false === strpos($doc, '@param') || StatelessInvocation::class === $class) {
+ if ($finalOrInternal || $method->isConstructor() || !str_contains($doc, '@param') || StatelessInvocation::class === $class) {
continue;
}
if (!preg_match_all('#\n\s+\* @param +((?(?!callable *\().*?|callable *\(.*\).*?))(?<= )\$([a-zA-Z0-9_\x7f-\xff]++)#', $doc, $matches, \PREG_SET_ORDER)) {
diff --git a/src/Symfony/Component/Debug/ErrorHandler.php b/src/Symfony/Component/Debug/ErrorHandler.php
index fd22f201adef6..4a1c21fa97fbd 100644
--- a/src/Symfony/Component/Debug/ErrorHandler.php
+++ b/src/Symfony/Component/Debug/ErrorHandler.php
@@ -385,7 +385,7 @@ private function reRegister(int $prev)
*/
public function handleError($type, $message, $file, $line)
{
- if (\PHP_VERSION_ID >= 70300 && \E_WARNING === $type && '"' === $message[0] && false !== strpos($message, '" targeting switch is equivalent to "break')) {
+ if (\PHP_VERSION_ID >= 70300 && \E_WARNING === $type && '"' === $message[0] && str_contains($message, '" targeting switch is equivalent to "break')) {
$type = \E_DEPRECATED;
}
@@ -403,7 +403,7 @@ public function handleError($type, $message, $file, $line)
}
$scope = $this->scopedErrors & $type;
- if (false !== strpos($message, "@anonymous\0")) {
+ if (str_contains($message, "@anonymous\0")) {
$logMessage = $this->levels[$type].': '.(new FlattenException())->setMessage($message)->getMessage();
} else {
$logMessage = $this->levels[$type].': '.$message;
@@ -530,7 +530,7 @@ public function handleException($exception, array $error = null)
$handlerException = null;
if (($this->loggedErrors & $type) || $exception instanceof FatalThrowableError) {
- if (false !== strpos($message = $exception->getMessage(), "@anonymous\0")) {
+ if (str_contains($message = $exception->getMessage(), "@anonymous\0")) {
$message = (new FlattenException())->setMessage($message)->getMessage();
}
if ($exception instanceof FatalErrorException) {
@@ -638,7 +638,7 @@ public static function handleFatalError(array $error = null)
$handler->throwAt(0, true);
$trace = $error['backtrace'] ?? null;
- if (0 === strpos($error['message'], 'Allowed memory') || 0 === strpos($error['message'], 'Out of memory')) {
+ if (str_starts_with($error['message'], 'Allowed memory') || str_starts_with($error['message'], 'Out of memory')) {
$exception = new OutOfMemoryException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, false, $trace);
} else {
$exception = new FatalErrorException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, true, $trace);
diff --git a/src/Symfony/Component/Debug/Exception/FlattenException.php b/src/Symfony/Component/Debug/Exception/FlattenException.php
index 8e877b0e03319..8d6e2391a0a58 100644
--- a/src/Symfony/Component/Debug/Exception/FlattenException.php
+++ b/src/Symfony/Component/Debug/Exception/FlattenException.php
@@ -134,7 +134,7 @@ public function getClass()
*/
public function setClass($class)
{
- $this->class = false !== strpos($class, "@anonymous\0") ? (get_parent_class($class) ?: key(class_implements($class)) ?: 'class').'@anonymous' : $class;
+ $this->class = str_contains($class, "@anonymous\0") ? (get_parent_class($class) ?: key(class_implements($class)) ?: 'class').'@anonymous' : $class;
return $this;
}
@@ -179,7 +179,7 @@ public function getMessage()
*/
public function setMessage($message)
{
- if (false !== strpos($message, "@anonymous\0")) {
+ if (str_contains($message, "@anonymous\0")) {
$message = preg_replace_callback('/[a-zA-Z_\x7f-\xff][\\\\a-zA-Z0-9_\x7f-\xff]*+@anonymous\x00.*?\.php(?:0x?|:[0-9]++\$)[0-9a-fA-F]++/', function ($m) {
return class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0];
}, $message);
diff --git a/src/Symfony/Component/Debug/ExceptionHandler.php b/src/Symfony/Component/Debug/ExceptionHandler.php
index 21be2827cd864..e8c9092d4a538 100644
--- a/src/Symfony/Component/Debug/ExceptionHandler.php
+++ b/src/Symfony/Component/Debug/ExceptionHandler.php
@@ -401,7 +401,7 @@ private function formatPath(string $path, int $line): string
$fmt = [substr($f, 0, $i)] + preg_split('/&([^>]++)>/', substr($f, $i), -1, \PREG_SPLIT_DELIM_CAPTURE);
for ($i = 1; isset($fmt[$i]); ++$i) {
- if (0 === strpos($path, $k = $fmt[$i++])) {
+ if (str_starts_with($path, $k = $fmt[$i++])) {
$path = substr_replace($path, $fmt[$i], 0, \strlen($k));
break;
}
diff --git a/src/Symfony/Component/Debug/FatalErrorHandler/ClassNotFoundFatalErrorHandler.php b/src/Symfony/Component/Debug/FatalErrorHandler/ClassNotFoundFatalErrorHandler.php
index 64d7551343e7a..189ac2f8e9f53 100644
--- a/src/Symfony/Component/Debug/FatalErrorHandler/ClassNotFoundFatalErrorHandler.php
+++ b/src/Symfony/Component/Debug/FatalErrorHandler/ClassNotFoundFatalErrorHandler.php
@@ -149,7 +149,7 @@ private function convertFileToClass(string $path, string $file, string $prefix):
];
if ($prefix) {
- $candidates = array_filter($candidates, function ($candidate) use ($prefix) { return 0 === strpos($candidate, $prefix); });
+ $candidates = array_filter($candidates, function ($candidate) use ($prefix) { return str_starts_with($candidate, $prefix); });
}
// We cannot use the autoloader here as most of them use require; but if the class
diff --git a/src/Symfony/Component/Debug/FatalErrorHandler/UndefinedFunctionFatalErrorHandler.php b/src/Symfony/Component/Debug/FatalErrorHandler/UndefinedFunctionFatalErrorHandler.php
index 95096a9cd1a94..b74bfca47ab07 100644
--- a/src/Symfony/Component/Debug/FatalErrorHandler/UndefinedFunctionFatalErrorHandler.php
+++ b/src/Symfony/Component/Debug/FatalErrorHandler/UndefinedFunctionFatalErrorHandler.php
@@ -43,7 +43,7 @@ public function handleError(array $error, FatalErrorException $exception)
$prefix = 'Call to undefined function ';
$prefixLen = \strlen($prefix);
- if (0 !== strpos($error['message'], $prefix)) {
+ if (!str_starts_with($error['message'], $prefix)) {
return null;
}
diff --git a/src/Symfony/Component/Debug/FatalErrorHandler/UndefinedMethodFatalErrorHandler.php b/src/Symfony/Component/Debug/FatalErrorHandler/UndefinedMethodFatalErrorHandler.php
index 4f622deeca53d..ef72121e86138 100644
--- a/src/Symfony/Component/Debug/FatalErrorHandler/UndefinedMethodFatalErrorHandler.php
+++ b/src/Symfony/Component/Debug/FatalErrorHandler/UndefinedMethodFatalErrorHandler.php
@@ -48,7 +48,7 @@ public function handleError(array $error, FatalErrorException $exception)
$candidates = [];
foreach ($methods as $definedMethodName) {
$lev = levenshtein($methodName, $definedMethodName);
- if ($lev <= \strlen($methodName) / 3 || false !== strpos($definedMethodName, $methodName)) {
+ if ($lev <= \strlen($methodName) / 3 || str_contains($definedMethodName, $methodName)) {
$candidates[] = $definedMethodName;
}
}
diff --git a/src/Symfony/Component/DependencyInjection/Alias.php b/src/Symfony/Component/DependencyInjection/Alias.php
index ca8a45a69cb9c..248eeefa06865 100644
--- a/src/Symfony/Component/DependencyInjection/Alias.php
+++ b/src/Symfony/Component/DependencyInjection/Alias.php
@@ -103,7 +103,7 @@ public function setDeprecated($status = true, $template = null)
throw new InvalidArgumentException('Invalid characters found in deprecation template.');
}
- if (false === strpos($template, '%alias_id%')) {
+ if (!str_contains($template, '%alias_id%')) {
throw new InvalidArgumentException('The deprecation template must contain the "%alias_id%" placeholder.');
}
diff --git a/src/Symfony/Component/DependencyInjection/ChildDefinition.php b/src/Symfony/Component/DependencyInjection/ChildDefinition.php
index 7718f725b18bd..5aefec6454827 100644
--- a/src/Symfony/Component/DependencyInjection/ChildDefinition.php
+++ b/src/Symfony/Component/DependencyInjection/ChildDefinition.php
@@ -97,7 +97,7 @@ public function replaceArgument($index, $value)
{
if (\is_int($index)) {
$this->arguments['index_'.$index] = $value;
- } elseif (0 === strpos($index, '$')) {
+ } elseif (str_starts_with($index, '$')) {
$this->arguments[$index] = $value;
} else {
throw new InvalidArgumentException('The argument must be an existing index or the name of a constructor\'s parameter.');
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/AutowirePass.php b/src/Symfony/Component/DependencyInjection/Compiler/AutowirePass.php
index b222d5787e4a0..470c638404411 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/AutowirePass.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/AutowirePass.php
@@ -297,7 +297,7 @@ private function getAutowiredReference(TypedReference $reference): ?TypedReferen
if ($this->container->has($name) && !$this->container->findDefinition($name)->isAbstract()) {
foreach ($this->container->getAliases() as $id => $alias) {
- if ($name === (string) $alias && 0 === strpos($id, $type.' $')) {
+ if ($name === (string) $alias && str_starts_with($id, $type.' $')) {
return new TypedReference($name, $type, $reference->getInvalidBehavior());
}
}
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/CheckDefinitionValidityPass.php b/src/Symfony/Component/DependencyInjection/Compiler/CheckDefinitionValidityPass.php
index bb87f47cddd47..7abac908f5a01 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/CheckDefinitionValidityPass.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/CheckDefinitionValidityPass.php
@@ -49,7 +49,7 @@ public function process(ContainerBuilder $container)
throw new RuntimeException(sprintf('Please add the class to service "%s" even if it is constructed by a factory since we might need to add method calls based on compile-time checks.', $id));
}
if (class_exists($id) || interface_exists($id, false)) {
- if (0 === strpos($id, '\\') && 1 < substr_count($id, '\\')) {
+ if (str_starts_with($id, '\\') && 1 < substr_count($id, '\\')) {
throw new RuntimeException(sprintf('The definition for "%s" has no class attribute, and appears to reference a class or interface. Please specify the class attribute explicitly or remove the leading backslash by renaming the service to "%s" to get rid of this error.', $id, substr($id, 1)));
}
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/CheckTypeDeclarationsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/CheckTypeDeclarationsPass.php
index 6f4cfd151ac74..50f83675d3f57 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/CheckTypeDeclarationsPass.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/CheckTypeDeclarationsPass.php
@@ -231,7 +231,7 @@ private function checkType(Definition $checkedDefinition, $value, \ReflectionPar
$value = $this->container->getParameter(substr($value, 1, -1));
}
- if ($envPlaceholderUniquePrefix && \is_string($value) && false !== strpos($value, 'env_')) {
+ if ($envPlaceholderUniquePrefix && \is_string($value) && str_contains($value, 'env_')) {
// If the value is an env placeholder that is either mixed with a string or with another env placeholder, then its resolved value will always be a string, so we don't need to resolve it.
// We don't need to change the value because it is already a string.
if ('' === preg_replace('/'.$envPlaceholderUniquePrefix.'_\w+_[a-f0-9]{32}/U', '', $value, -1, $c) && 1 === $c) {
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php b/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php
index 14dedf007b092..224ff6b1ea0c0 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/Compiler.php
@@ -67,7 +67,7 @@ public function addPass(CompilerPassInterface $pass, $type = PassConfig::TYPE_BE
*/
public function log(CompilerPassInterface $pass, string $message)
{
- if (false !== strpos($message, "\n")) {
+ if (str_contains($message, "\n")) {
$message = str_replace("\n", "\n".\get_class($pass).': ', trim($message));
}
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/MergeExtensionConfigurationPass.php b/src/Symfony/Component/DependencyInjection/Compiler/MergeExtensionConfigurationPass.php
index 9a7ac18e67ea7..5e4dd399617a9 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/MergeExtensionConfigurationPass.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/MergeExtensionConfigurationPass.php
@@ -209,7 +209,7 @@ public function resolveEnvPlaceholders($value, $format = null, array &$usedEnvs
}
foreach ($bag->getEnvPlaceholders() as $env => $placeholders) {
- if (false === strpos($env, ':')) {
+ if (!str_contains($env, ':')) {
continue;
}
foreach ($placeholders as $placeholder) {
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/RegisterServiceSubscribersPass.php b/src/Symfony/Component/DependencyInjection/Compiler/RegisterServiceSubscribersPass.php
index 7373c95ab709a..b6d1ede4c5834 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/RegisterServiceSubscribersPass.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/RegisterServiceSubscribersPass.php
@@ -91,7 +91,7 @@ protected function processValue($value, $isRoot = false)
if ($name) {
if (false !== $i = strpos($name, '::get')) {
$name = lcfirst(substr($name, 5 + $i));
- } elseif (false !== strpos($name, '::')) {
+ } elseif (str_contains($name, '::')) {
$name = null;
}
}
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ResolveBindingsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/ResolveBindingsPass.php
index 695a916f867fc..59c15cf2382c1 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/ResolveBindingsPass.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/ResolveBindingsPass.php
@@ -44,7 +44,7 @@ public function process(ContainerBuilder $container)
foreach ($this->unusedBindings as [$key, $serviceId, $bindingType, $file]) {
$argumentType = $argumentName = $message = null;
- if (false !== strpos($key, ' ')) {
+ if (str_contains($key, ' ')) {
[$argumentType, $argumentName] = explode(' ', $key, 2);
} elseif ('$' === $key[0]) {
$argumentName = $key;
diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ResolveChildDefinitionsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/ResolveChildDefinitionsPass.php
index 453e3f63c3f2a..99c374ee492f2 100644
--- a/src/Symfony/Component/DependencyInjection/Compiler/ResolveChildDefinitionsPass.php
+++ b/src/Symfony/Component/DependencyInjection/Compiler/ResolveChildDefinitionsPass.php
@@ -158,7 +158,7 @@ private function doResolveDefinition(ChildDefinition $definition): Definition
foreach ($definition->getArguments() as $k => $v) {
if (is_numeric($k)) {
$def->addArgument($v);
- } elseif (0 === strpos($k, 'index_')) {
+ } elseif (str_starts_with($k, 'index_')) {
$def->replaceArgument((int) substr($k, \strlen('index_')), $v);
} else {
$def->setArgument($k, $v);
diff --git a/src/Symfony/Component/DependencyInjection/Container.php b/src/Symfony/Component/DependencyInjection/Container.php
index ce44885b881d4..789c8f7275ca3 100644
--- a/src/Symfony/Component/DependencyInjection/Container.php
+++ b/src/Symfony/Component/DependencyInjection/Container.php
@@ -281,7 +281,7 @@ private function make(string $id, int $invalidBehavior)
continue;
}
$lev = levenshtein($id, $knownId);
- if ($lev <= \strlen($id) / 3 || false !== strpos($knownId, $id)) {
+ if ($lev <= \strlen($id) / 3 || str_contains($knownId, $id)) {
$alternatives[] = $knownId;
}
}
diff --git a/src/Symfony/Component/DependencyInjection/ContainerBuilder.php b/src/Symfony/Component/DependencyInjection/ContainerBuilder.php
index ca5a367e3c3b2..f97a57406ae62 100644
--- a/src/Symfony/Component/DependencyInjection/ContainerBuilder.php
+++ b/src/Symfony/Component/DependencyInjection/ContainerBuilder.php
@@ -1658,7 +1658,7 @@ private function inVendors(string $path): bool
$path = realpath($path) ?: $path;
foreach ($this->vendors as $vendor) {
- if (0 === strpos($path, $vendor) && false !== strpbrk(substr($path, \strlen($vendor), 1), '/'.\DIRECTORY_SEPARATOR)) {
+ if (str_starts_with($path, $vendor) && false !== strpbrk(substr($path, \strlen($vendor), 1), '/'.\DIRECTORY_SEPARATOR)) {
$this->addResource(new FileResource($vendor.'/composer/installed.json'));
return true;
diff --git a/src/Symfony/Component/DependencyInjection/Definition.php b/src/Symfony/Component/DependencyInjection/Definition.php
index 727594dcb4090..34ddbbbdd838b 100644
--- a/src/Symfony/Component/DependencyInjection/Definition.php
+++ b/src/Symfony/Component/DependencyInjection/Definition.php
@@ -110,7 +110,7 @@ public function setFactory($factory)
{
$this->changes['factory'] = true;
- if (\is_string($factory) && false !== strpos($factory, '::')) {
+ if (\is_string($factory) && str_contains($factory, '::')) {
$factory = explode('::', $factory, 2);
} elseif ($factory instanceof Reference) {
$factory = [$factory, '__invoke'];
@@ -765,7 +765,7 @@ public function setDeprecated($status = true, $template = null)
throw new InvalidArgumentException('Invalid characters found in deprecation template.');
}
- if (false === strpos($template, '%service_id%')) {
+ if (!str_contains($template, '%service_id%')) {
throw new InvalidArgumentException('The deprecation template must contain the "%service_id%" placeholder.');
}
@@ -813,7 +813,7 @@ public function setConfigurator($configurator)
{
$this->changes['configurator'] = true;
- if (\is_string($configurator) && false !== strpos($configurator, '::')) {
+ if (\is_string($configurator) && str_contains($configurator, '::')) {
$configurator = explode('::', $configurator, 2);
} elseif ($configurator instanceof Reference) {
$configurator = [$configurator, '__invoke'];
diff --git a/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php b/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
index f888b8d4b4c50..4f89bb3fd68df 100644
--- a/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
+++ b/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
@@ -156,7 +156,7 @@ public function dump(array $options = [])
$this->inlineRequires = $options['inline_class_loader_parameter'] && $this->container->hasParameter($options['inline_class_loader_parameter']) && $this->container->getParameter($options['inline_class_loader_parameter']);
$this->serviceLocatorTag = $options['service_locator_tag'];
- if (0 !== strpos($baseClass = $options['base_class'], '\\') && 'Container' !== $baseClass) {
+ if (!str_starts_with($baseClass = $options['base_class'], '\\') && 'Container' !== $baseClass) {
$baseClass = sprintf('%s\%s', $options['namespace'] ? '\\'.$options['namespace'] : '', $baseClass);
$this->baseClass = $baseClass;
} elseif ('Container' === $baseClass) {
@@ -313,7 +313,7 @@ public function dump(array $options = [])
EOF;
foreach ($this->preload as $class) {
- if (!$class || false !== strpos($class, '$')) {
+ if (!$class || str_contains($class, '$')) {
continue;
}
if (!(class_exists($class, false) || interface_exists($class, false) || trait_exists($class, false)) || (new \ReflectionClass($class))->isUserDefined()) {
@@ -631,7 +631,7 @@ private function addServiceInstance(string $id, Definition $definition, bool $is
{
$class = $this->dumpValue($definition->getClass());
- if (0 === strpos($class, "'") && false === strpos($class, '$') && !preg_match('/^\'(?:\\\{2})?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(?:\\\{2}[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*\'$/', $class)) {
+ if (str_starts_with($class, "'") && !str_contains($class, '$') && !preg_match('/^\'(?:\\\{2})?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(?:\\\{2}[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*\'$/', $class)) {
throw new InvalidArgumentException(sprintf('"%s" is not a valid class name for the "%s" service.', $class, $id));
}
@@ -758,11 +758,11 @@ private function addServiceConfigurator(Definition $definition, string $variable
$class = $this->dumpValue($callable[0]);
// If the class is a string we can optimize away
- if (0 === strpos($class, "'") && false === strpos($class, '$')) {
+ if (str_starts_with($class, "'") && !str_contains($class, '$')) {
return sprintf(" %s::%s(\$%s);\n", $this->dumpLiteralClass($class), $callable[1], $variableName);
}
- if (0 === strpos($class, 'new ')) {
+ if (str_starts_with($class, 'new ')) {
return sprintf(" (%s)->%s(\$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName);
}
@@ -783,7 +783,7 @@ private function addService(string $id, Definition $definition): array
if ($class = $definition->getClass()) {
$class = $class instanceof Parameter ? '%'.$class.'%' : $this->container->resolveEnvPlaceholders($class);
- $return[] = sprintf(0 === strpos($class, '%') ? '@return object A %1$s instance' : '@return \%s', ltrim($class, '\\'));
+ $return[] = sprintf(str_starts_with($class, '%') ? '@return object A %1$s instance' : '@return \%s', ltrim($class, '\\'));
} elseif ($definition->getFactory()) {
$factory = $definition->getFactory();
if (\is_string($factory)) {
@@ -796,7 +796,7 @@ private function addService(string $id, Definition $definition): array
}
if ($definition->isDeprecated()) {
- if ($return && 0 === strpos($return[\count($return) - 1], '@return')) {
+ if ($return && str_starts_with($return[\count($return) - 1], '@return')) {
$return[] = '';
}
@@ -1099,7 +1099,7 @@ private function addNewInstance(Definition $definition, string $return = '', str
$class = $this->dumpValue($callable[0]);
// If the class is a string we can optimize away
- if (0 === strpos($class, "'") && false === strpos($class, '$')) {
+ if (str_starts_with($class, "'") && !str_contains($class, '$')) {
if ("''" === $class) {
throw new RuntimeException(sprintf('Cannot dump definition: %s service is defined to be created by a factory but is missing the service reference, did you forget to define the factory service id or class?', $id ? 'The "'.$id.'"' : 'inline'));
}
@@ -1107,7 +1107,7 @@ private function addNewInstance(Definition $definition, string $return = '', str
return $return.sprintf('%s::%s(%s)', $this->dumpLiteralClass($class), $callable[1], $arguments ? implode(', ', $arguments) : '').$tail;
}
- if (0 === strpos($class, 'new ')) {
+ if (str_starts_with($class, 'new ')) {
return $return.sprintf('(%s)->%s(%s)', $class, $callable[1], $arguments ? implode(', ', $arguments) : '').$tail;
}
@@ -1828,16 +1828,16 @@ private function dumpValue($value, bool $interpolate = true): string
*/
private function dumpLiteralClass(string $class): string
{
- if (false !== strpos($class, '$')) {
+ if (str_contains($class, '$')) {
return sprintf('${($_ = %s) && false ?: "_"}', $class);
}
- if (0 !== strpos($class, "'") || !preg_match('/^\'(?:\\\{2})?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(?:\\\{2}[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*\'$/', $class)) {
+ if (!str_starts_with($class, "'") || !preg_match('/^\'(?:\\\{2})?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(?:\\\{2}[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*\'$/', $class)) {
throw new RuntimeException(sprintf('Cannot dump definition because of invalid class name (%s).', $class ?: 'n/a'));
}
$class = substr(str_replace('\\\\', '\\', $class), 1, -1);
- return 0 === strpos($class, '\\') ? $class : '\\'.$class;
+ return str_starts_with($class, '\\') ? $class : '\\'.$class;
}
private function dumpParameter(string $name): string
@@ -2085,7 +2085,7 @@ private function doExport($value, bool $resolveEnv = false)
if ($shouldCacheValue && isset($this->exportedVariables[$value])) {
return $this->exportedVariables[$value];
}
- if (\is_string($value) && false !== strpos($value, "\n")) {
+ if (\is_string($value) && str_contains($value, "\n")) {
$cleanParts = explode("\n", $value);
$cleanParts = array_map(function ($part) { return var_export($part, true); }, $cleanParts);
$export = implode('."\n".', $cleanParts);
@@ -2131,7 +2131,7 @@ private function getAutoloadFile(): ?string
}
foreach (get_declared_classes() as $class) {
- if (0 === strpos($class, 'ComposerAutoloaderInit') && $class::getLoader() === $autoloader[0]) {
+ if (str_starts_with($class, 'ComposerAutoloaderInit') && $class::getLoader() === $autoloader[0]) {
$file = \dirname((new \ReflectionClass($class))->getFileName(), 2).'/autoload.php';
if (null !== $this->targetDirRegex && preg_match($this->targetDirRegex.'A', $file)) {
diff --git a/src/Symfony/Component/DependencyInjection/Dumper/YamlDumper.php b/src/Symfony/Component/DependencyInjection/Dumper/YamlDumper.php
index 5dce997d9df9d..e053d3b6cdf31 100644
--- a/src/Symfony/Component/DependencyInjection/Dumper/YamlDumper.php
+++ b/src/Symfony/Component/DependencyInjection/Dumper/YamlDumper.php
@@ -325,7 +325,7 @@ private function prepareParameters(array $parameters, bool $escape = true): arra
foreach ($parameters as $key => $value) {
if (\is_array($value)) {
$value = $this->prepareParameters($value, $escape);
- } elseif ($value instanceof Reference || \is_string($value) && 0 === strpos($value, '@')) {
+ } elseif ($value instanceof Reference || \is_string($value) && str_starts_with($value, '@')) {
$value = '@'.$value;
}
diff --git a/src/Symfony/Component/DependencyInjection/EnvVarProcessor.php b/src/Symfony/Component/DependencyInjection/EnvVarProcessor.php
index d9809959d5895..adf9c311f3817 100644
--- a/src/Symfony/Component/DependencyInjection/EnvVarProcessor.php
+++ b/src/Symfony/Component/DependencyInjection/EnvVarProcessor.php
@@ -129,7 +129,7 @@ public function getEnv($prefix, $name, \Closure $getEnv)
$env = $getEnv($name);
} elseif (isset($_ENV[$name])) {
$env = $_ENV[$name];
- } elseif (isset($_SERVER[$name]) && 0 !== strpos($name, 'HTTP_')) {
+ } elseif (isset($_SERVER[$name]) && !str_starts_with($name, 'HTTP_')) {
$env = $_SERVER[$name];
} elseif (false === ($env = getenv($name)) || null === $env) { // null is a possible value because of thread safety issues
foreach ($this->loadedVars as $vars) {
diff --git a/src/Symfony/Component/DependencyInjection/Extension/Extension.php b/src/Symfony/Component/DependencyInjection/Extension/Extension.php
index 98d78808779ac..01c1e0014647c 100644
--- a/src/Symfony/Component/DependencyInjection/Extension/Extension.php
+++ b/src/Symfony/Component/DependencyInjection/Extension/Extension.php
@@ -81,7 +81,7 @@ public function getConfiguration(array $config, ContainerBuilder $container)
{
$class = static::class;
- if (false !== strpos($class, "\0")) {
+ if (str_contains($class, "\0")) {
return null; // ignore anonymous classes
}
diff --git a/src/Symfony/Component/DependencyInjection/Loader/FileLoader.php b/src/Symfony/Component/DependencyInjection/Loader/FileLoader.php
index a6e8115a7dfab..d5a6e2e55667f 100644
--- a/src/Symfony/Component/DependencyInjection/Loader/FileLoader.php
+++ b/src/Symfony/Component/DependencyInjection/Loader/FileLoader.php
@@ -179,7 +179,7 @@ private function findClasses(string $namespace, string $pattern, array $excludeP
if (null === $prefixLen) {
$prefixLen = \strlen($resource->getPrefix());
- if ($excludePrefix && 0 !== strpos($excludePrefix, $resource->getPrefix())) {
+ if ($excludePrefix && !str_starts_with($excludePrefix, $resource->getPrefix())) {
throw new InvalidArgumentException(sprintf('Invalid "exclude" pattern when importing classes for "%s": make sure your "exclude" pattern (%s) is a subset of the "resource" pattern (%s).', $namespace, $excludePattern, $pattern));
}
}
diff --git a/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php b/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php
index 7a92cc3b35b1c..968a3f5eebff5 100644
--- a/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php
+++ b/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php
@@ -337,7 +337,7 @@ private function parseDefinition(\DOMElement $service, string $file, array $defa
continue;
}
- if (false !== strpos($name, '-') && false === strpos($name, '_') && !\array_key_exists($normalizedName = str_replace('-', '_', $name), $parameters)) {
+ if (str_contains($name, '-') && !str_contains($name, '_') && !\array_key_exists($normalizedName = str_replace('-', '_', $name), $parameters)) {
$parameters[$normalizedName] = XmlUtils::phpize($node->nodeValue);
}
// keep not normalized key
@@ -622,7 +622,7 @@ public function validateSchema(\DOMDocument $dom)
array_shift($parts);
$locationstart = 'phar:///';
}
- } elseif ('\\' === \DIRECTORY_SEPARATOR && 0 === strpos($location, '\\\\')) {
+ } elseif ('\\' === \DIRECTORY_SEPARATOR && str_starts_with($location, '\\\\')) {
$locationstart = '';
}
$drive = '\\' === \DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
diff --git a/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php b/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php
index 20780ad6facad..66d0335265847 100644
--- a/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php
+++ b/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php
@@ -221,7 +221,7 @@ private function parseDefinitions(array $content, string $file)
if (!$service || !\is_array($service)) {
throw new InvalidArgumentException(sprintf('Type definition "%s" must be a non-empty array within "_instanceof" in "%s". Check your YAML syntax.', $id, $file));
}
- if (\is_string($service) && 0 === strpos($service, '@')) {
+ if (\is_string($service) && str_starts_with($service, '@')) {
throw new InvalidArgumentException(sprintf('Type definition "%s" cannot be an alias within "_instanceof" in "%s". Check your YAML syntax.', $id, $file));
}
$this->parseDefinition($id, $service, $file, []);
@@ -300,7 +300,7 @@ private function parseDefaults(array &$content, string $file): array
private function isUsingShortSyntax(array $service): bool
{
foreach ($service as $key => $value) {
- if (\is_string($key) && ('' === $key || ('$' !== $key[0] && false === strpos($key, '\\')))) {
+ if (\is_string($key) && ('' === $key || ('$' !== $key[0] && !str_contains($key, '\\')))) {
return false;
}
}
@@ -321,7 +321,7 @@ private function parseDefinition(string $id, $service, string $file, array $defa
throw new InvalidArgumentException(sprintf('Service names that start with an underscore are reserved. Rename the "%s" service or define it in XML instead.', $id));
}
- if (\is_string($service) && 0 === strpos($service, '@')) {
+ if (\is_string($service) && str_starts_with($service, '@')) {
$this->container->setAlias($id, $alias = new Alias(substr($service, 1)));
if (isset($defaults['public'])) {
$alias->setPublic($defaults['public']);
@@ -628,14 +628,14 @@ private function parseCallable($callable, string $parameter, string $id, string
{
if (\is_string($callable)) {
if ('' !== $callable && '@' === $callable[0]) {
- if (false === strpos($callable, ':')) {
+ if (!str_contains($callable, ':')) {
return [$this->resolveServices($callable, $file), '__invoke'];
}
throw new InvalidArgumentException(sprintf('The value of the "%s" option for the "%s" service must be the id of the service without the "@" prefix (replace "%s" with "%s" in "%s").', $parameter, $id, $callable, substr($callable, 1), $file));
}
- if (false !== strpos($callable, ':') && false === strpos($callable, '::')) {
+ if (str_contains($callable, ':') && !str_contains($callable, '::')) {
$parts = explode(':', $callable);
@trigger_error(sprintf('Using short %s syntax for service "%s" is deprecated since Symfony 4.4, use "[\'@%s\', \'%s\']" instead.', $parameter, $id, ...$parts), \E_USER_DEPRECATED);
@@ -821,20 +821,20 @@ private function resolveServices($value, string $file, bool $isParameter = false
foreach ($value as $k => $v) {
$value[$k] = $this->resolveServices($v, $file, $isParameter);
}
- } elseif (\is_string($value) && 0 === strpos($value, '@=')) {
+ } elseif (\is_string($value) && str_starts_with($value, '@=')) {
if (!class_exists(Expression::class)) {
throw new \LogicException('The "@=" expression syntax cannot be used without the ExpressionLanguage component. Try running "composer require symfony/expression-language".');
}
return new Expression(substr($value, 2));
- } elseif (\is_string($value) && 0 === strpos($value, '@')) {
- if (0 === strpos($value, '@@')) {
+ } elseif (\is_string($value) && str_starts_with($value, '@')) {
+ if (str_starts_with($value, '@@')) {
$value = substr($value, 1);
$invalidBehavior = null;
- } elseif (0 === strpos($value, '@!')) {
+ } elseif (str_starts_with($value, '@!')) {
$value = substr($value, 2);
$invalidBehavior = ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE;
- } elseif (0 === strpos($value, '@?')) {
+ } elseif (str_starts_with($value, '@?')) {
$value = substr($value, 2);
$invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
} else {
diff --git a/src/Symfony/Component/DependencyInjection/ParameterBag/EnvPlaceholderParameterBag.php b/src/Symfony/Component/DependencyInjection/ParameterBag/EnvPlaceholderParameterBag.php
index 2ee1fd5cbfef3..22f6812093c9f 100644
--- a/src/Symfony/Component/DependencyInjection/ParameterBag/EnvPlaceholderParameterBag.php
+++ b/src/Symfony/Component/DependencyInjection/ParameterBag/EnvPlaceholderParameterBag.php
@@ -31,7 +31,7 @@ class EnvPlaceholderParameterBag extends ParameterBag
*/
public function get($name)
{
- if (0 === strpos($name, 'env(') && str_ends_with($name, ')') && 'env()' !== $name) {
+ if (str_starts_with($name, 'env(') && str_ends_with($name, ')') && 'env()' !== $name) {
$env = substr($name, 4, -1);
if (isset($this->envPlaceholders[$env])) {
diff --git a/src/Symfony/Component/DependencyInjection/ParameterBag/ParameterBag.php b/src/Symfony/Component/DependencyInjection/ParameterBag/ParameterBag.php
index a2de1a4f542fe..7a9f3814e9394 100644
--- a/src/Symfony/Component/DependencyInjection/ParameterBag/ParameterBag.php
+++ b/src/Symfony/Component/DependencyInjection/ParameterBag/ParameterBag.php
@@ -71,13 +71,13 @@ public function get($name)
$alternatives = [];
foreach ($this->parameters as $key => $parameterValue) {
$lev = levenshtein($name, $key);
- if ($lev <= \strlen($name) / 3 || false !== strpos($key, $name)) {
+ if ($lev <= \strlen($name) / 3 || str_contains($key, $name)) {
$alternatives[] = $key;
}
}
$nonNestedAlternative = null;
- if (!\count($alternatives) && false !== strpos($name, '.')) {
+ if (!\count($alternatives) && str_contains($name, '.')) {
$namePartsLength = array_map('strlen', explode('.', $name));
$key = substr($name, 0, -1 * (1 + array_pop($namePartsLength)));
while (\count($namePartsLength)) {
diff --git a/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php b/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php
index 78a8edd1f0057..7cbd9acdd5f31 100644
--- a/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php
+++ b/src/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.php
@@ -1008,7 +1008,7 @@ public function testResources()
$container->addResource($b = new FileResource(__DIR__.'/Fixtures/xml/services2.xml'));
$resources = [];
foreach ($container->getResources() as $resource) {
- if (false === strpos($resource, '.php')) {
+ if (!str_contains($resource, '.php')) {
$resources[] = $resource;
}
}
@@ -1028,7 +1028,7 @@ public function testFileExists()
$resources = [];
foreach ($container->getResources() as $resource) {
- if (false === strpos($resource, '.php')) {
+ if (!str_contains($resource, '.php')) {
$resources[] = $resource;
}
}
diff --git a/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php
index ef00b2f721608..e50e4cd4861e8 100644
--- a/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php
+++ b/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php
@@ -531,7 +531,7 @@ public function testExtensions()
public function testExtensionInPhar()
{
- if (\extension_loaded('suhosin') && false === strpos(ini_get('suhosin.executor.include.whitelist'), 'phar')) {
+ if (\extension_loaded('suhosin') && !str_contains(ini_get('suhosin.executor.include.whitelist'), 'phar')) {
$this->markTestSkipped('To run this test, add "phar" to the "suhosin.executor.include.whitelist" settings in your php.ini file.');
}
diff --git a/src/Symfony/Component/DomCrawler/AbstractUriElement.php b/src/Symfony/Component/DomCrawler/AbstractUriElement.php
index 2439877f061f2..7c7aecc6f74b8 100644
--- a/src/Symfony/Component/DomCrawler/AbstractUriElement.php
+++ b/src/Symfony/Component/DomCrawler/AbstractUriElement.php
@@ -104,7 +104,7 @@ public function getUri()
}
// absolute URL with relative schema
- if (0 === strpos($uri, '//')) {
+ if (str_starts_with($uri, '//')) {
return preg_replace('#^([^/]*)//.*$#', '$1', $baseUri).$uri;
}
diff --git a/src/Symfony/Component/DomCrawler/Crawler.php b/src/Symfony/Component/DomCrawler/Crawler.php
index f8839e875b157..3f5c2a50d6fec 100644
--- a/src/Symfony/Component/DomCrawler/Crawler.php
+++ b/src/Symfony/Component/DomCrawler/Crawler.php
@@ -148,7 +148,7 @@ public function add($node)
public function addContent($content, $type = null)
{
if (empty($type)) {
- $type = 0 === strpos($content, ' $value) {
- $notHttpName = 0 !== strpos($name, 'HTTP_');
+ $notHttpName = !str_starts_with($name, 'HTTP_');
// don't check existence with getenv() because of thread safety issues
if (!isset($loadedVars[$name]) && (!$overrideExistingVars && (isset($_ENV[$name]) || (isset($_SERVER[$name]) && $notHttpName)))) {
continue;
@@ -372,7 +372,7 @@ private function skipEmptyLines()
private function resolveCommands(string $value, array $loadedVars): string
{
- if (false === strpos($value, '$')) {
+ if (!str_contains($value, '$')) {
return $value;
}
@@ -408,7 +408,7 @@ private function resolveCommands(string $value, array $loadedVars): string
$env = [];
foreach ($this->values as $name => $value) {
- if (isset($loadedVars[$name]) || (!isset($_ENV[$name]) && !(isset($_SERVER[$name]) && 0 !== strpos($name, 'HTTP_')))) {
+ if (isset($loadedVars[$name]) || (!isset($_ENV[$name]) && !(isset($_SERVER[$name]) && !str_starts_with($name, 'HTTP_')))) {
$env[$name] = $value;
}
}
@@ -426,7 +426,7 @@ private function resolveCommands(string $value, array $loadedVars): string
private function resolveVariables(string $value, array $loadedVars): string
{
- if (false === strpos($value, '$')) {
+ if (!str_contains($value, '$')) {
return $value;
}
@@ -461,7 +461,7 @@ private function resolveVariables(string $value, array $loadedVars): string
$value = $this->values[$name];
} elseif (isset($_ENV[$name])) {
$value = $_ENV[$name];
- } elseif (isset($_SERVER[$name]) && 0 !== strpos($name, 'HTTP_')) {
+ } elseif (isset($_SERVER[$name]) && !str_starts_with($name, 'HTTP_')) {
$value = $_SERVER[$name];
} elseif (isset($this->values[$name])) {
$value = $this->values[$name];
diff --git a/src/Symfony/Component/Dotenv/composer.json b/src/Symfony/Component/Dotenv/composer.json
index a6f7fdd7904aa..037d039f4a921 100644
--- a/src/Symfony/Component/Dotenv/composer.json
+++ b/src/Symfony/Component/Dotenv/composer.json
@@ -16,7 +16,8 @@
}
],
"require": {
- "php": ">=7.1.3"
+ "php": ">=7.1.3",
+ "symfony/polyfill-php80": "^1.16"
},
"require-dev": {
"symfony/process": "^3.4.2|^4.0|^5.0"
diff --git a/src/Symfony/Component/ErrorHandler/BufferingLogger.php b/src/Symfony/Component/ErrorHandler/BufferingLogger.php
index 72be64d1278a4..4c27685a845fb 100644
--- a/src/Symfony/Component/ErrorHandler/BufferingLogger.php
+++ b/src/Symfony/Component/ErrorHandler/BufferingLogger.php
@@ -48,7 +48,7 @@ public function __wakeup()
public function __destruct()
{
foreach ($this->logs as [$level, $message, $context]) {
- if (false !== strpos($message, '{')) {
+ if (str_contains($message, '{')) {
foreach ($context as $key => $val) {
if (null === $val || is_scalar($val) || (\is_object($val) && \is_callable([$val, '__toString']))) {
$message = str_replace("{{$key}}", $val, $message);
diff --git a/src/Symfony/Component/ErrorHandler/DebugClassLoader.php b/src/Symfony/Component/ErrorHandler/DebugClassLoader.php
index c67ca9f3e841a..cab601c23c707 100644
--- a/src/Symfony/Component/ErrorHandler/DebugClassLoader.php
+++ b/src/Symfony/Component/ErrorHandler/DebugClassLoader.php
@@ -396,7 +396,7 @@ private function checkClass(string $class, string $file = null): void
}
if (!$exists) {
- if (false !== strpos($class, '/')) {
+ if (str_contains($class, '/')) {
throw new \RuntimeException(sprintf('Trying to autoload a class with an invalid name "%s". Be careful that the namespace separator is "\" in PHP, not "/".', $class));
}
@@ -419,7 +419,7 @@ public function checkAnnotations(\ReflectionClass $refl, string $class): array
}
$deprecations = [];
- $className = false !== strpos($class, "@anonymous\0") ? (get_parent_class($class) ?: key(class_implements($class)) ?: 'class').'@anonymous' : $class;
+ $className = str_contains($class, "@anonymous\0") ? (get_parent_class($class) ?: key(class_implements($class)) ?: 'class').'@anonymous' : $class;
// Don't trigger deprecations for classes in the same vendor
if ($class !== $className) {
@@ -435,17 +435,17 @@ public function checkAnnotations(\ReflectionClass $refl, string $class): array
// Detect annotations on the class
if (false !== $doc = $refl->getDocComment()) {
foreach (['final', 'deprecated', 'internal'] as $annotation) {
- if (false !== strpos($doc, $annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$|\r?\n)#s', $doc, $notice)) {
+ if (str_contains($doc, $annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$|\r?\n)#s', $doc, $notice)) {
self::${$annotation}[$class] = isset($notice[1]) ? preg_replace('#\.?\r?\n( \*)? *(?= |\r?\n|$)#', '', $notice[1]) : '';
}
}
- if ($refl->isInterface() && false !== strpos($doc, 'method') && preg_match_all('#\n \* @method\s+(static\s+)?+([\w\|&\[\]\\\]+\s+)?(\w+(?:\s*\([^\)]*\))?)+(.+?([[:punct:]]\s*)?)?(?=\r?\n \*(?: @|/$|\r?\n))#', $doc, $notice, \PREG_SET_ORDER)) {
+ if ($refl->isInterface() && str_contains($doc, 'method') && preg_match_all('#\n \* @method\s+(static\s+)?+([\w\|&\[\]\\\]+\s+)?(\w+(?:\s*\([^\)]*\))?)+(.+?([[:punct:]]\s*)?)?(?=\r?\n \*(?: @|/$|\r?\n))#', $doc, $notice, \PREG_SET_ORDER)) {
foreach ($notice as $method) {
$static = '' !== $method[1] && !empty($method[2]);
$name = $method[3];
$description = $method[4] ?? null;
- if (false === strpos($name, '(')) {
+ if (!str_contains($name, '(')) {
$name .= '()';
}
if (null !== $description) {
@@ -496,7 +496,7 @@ public function checkAnnotations(\ReflectionClass $refl, string $class): array
}
} elseif (!$refl->isInterface()) {
if (!strncmp($vendor, str_replace('_', '\\', $use), $vendorLen)
- && 0 === strpos($className, 'Symfony\\')
+ && str_starts_with($className, 'Symfony\\')
&& (!class_exists(InstalledVersions::class)
|| 'symfony/symfony' !== InstalledVersions::getRootPackage()['name'])
) {
@@ -597,12 +597,12 @@ public function checkAnnotations(\ReflectionClass $refl, string $class): array
$forcePatchTypes = $this->patchTypes['force'];
- if ($canAddReturnType = null !== $forcePatchTypes && false === strpos($method->getFileName(), \DIRECTORY_SEPARATOR.'vendor'.\DIRECTORY_SEPARATOR)) {
+ if ($canAddReturnType = null !== $forcePatchTypes && !str_contains($method->getFileName(), \DIRECTORY_SEPARATOR.'vendor'.\DIRECTORY_SEPARATOR)) {
if ('void' !== (self::MAGIC_METHODS[$method->name] ?? 'void')) {
$this->patchTypes['force'] = $forcePatchTypes ?: 'docblock';
}
- $canAddReturnType = false !== strpos($refl->getFileName(), \DIRECTORY_SEPARATOR.'Tests'.\DIRECTORY_SEPARATOR)
+ $canAddReturnType = str_contains($refl->getFileName(), \DIRECTORY_SEPARATOR.'Tests'.\DIRECTORY_SEPARATOR)
|| $refl->isFinal()
|| $method->isFinal()
|| $method->isPrivate()
@@ -623,8 +623,8 @@ public function checkAnnotations(\ReflectionClass $refl, string $class): array
$this->patchMethod($method, $returnType, $declaringFile, $normalizedType);
}
- if (false === strpos($doc, '* @deprecated') && strncmp($ns, $declaringClass, $len)) {
- if ($canAddReturnType && 'docblock' === $this->patchTypes['force'] && false === strpos($method->getFileName(), \DIRECTORY_SEPARATOR.'vendor'.\DIRECTORY_SEPARATOR)) {
+ if (!str_contains($doc, '* @deprecated') && strncmp($ns, $declaringClass, $len)) {
+ if ($canAddReturnType && 'docblock' === $this->patchTypes['force'] && !str_contains($method->getFileName(), \DIRECTORY_SEPARATOR.'vendor'.\DIRECTORY_SEPARATOR)) {
$this->patchMethod($method, $returnType, $declaringFile, $normalizedType);
} elseif ('' !== $declaringClass && $this->patchTypes['deprecations']) {
$deprecations[] = sprintf('Method "%s::%s()" will return "%s" as of its next major version. Doing the same in %s "%s" will be required when upgrading.', $declaringClass, $method->name, $normalizedType, interface_exists($declaringClass) ? 'implementation' : 'child class', $className);
@@ -640,7 +640,7 @@ public function checkAnnotations(\ReflectionClass $refl, string $class): array
$matches = [];
- if (!$method->hasReturnType() && ((false !== strpos($doc, '@return') && preg_match('/\n\s+\* @return +([^\s<(]+)/', $doc, $matches)) || 'void' !== (self::MAGIC_METHODS[$method->name] ?? 'void'))) {
+ if (!$method->hasReturnType() && ((str_contains($doc, '@return') && preg_match('/\n\s+\* @return +([^\s<(]+)/', $doc, $matches)) || 'void' !== (self::MAGIC_METHODS[$method->name] ?? 'void'))) {
$matches = $matches ?: [1 => self::MAGIC_METHODS[$method->name]];
$this->setReturnType($matches[1], $method, $parent);
@@ -662,14 +662,14 @@ public function checkAnnotations(\ReflectionClass $refl, string $class): array
$finalOrInternal = false;
foreach (['final', 'internal'] as $annotation) {
- if (false !== strpos($doc, $annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$|\r?\n)#s', $doc, $notice)) {
+ if (str_contains($doc, $annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$|\r?\n)#s', $doc, $notice)) {
$message = isset($notice[1]) ? preg_replace('#\.?\r?\n( \*)? *(?= |\r?\n|$)#', '', $notice[1]) : '';
self::${$annotation.'Methods'}[$class][$method->name] = [$class, $message];
$finalOrInternal = true;
}
}
- if ($finalOrInternal || $method->isConstructor() || false === strpos($doc, '@param') || StatelessInvocation::class === $class) {
+ if ($finalOrInternal || $method->isConstructor() || !str_contains($doc, '@param') || StatelessInvocation::class === $class) {
continue;
}
if (!preg_match_all('#\n\s+\* @param +((?(?!callable *\().*?|callable *\(.*\).*?))(?<= )\$([a-zA-Z0-9_\x7f-\xff]++)#', $doc, $matches, \PREG_SET_ORDER)) {
@@ -850,7 +850,7 @@ private function setReturnType(string $types, \ReflectionMethod $method, ?string
$iterable = $object = true;
foreach ($typesMap as $n => $t) {
if ('null' !== $n) {
- $iterable = $iterable && (\in_array($n, ['array', 'iterable']) || false !== strpos($n, 'Iterator'));
+ $iterable = $iterable && (\in_array($n, ['array', 'iterable']) || str_contains($n, 'Iterator'));
$object = $object && (\in_array($n, ['callable', 'object', '$this', 'static']) || !isset(self::SPECIAL_RETURN_TYPES[$n]));
}
}
@@ -1034,15 +1034,15 @@ private static function getUseStatements(string $file): array
break;
}
- if (0 === strpos($file[$i], 'namespace ')) {
+ if (str_starts_with($file[$i], 'namespace ')) {
$namespace = substr($file[$i], \strlen('namespace '), -2).'\\';
$useOffset = $i + 2;
}
- if (0 === strpos($file[$i], 'use ')) {
+ if (str_starts_with($file[$i], 'use ')) {
$useOffset = $i;
- for (; 0 === strpos($file[$i], 'use '); ++$i) {
+ for (; str_starts_with($file[$i], 'use '); ++$i) {
$u = explode(' as ', substr($file[$i], 4, -2), 2);
if (1 === \count($u)) {
diff --git a/src/Symfony/Component/ErrorHandler/ErrorEnhancer/ClassNotFoundErrorEnhancer.php b/src/Symfony/Component/ErrorHandler/ErrorEnhancer/ClassNotFoundErrorEnhancer.php
index 96a58be800e4b..25a622820b7d9 100644
--- a/src/Symfony/Component/ErrorHandler/ErrorEnhancer/ClassNotFoundErrorEnhancer.php
+++ b/src/Symfony/Component/ErrorHandler/ErrorEnhancer/ClassNotFoundErrorEnhancer.php
@@ -145,7 +145,7 @@ private function convertFileToClass(string $path, string $file, string $prefix):
];
if ($prefix) {
- $candidates = array_filter($candidates, function ($candidate) use ($prefix) { return 0 === strpos($candidate, $prefix); });
+ $candidates = array_filter($candidates, function ($candidate) use ($prefix) { return str_starts_with($candidate, $prefix); });
}
// We cannot use the autoloader here as most of them use require; but if the class
diff --git a/src/Symfony/Component/ErrorHandler/ErrorEnhancer/UndefinedFunctionErrorEnhancer.php b/src/Symfony/Component/ErrorHandler/ErrorEnhancer/UndefinedFunctionErrorEnhancer.php
index f4c49c2856c22..2e3838a84d382 100644
--- a/src/Symfony/Component/ErrorHandler/ErrorEnhancer/UndefinedFunctionErrorEnhancer.php
+++ b/src/Symfony/Component/ErrorHandler/ErrorEnhancer/UndefinedFunctionErrorEnhancer.php
@@ -42,7 +42,7 @@ public function enhance(\Throwable $error): ?\Throwable
$prefix = 'Call to undefined function ';
$prefixLen = \strlen($prefix);
- if (0 !== strpos($message, $prefix)) {
+ if (!str_starts_with($message, $prefix)) {
return null;
}
diff --git a/src/Symfony/Component/ErrorHandler/ErrorEnhancer/UndefinedMethodErrorEnhancer.php b/src/Symfony/Component/ErrorHandler/ErrorEnhancer/UndefinedMethodErrorEnhancer.php
index c4355f92ce089..d5eb6d6b1e4a6 100644
--- a/src/Symfony/Component/ErrorHandler/ErrorEnhancer/UndefinedMethodErrorEnhancer.php
+++ b/src/Symfony/Component/ErrorHandler/ErrorEnhancer/UndefinedMethodErrorEnhancer.php
@@ -47,7 +47,7 @@ public function enhance(\Throwable $error): ?\Throwable
$candidates = [];
foreach ($methods as $definedMethodName) {
$lev = levenshtein($methodName, $definedMethodName);
- if ($lev <= \strlen($methodName) / 3 || false !== strpos($definedMethodName, $methodName)) {
+ if ($lev <= \strlen($methodName) / 3 || str_contains($definedMethodName, $methodName)) {
$candidates[] = $definedMethodName;
}
}
diff --git a/src/Symfony/Component/ErrorHandler/ErrorHandler.php b/src/Symfony/Component/ErrorHandler/ErrorHandler.php
index e6e21d601700e..3851eea72a8be 100644
--- a/src/Symfony/Component/ErrorHandler/ErrorHandler.php
+++ b/src/Symfony/Component/ErrorHandler/ErrorHandler.php
@@ -400,7 +400,7 @@ private function reRegister(int $prev): void
*/
public function handleError(int $type, string $message, string $file, int $line): bool
{
- if (\PHP_VERSION_ID >= 70300 && \E_WARNING === $type && '"' === $message[0] && false !== strpos($message, '" targeting switch is equivalent to "break')) {
+ if (\PHP_VERSION_ID >= 70300 && \E_WARNING === $type && '"' === $message[0] && str_contains($message, '" targeting switch is equivalent to "break')) {
$type = \E_DEPRECATED;
}
@@ -451,7 +451,7 @@ public function handleError(int $type, string $message, string $file, int $line)
return true;
}
} else {
- if (false !== strpos($message, '@anonymous')) {
+ if (str_contains($message, '@anonymous')) {
$backtrace = debug_backtrace(false, 5);
for ($i = 1; isset($backtrace[$i]); ++$i) {
@@ -560,7 +560,7 @@ public function handleException(\Throwable $exception)
}
if ($this->loggedErrors & $type) {
- if (false !== strpos($message = $exception->getMessage(), "@anonymous\0")) {
+ if (str_contains($message = $exception->getMessage(), "@anonymous\0")) {
$message = $this->parseAnonymousClass($message);
}
@@ -674,7 +674,7 @@ public static function handleFatalError(array $error = null): void
$handler->throwAt(0, true);
$trace = $error['backtrace'] ?? null;
- if (0 === strpos($error['message'], 'Allowed memory') || 0 === strpos($error['message'], 'Out of memory')) {
+ if (str_starts_with($error['message'], 'Allowed memory') || str_starts_with($error['message'], 'Out of memory')) {
$fatalError = new OutOfMemoryError($handler->levels[$error['type']].': '.$error['message'], 0, $error, 2, false, $trace);
} else {
$fatalError = new FatalError($handler->levels[$error['type']].': '.$error['message'], 0, $error, 2, true, $trace);
diff --git a/src/Symfony/Component/ErrorHandler/ErrorRenderer/HtmlErrorRenderer.php b/src/Symfony/Component/ErrorHandler/ErrorRenderer/HtmlErrorRenderer.php
index 69e1b9ce74555..95df271cc7112 100644
--- a/src/Symfony/Component/ErrorHandler/ErrorRenderer/HtmlErrorRenderer.php
+++ b/src/Symfony/Component/ErrorHandler/ErrorRenderer/HtmlErrorRenderer.php
@@ -199,7 +199,7 @@ private function getFileRelative(string $file): ?string
{
$file = str_replace('\\', '/', $file);
- if (null !== $this->projectDir && 0 === strpos($file, $this->projectDir)) {
+ if (null !== $this->projectDir && str_starts_with($file, $this->projectDir)) {
return ltrim(substr($file, \strlen($this->projectDir)), '/');
}
@@ -316,7 +316,7 @@ private function formatFileFromText(string $text)
private function formatLogMessage(string $message, array $context)
{
- if ($context && false !== strpos($message, '{')) {
+ if ($context && str_contains($message, '{')) {
$replacements = [];
foreach ($context as $key => $val) {
if (is_scalar($val)) {
diff --git a/src/Symfony/Component/ErrorHandler/Exception/FlattenException.php b/src/Symfony/Component/ErrorHandler/Exception/FlattenException.php
index 330b5cc3f4bd0..9b0949d718319 100644
--- a/src/Symfony/Component/ErrorHandler/Exception/FlattenException.php
+++ b/src/Symfony/Component/ErrorHandler/Exception/FlattenException.php
@@ -171,7 +171,7 @@ public function getClass(): string
*/
public function setClass($class): self
{
- $this->class = false !== strpos($class, "@anonymous\0") ? (get_parent_class($class) ?: key(class_implements($class)) ?: 'class').'@anonymous' : $class;
+ $this->class = str_contains($class, "@anonymous\0") ? (get_parent_class($class) ?: key(class_implements($class)) ?: 'class').'@anonymous' : $class;
return $this;
}
@@ -234,7 +234,7 @@ public function getMessage(): string
*/
public function setMessage($message): self
{
- if (false !== strpos($message, "@anonymous\0")) {
+ if (str_contains($message, "@anonymous\0")) {
$message = preg_replace_callback('/[a-zA-Z_\x7f-\xff][\\\\a-zA-Z0-9_\x7f-\xff]*+@anonymous\x00.*?\.php(?:0x?|:[0-9]++\$)[0-9a-fA-F]++/', function ($m) {
return class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0];
}, $message);
diff --git a/src/Symfony/Component/EventDispatcher/Debug/WrappedListener.php b/src/Symfony/Component/EventDispatcher/Debug/WrappedListener.php
index e047639081c78..9b910e6677e05 100644
--- a/src/Symfony/Component/EventDispatcher/Debug/WrappedListener.php
+++ b/src/Symfony/Component/EventDispatcher/Debug/WrappedListener.php
@@ -52,7 +52,7 @@ public function __construct($listener, ?string $name, Stopwatch $stopwatch, Even
$this->pretty = $this->name.'::'.$listener[1];
} elseif ($listener instanceof \Closure) {
$r = new \ReflectionFunction($listener);
- if (false !== strpos($r->name, '{closure}')) {
+ if (str_contains($r->name, '{closure}')) {
$this->pretty = $this->name = 'closure';
} elseif ($class = $r->getClosureScopeClass()) {
$this->name = $class->name;
diff --git a/src/Symfony/Component/EventDispatcher/composer.json b/src/Symfony/Component/EventDispatcher/composer.json
index 0a518a54e8855..55c2716a63bd1 100644
--- a/src/Symfony/Component/EventDispatcher/composer.json
+++ b/src/Symfony/Component/EventDispatcher/composer.json
@@ -17,7 +17,8 @@
],
"require": {
"php": ">=7.1.3",
- "symfony/event-dispatcher-contracts": "^1.1"
+ "symfony/event-dispatcher-contracts": "^1.1",
+ "symfony/polyfill-php80": "^1.16"
},
"require-dev": {
"symfony/dependency-injection": "^3.4|^4.0|^5.0",
diff --git a/src/Symfony/Component/ExpressionLanguage/Lexer.php b/src/Symfony/Component/ExpressionLanguage/Lexer.php
index 46d3e1c0c38e6..af859318d50d6 100644
--- a/src/Symfony/Component/ExpressionLanguage/Lexer.php
+++ b/src/Symfony/Component/ExpressionLanguage/Lexer.php
@@ -50,13 +50,13 @@ public function tokenize($expression)
}
$tokens[] = new Token(Token::NUMBER_TYPE, $number, $cursor + 1);
$cursor += \strlen($match[0]);
- } elseif (false !== strpos('([{', $expression[$cursor])) {
+ } elseif (str_contains('([{', $expression[$cursor])) {
// opening bracket
$brackets[] = [$expression[$cursor], $cursor];
$tokens[] = new Token(Token::PUNCTUATION_TYPE, $expression[$cursor], $cursor + 1);
++$cursor;
- } elseif (false !== strpos(')]}', $expression[$cursor])) {
+ } elseif (str_contains(')]}', $expression[$cursor])) {
// closing bracket
if (empty($brackets)) {
throw new SyntaxError(sprintf('Unexpected "%s".', $expression[$cursor]), $cursor, $expression);
@@ -77,7 +77,7 @@ public function tokenize($expression)
// operators
$tokens[] = new Token(Token::OPERATOR_TYPE, $match[0], $cursor + 1);
$cursor += \strlen($match[0]);
- } elseif (false !== strpos('.,?:', $expression[$cursor])) {
+ } elseif (str_contains('.,?:', $expression[$cursor])) {
// punctuation
$tokens[] = new Token(Token::PUNCTUATION_TYPE, $expression[$cursor], $cursor + 1);
++$cursor;
diff --git a/src/Symfony/Component/ExpressionLanguage/composer.json b/src/Symfony/Component/ExpressionLanguage/composer.json
index 0e5cdadfb0573..01922550ee40f 100644
--- a/src/Symfony/Component/ExpressionLanguage/composer.json
+++ b/src/Symfony/Component/ExpressionLanguage/composer.json
@@ -18,6 +18,7 @@
"require": {
"php": ">=7.1.3",
"symfony/cache": "^3.4|^4.0|^5.0",
+ "symfony/polyfill-php80": "^1.16",
"symfony/service-contracts": "^1.1|^2"
},
"autoload": {
diff --git a/src/Symfony/Component/Filesystem/Filesystem.php b/src/Symfony/Component/Filesystem/Filesystem.php
index 675c1cd547fc4..5c9bbd12b7107 100644
--- a/src/Symfony/Component/Filesystem/Filesystem.php
+++ b/src/Symfony/Component/Filesystem/Filesystem.php
@@ -180,7 +180,7 @@ public function remove($files)
if (!self::box('rmdir', $file) && file_exists($file)) {
throw new IOException(sprintf('Failed to remove directory "%s": ', $file).self::$lastError);
}
- } elseif (!self::box('unlink', $file) && (false !== strpos(self::$lastError, 'Permission denied') || file_exists($file))) {
+ } elseif (!self::box('unlink', $file) && (str_contains(self::$lastError, 'Permission denied') || file_exists($file))) {
throw new IOException(sprintf('Failed to remove file "%s": ', $file).self::$lastError);
}
}
@@ -382,7 +382,7 @@ public function hardlink($originFile, $targetFiles)
private function linkException(string $origin, string $target, string $linkType)
{
if (self::$lastError) {
- if ('\\' === \DIRECTORY_SEPARATOR && false !== strpos(self::$lastError, 'error code(1314)')) {
+ if ('\\' === \DIRECTORY_SEPARATOR && str_contains(self::$lastError, 'error code(1314)')) {
throw new IOException(sprintf('Unable to create "%s" link due to error code 1314: \'A required privilege is not held by the client\'. Do you have the required Administrator-rights?', $linkType), 0, null, $target);
}
}
diff --git a/src/Symfony/Component/Filesystem/Tests/FilesystemTestCase.php b/src/Symfony/Component/Filesystem/Tests/FilesystemTestCase.php
index e76d1da3fe26e..738e7fffa0daa 100644
--- a/src/Symfony/Component/Filesystem/Tests/FilesystemTestCase.php
+++ b/src/Symfony/Component/Filesystem/Tests/FilesystemTestCase.php
@@ -48,7 +48,7 @@ public static function setUpBeforeClass(): void
$targetFile = tempnam(sys_get_temp_dir(), 'li');
if (true !== @link($originFile, $targetFile)) {
$report = error_get_last();
- if (\is_array($report) && false !== strpos($report['message'], 'error code(1314)')) {
+ if (\is_array($report) && str_contains($report['message'], 'error code(1314)')) {
self::$linkOnWindows = false;
}
} else {
@@ -60,7 +60,7 @@ public static function setUpBeforeClass(): void
$targetDir = tempnam(sys_get_temp_dir(), 'sl');
if (true !== @symlink($originDir, $targetDir)) {
$report = error_get_last();
- if (\is_array($report) && false !== strpos($report['message'], 'error code(1314)')) {
+ if (\is_array($report) && str_contains($report['message'], 'error code(1314)')) {
self::$symlinkOnWindows = false;
}
} else {
diff --git a/src/Symfony/Component/Filesystem/composer.json b/src/Symfony/Component/Filesystem/composer.json
index 9feb1013ef453..c943180d0c3b2 100644
--- a/src/Symfony/Component/Filesystem/composer.json
+++ b/src/Symfony/Component/Filesystem/composer.json
@@ -17,7 +17,8 @@
],
"require": {
"php": ">=7.1.3",
- "symfony/polyfill-ctype": "~1.8"
+ "symfony/polyfill-ctype": "~1.8",
+ "symfony/polyfill-php80": "^1.16"
},
"autoload": {
"psr-4": { "Symfony\\Component\\Filesystem\\": "" },
diff --git a/src/Symfony/Component/Finder/Iterator/ExcludeDirectoryFilterIterator.php b/src/Symfony/Component/Finder/Iterator/ExcludeDirectoryFilterIterator.php
index 6a1b291adea30..f37431433d0ed 100644
--- a/src/Symfony/Component/Finder/Iterator/ExcludeDirectoryFilterIterator.php
+++ b/src/Symfony/Component/Finder/Iterator/ExcludeDirectoryFilterIterator.php
@@ -34,7 +34,7 @@ public function __construct(\Iterator $iterator, array $directories)
$patterns = [];
foreach ($directories as $directory) {
$directory = rtrim($directory, '/');
- if (!$this->isRecursive || false !== strpos($directory, '/')) {
+ if (!$this->isRecursive || str_contains($directory, '/')) {
$patterns[] = preg_quote($directory, '#');
} else {
$this->excludedDirs[$directory] = true;
diff --git a/src/Symfony/Component/Finder/Tests/FinderTest.php b/src/Symfony/Component/Finder/Tests/FinderTest.php
index dbc66cbc474c7..4fb1cb4d953ae 100644
--- a/src/Symfony/Component/Finder/Tests/FinderTest.php
+++ b/src/Symfony/Component/Finder/Tests/FinderTest.php
@@ -869,7 +869,7 @@ public function testSortAcrossDirectories()
public function testFilter()
{
$finder = $this->buildFinder();
- $this->assertSame($finder, $finder->filter(function (\SplFileInfo $f) { return false !== strpos($f, 'test'); }));
+ $this->assertSame($finder, $finder->filter(function (\SplFileInfo $f) { return str_contains($f, 'test'); }));
$this->assertIterator($this->toAbsolute(['test.php', 'test.py']), $finder->in(self::$tmpDir)->getIterator());
}
diff --git a/src/Symfony/Component/Finder/Tests/Iterator/CustomFilterIteratorTest.php b/src/Symfony/Component/Finder/Tests/Iterator/CustomFilterIteratorTest.php
index 4d55b112dcadc..7c3c65ce5ee81 100644
--- a/src/Symfony/Component/Finder/Tests/Iterator/CustomFilterIteratorTest.php
+++ b/src/Symfony/Component/Finder/Tests/Iterator/CustomFilterIteratorTest.php
@@ -37,7 +37,7 @@ public function getAcceptData()
{
return [
[[function (\SplFileInfo $fileinfo) { return false; }], []],
- [[function (\SplFileInfo $fileinfo) { return 0 === strpos($fileinfo, 'test'); }], ['test.php', 'test.py']],
+ [[function (\SplFileInfo $fileinfo) { return str_starts_with($fileinfo, 'test'); }], ['test.php', 'test.py']],
[['is_dir'], []],
];
}
diff --git a/src/Symfony/Component/Finder/Tests/Iterator/MockSplFileInfo.php b/src/Symfony/Component/Finder/Tests/Iterator/MockSplFileInfo.php
index bc80ed2e1e856..028e35845251d 100644
--- a/src/Symfony/Component/Finder/Tests/Iterator/MockSplFileInfo.php
+++ b/src/Symfony/Component/Finder/Tests/Iterator/MockSplFileInfo.php
@@ -51,7 +51,7 @@ public function __construct($param)
public function isFile(): bool
{
if (null === $this->type) {
- return false !== strpos($this->getFilename(), 'file');
+ return str_contains($this->getFilename(), 'file');
}
return self::TYPE_FILE === $this->type;
@@ -60,7 +60,7 @@ public function isFile(): bool
public function isDir(): bool
{
if (null === $this->type) {
- return false !== strpos($this->getFilename(), 'directory');
+ return str_contains($this->getFilename(), 'directory');
}
return self::TYPE_DIRECTORY === $this->type;
diff --git a/src/Symfony/Component/Form/Command/DebugCommand.php b/src/Symfony/Component/Form/Command/DebugCommand.php
index fc233999a3731..04ed1c140fd5f 100644
--- a/src/Symfony/Component/Form/Command/DebugCommand.php
+++ b/src/Symfony/Component/Form/Command/DebugCommand.php
@@ -230,7 +230,7 @@ private function findAlternatives(string $name, array $collection): array
$alternatives = [];
foreach ($collection as $item) {
$lev = levenshtein($name, $item);
- if ($lev <= \strlen($name) / 3 || false !== strpos($item, $name)) {
+ if ($lev <= \strlen($name) / 3 || str_contains($item, $name)) {
$alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev : $lev;
}
}
diff --git a/src/Symfony/Component/Form/Extension/Core/DataMapper/PropertyPathMapper.php b/src/Symfony/Component/Form/Extension/Core/DataMapper/PropertyPathMapper.php
index bc31505157f77..2a78e03f89715 100644
--- a/src/Symfony/Component/Form/Extension/Core/DataMapper/PropertyPathMapper.php
+++ b/src/Symfony/Component/Form/Extension/Core/DataMapper/PropertyPathMapper.php
@@ -98,7 +98,7 @@ private function getPropertyValue($data, $propertyPath)
} catch (AccessException $e) {
if (!$e instanceof UninitializedPropertyException
// For versions without UninitializedPropertyException check the exception message
- && (class_exists(UninitializedPropertyException::class) || false === strpos($e->getMessage(), 'You should initialize it'))
+ && (class_exists(UninitializedPropertyException::class) || !str_contains($e->getMessage(), 'You should initialize it'))
) {
throw $e;
}
diff --git a/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToStringTransformer.php b/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToStringTransformer.php
index a8f81bb8a8378..52565f3879455 100644
--- a/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToStringTransformer.php
+++ b/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToStringTransformer.php
@@ -62,7 +62,7 @@ public function __construct(string $inputTimezone = null, string $outputTimezone
// where the time corresponds to the current server time.
// With "|" and "Y-m-d", "2010-02-03" becomes "2010-02-03 00:00:00",
// which is at least deterministic and thus used here.
- if (false === strpos($this->parseFormat, '|')) {
+ if (!str_contains($this->parseFormat, '|')) {
$this->parseFormat .= '|';
}
}
diff --git a/src/Symfony/Component/Form/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php b/src/Symfony/Component/Form/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php
index 4c85c2e957d38..e20ddf7fd2b7d 100644
--- a/src/Symfony/Component/Form/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php
+++ b/src/Symfony/Component/Form/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php
@@ -48,7 +48,7 @@ public function reverseTransform($value)
{
$decimalSeparator = $this->getNumberFormatter()->getSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL);
- if (\is_string($value) && false !== strpos($value, $decimalSeparator)) {
+ if (\is_string($value) && str_contains($value, $decimalSeparator)) {
throw new TransformationFailedException(sprintf('The value "%s" is not a valid integer.', $value));
}
diff --git a/src/Symfony/Component/Form/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php b/src/Symfony/Component/Form/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php
index 9ad2dbad628e3..171f802222b01 100644
--- a/src/Symfony/Component/Form/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php
+++ b/src/Symfony/Component/Form/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php
@@ -157,7 +157,7 @@ public function reverseTransform($value)
$value = str_replace(',', $decSep, $value);
}
- if (false !== strpos($value, $decSep)) {
+ if (str_contains($value, $decSep)) {
$type = \NumberFormatter::TYPE_DOUBLE;
} else {
$type = \PHP_INT_SIZE === 8
diff --git a/src/Symfony/Component/Form/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php b/src/Symfony/Component/Form/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php
index a6e433f1e0d33..a98774581ab81 100644
--- a/src/Symfony/Component/Form/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php
+++ b/src/Symfony/Component/Form/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php
@@ -122,7 +122,7 @@ public function reverseTransform($value)
$value = str_replace(',', $decSep, $value);
}
- if (false !== strpos($value, $decSep)) {
+ if (str_contains($value, $decSep)) {
$type = \NumberFormatter::TYPE_DOUBLE;
} else {
$type = \PHP_INT_SIZE === 8 ? \NumberFormatter::TYPE_INT64 : \NumberFormatter::TYPE_INT32;
diff --git a/src/Symfony/Component/Form/Extension/Core/Type/DateType.php b/src/Symfony/Component/Form/Extension/Core/Type/DateType.php
index c43a9f0b24da1..a03e06ab23cd7 100644
--- a/src/Symfony/Component/Form/Extension/Core/Type/DateType.php
+++ b/src/Symfony/Component/Form/Extension/Core/Type/DateType.php
@@ -58,7 +58,7 @@ public function buildForm(FormBuilderInterface $builder, array $options)
}
if ('single_text' === $options['widget']) {
- if ('' !== $pattern && false === strpos($pattern, 'y') && false === strpos($pattern, 'M') && false === strpos($pattern, 'd')) {
+ if ('' !== $pattern && !str_contains($pattern, 'y') && !str_contains($pattern, 'M') && !str_contains($pattern, 'd')) {
throw new InvalidOptionsException(sprintf('The "format" option should contain the letters "y", "M" or "d". Its current value is "%s".', $pattern));
}
@@ -71,7 +71,7 @@ public function buildForm(FormBuilderInterface $builder, array $options)
$pattern
));
} else {
- if ('' !== $pattern && (false === strpos($pattern, 'y') || false === strpos($pattern, 'M') || false === strpos($pattern, 'd'))) {
+ if ('' !== $pattern && (!str_contains($pattern, 'y') || !str_contains($pattern, 'M') || !str_contains($pattern, 'd'))) {
throw new InvalidOptionsException(sprintf('The "format" option should contain the letters "y", "M" and "d". Its current value is "%s".', $pattern));
}
diff --git a/src/Symfony/Component/Form/Extension/Core/Type/FileType.php b/src/Symfony/Component/Form/Extension/Core/Type/FileType.php
index e26cedd37c4e8..343fc76d475e0 100644
--- a/src/Symfony/Component/Form/Extension/Core/Type/FileType.php
+++ b/src/Symfony/Component/Form/Extension/Core/Type/FileType.php
@@ -190,9 +190,9 @@ private static function getMaxFilesize()
}
$max = ltrim($iniMax, '+');
- if (0 === strpos($max, '0x')) {
+ if (str_starts_with($max, '0x')) {
$max = \intval($max, 16);
- } elseif (0 === strpos($max, '0')) {
+ } elseif (str_starts_with($max, '0')) {
$max = \intval($max, 8);
} else {
$max = (int) $max;
diff --git a/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/ViolationMapper.php b/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/ViolationMapper.php
index 4c19e9850a444..d788419a16059 100644
--- a/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/ViolationMapper.php
+++ b/src/Symfony/Component/Form/Extension/Validator/ViolationMapper/ViolationMapper.php
@@ -206,7 +206,7 @@ private function matchChild(FormInterface $form, PropertyPathIteratorInterface $
if ($childPath === $chunk) {
$target = $child;
$foundAtIndex = $it->key();
- } elseif (0 === strpos($childPath, $chunk)) {
+ } elseif (str_starts_with($childPath, $chunk)) {
continue;
}
diff --git a/src/Symfony/Component/Form/Util/ServerParams.php b/src/Symfony/Component/Form/Util/ServerParams.php
index 08b9d690c7d99..b6ce9d1065617 100644
--- a/src/Symfony/Component/Form/Util/ServerParams.php
+++ b/src/Symfony/Component/Form/Util/ServerParams.php
@@ -52,9 +52,9 @@ public function getPostMaxSize()
}
$max = ltrim($iniMax, '+');
- if (0 === strpos($max, '0x')) {
+ if (str_starts_with($max, '0x')) {
$max = \intval($max, 16);
- } elseif (0 === strpos($max, '0')) {
+ } elseif (str_starts_with($max, '0')) {
$max = \intval($max, 8);
} else {
$max = (int) $max;
diff --git a/src/Symfony/Component/HttpClient/CurlHttpClient.php b/src/Symfony/Component/HttpClient/CurlHttpClient.php
index 42388a65e0c1d..25e517aa6d05f 100644
--- a/src/Symfony/Component/HttpClient/CurlHttpClient.php
+++ b/src/Symfony/Component/HttpClient/CurlHttpClient.php
@@ -269,7 +269,7 @@ public function request(string $method, string $url, array $options = []): Respo
if ($options['bindto']) {
if (file_exists($options['bindto'])) {
$curlopts[\CURLOPT_UNIX_SOCKET_PATH] = $options['bindto'];
- } elseif (0 !== strpos($options['bindto'], 'if!') && preg_match('/^(.*):(\d+)$/', $options['bindto'], $matches)) {
+ } elseif (!str_starts_with($options['bindto'], 'if!') && preg_match('/^(.*):(\d+)$/', $options['bindto'], $matches)) {
$curlopts[\CURLOPT_INTERFACE] = $matches[1];
$curlopts[\CURLOPT_LOCALPORT] = $matches[2];
} else {
@@ -305,7 +305,7 @@ public function request(string $method, string $url, array $options = []): Respo
foreach ($curlopts as $opt => $value) {
if (null !== $value && !curl_setopt($ch, $opt, $value) && \CURLOPT_CERTINFO !== $opt) {
$constants = array_filter(get_defined_constants(), static function ($v, $k) use ($opt) {
- return $v === $opt && 'C' === $k[0] && (0 === strpos($k, 'CURLOPT_') || 0 === strpos($k, 'CURLINFO_'));
+ return $v === $opt && 'C' === $k[0] && (str_starts_with($k, 'CURLOPT_') || str_starts_with($k, 'CURLINFO_'));
}, \ARRAY_FILTER_USE_BOTH);
throw new TransportException(sprintf('Curl option "%s" is not supported.', key($constants) ?? $opt));
@@ -399,7 +399,7 @@ private function handlePush($parent, $pushed, array $requestHeaders, int $maxPen
// curl before 7.65 doesn't validate the pushed ":authority" header,
// but this is a MUST in the HTTP/2 RFC; let's restrict pushes to the original host,
// ignoring domains mentioned as alt-name in the certificate for now (same as curl).
- if (0 !== strpos($origin, $url.'/')) {
+ if (!str_starts_with($origin, $url.'/')) {
$this->logger && $this->logger->debug(sprintf('Rejecting pushed response from "%s": server is not authoritative for "%s"', $origin, $url));
return \CURL_PUSH_DENY;
diff --git a/src/Symfony/Component/HttpClient/Exception/HttpExceptionTrait.php b/src/Symfony/Component/HttpClient/Exception/HttpExceptionTrait.php
index 5b7b44830722c..7ab27524faa0f 100644
--- a/src/Symfony/Component/HttpClient/Exception/HttpExceptionTrait.php
+++ b/src/Symfony/Component/HttpClient/Exception/HttpExceptionTrait.php
@@ -32,7 +32,7 @@ public function __construct(ResponseInterface $response)
$httpCodeFound = false;
$isJson = false;
foreach (array_reverse($response->getInfo('response_headers')) as $h) {
- if (0 === strpos($h, 'HTTP/')) {
+ if (str_starts_with($h, 'HTTP/')) {
if ($httpCodeFound) {
break;
}
diff --git a/src/Symfony/Component/HttpClient/HttpClientTrait.php b/src/Symfony/Component/HttpClient/HttpClientTrait.php
index cf439c6ff034a..70df9250f5e93 100644
--- a/src/Symfony/Component/HttpClient/HttpClientTrait.php
+++ b/src/Symfony/Component/HttpClient/HttpClientTrait.php
@@ -215,7 +215,7 @@ private static function mergeDefaultOptions(array $options, array $defaultOption
$alternatives = [];
foreach ($defaultOptions as $key => $v) {
- if (levenshtein($name, $key) <= \strlen($name) / 3 || false !== strpos($key, $name)) {
+ if (levenshtein($name, $key) <= \strlen($name) / 3 || str_contains($key, $name)) {
$alternatives[] = $key;
}
}
@@ -465,7 +465,7 @@ private static function parseUrl(string $url, array $query = [], array $allowedS
continue;
}
- if (false !== strpos($parts[$part], '%')) {
+ if (str_contains($parts[$part], '%')) {
// https://tools.ietf.org/html/rfc3986#section-2.3
$parts[$part] = preg_replace_callback('/%(?:2[DE]|3[0-9]|[46][1-9A-F]|5F|[57][0-9A]|7E)++/i', function ($m) { return rawurldecode($m[0]); }, $parts[$part]);
}
@@ -493,11 +493,11 @@ private static function removeDotSegments(string $path)
$result = '';
while (!\in_array($path, ['', '.', '..'], true)) {
- if ('.' === $path[0] && (0 === strpos($path, $p = '../') || 0 === strpos($path, $p = './'))) {
+ if ('.' === $path[0] && (str_starts_with($path, $p = '../') || str_starts_with($path, $p = './'))) {
$path = substr($path, \strlen($p));
- } elseif ('/.' === $path || 0 === strpos($path, '/./')) {
+ } elseif ('/.' === $path || str_starts_with($path, '/./')) {
$path = substr_replace($path, '/', 0, 3);
- } elseif ('/..' === $path || 0 === strpos($path, '/../')) {
+ } elseif ('/..' === $path || str_starts_with($path, '/../')) {
$i = strrpos($result, '/');
$result = $i ? substr($result, 0, $i) : '';
$path = substr_replace($path, '/', 0, 4);
diff --git a/src/Symfony/Component/HttpClient/NativeHttpClient.php b/src/Symfony/Component/HttpClient/NativeHttpClient.php
index 4063c81262a74..f74e773048049 100644
--- a/src/Symfony/Component/HttpClient/NativeHttpClient.php
+++ b/src/Symfony/Component/HttpClient/NativeHttpClient.php
@@ -71,10 +71,10 @@ public function request(string $method, string $url, array $options = []): Respo
if (file_exists($options['bindto'])) {
throw new TransportException(__CLASS__.' cannot bind to local Unix sockets, use e.g. CurlHttpClient instead.');
}
- if (0 === strpos($options['bindto'], 'if!')) {
+ if (str_starts_with($options['bindto'], 'if!')) {
throw new TransportException(__CLASS__.' cannot bind to network interfaces, use e.g. CurlHttpClient instead.');
}
- if (0 === strpos($options['bindto'], 'host!')) {
+ if (str_starts_with($options['bindto'], 'host!')) {
$options['bindto'] = substr($options['bindto'], 5);
}
}
diff --git a/src/Symfony/Component/HttpClient/Response/CurlResponse.php b/src/Symfony/Component/HttpClient/Response/CurlResponse.php
index cc5bf4f0b25c6..1ccc48a688699 100644
--- a/src/Symfony/Component/HttpClient/Response/CurlResponse.php
+++ b/src/Symfony/Component/HttpClient/Response/CurlResponse.php
@@ -335,7 +335,7 @@ private static function parseHeaderLine($ch, string $data, array &$info, array &
return \strlen($data);
}
- if (0 !== strpos($data, 'HTTP/')) {
+ if (!str_starts_with($data, 'HTTP/')) {
if (0 === stripos($data, 'Location:')) {
$location = trim(substr($data, 9));
}
diff --git a/src/Symfony/Component/HttpClient/composer.json b/src/Symfony/Component/HttpClient/composer.json
index 086d34e22ff02..62e06b7ebebcd 100644
--- a/src/Symfony/Component/HttpClient/composer.json
+++ b/src/Symfony/Component/HttpClient/composer.json
@@ -18,7 +18,8 @@
"php-http/async-client-implementation": "*",
"php-http/client-implementation": "*",
"psr/http-client-implementation": "1.0",
- "symfony/http-client-implementation": "1.1|2.0"
+ "symfony/http-client-implementation": "1.1|2.0",
+ "symfony/polyfill-php80": "^1.16"
},
"require": {
"php": ">=7.1.3",
diff --git a/src/Symfony/Component/HttpFoundation/ApacheRequest.php b/src/Symfony/Component/HttpFoundation/ApacheRequest.php
index 5d9426879de18..a060d628f0ba4 100644
--- a/src/Symfony/Component/HttpFoundation/ApacheRequest.php
+++ b/src/Symfony/Component/HttpFoundation/ApacheRequest.php
@@ -37,7 +37,7 @@ protected function prepareBaseUrl()
{
$baseUrl = $this->server->get('SCRIPT_NAME');
- if (false === strpos($this->server->get('REQUEST_URI'), $baseUrl)) {
+ if (!str_contains($this->server->get('REQUEST_URI'), $baseUrl)) {
// assume mod_rewrite
return rtrim(\dirname($baseUrl), '/\\');
}
diff --git a/src/Symfony/Component/HttpFoundation/BinaryFileResponse.php b/src/Symfony/Component/HttpFoundation/BinaryFileResponse.php
index 02463933a98cc..238c254cbdcda 100644
--- a/src/Symfony/Component/HttpFoundation/BinaryFileResponse.php
+++ b/src/Symfony/Component/HttpFoundation/BinaryFileResponse.php
@@ -159,7 +159,7 @@ public function setContentDisposition($disposition, $filename = '', $filenameFal
$filename = $this->file->getFilename();
}
- if ('' === $filenameFallback && (!preg_match('/^[\x20-\x7e]*$/', $filename) || false !== strpos($filename, '%'))) {
+ if ('' === $filenameFallback && (!preg_match('/^[\x20-\x7e]*$/', $filename) || str_contains($filename, '%'))) {
$encoding = mb_detect_encoding($filename, null, true) ?: '8bit';
for ($i = 0, $filenameLength = mb_strlen($filename, $encoding); $i < $filenameLength; ++$i) {
@@ -239,7 +239,7 @@ public function prepare(Request $request)
if (!$request->headers->has('If-Range') || $this->hasValidIfRangeHeader($request->headers->get('If-Range'))) {
$range = $request->headers->get('Range');
- if (0 === strpos($range, 'bytes=')) {
+ if (str_starts_with($range, 'bytes=')) {
[$start, $end] = explode('-', substr($range, 6), 2) + [0];
$end = ('' === $end) ? $fileSize - 1 : (int) $end;
diff --git a/src/Symfony/Component/HttpFoundation/File/MimeType/FileBinaryMimeTypeGuesser.php b/src/Symfony/Component/HttpFoundation/File/MimeType/FileBinaryMimeTypeGuesser.php
index 6d2c274a9dd5b..4ee5eef4487aa 100644
--- a/src/Symfony/Component/HttpFoundation/File/MimeType/FileBinaryMimeTypeGuesser.php
+++ b/src/Symfony/Component/HttpFoundation/File/MimeType/FileBinaryMimeTypeGuesser.php
@@ -85,7 +85,7 @@ public function guess($path)
ob_start();
// need to use --mime instead of -i. see #6641
- passthru(sprintf($this->cmd, escapeshellarg((0 === strpos($path, '-') ? './' : '').$path)), $return);
+ passthru(sprintf($this->cmd, escapeshellarg((str_starts_with($path, '-') ? './' : '').$path)), $return);
if ($return > 0) {
ob_end_clean();
diff --git a/src/Symfony/Component/HttpFoundation/File/UploadedFile.php b/src/Symfony/Component/HttpFoundation/File/UploadedFile.php
index 89764c3a0f7a6..6e035a55cdcb0 100644
--- a/src/Symfony/Component/HttpFoundation/File/UploadedFile.php
+++ b/src/Symfony/Component/HttpFoundation/File/UploadedFile.php
@@ -263,9 +263,9 @@ private static function parseFilesize(string $size)
$size = strtolower($size);
$max = ltrim($size, '+');
- if (0 === strpos($max, '0x')) {
+ if (str_starts_with($max, '0x')) {
$max = \intval($max, 16);
- } elseif (0 === strpos($max, '0')) {
+ } elseif (str_starts_with($max, '0')) {
$max = \intval($max, 8);
} else {
$max = (int) $max;
diff --git a/src/Symfony/Component/HttpFoundation/HeaderUtils.php b/src/Symfony/Component/HttpFoundation/HeaderUtils.php
index 2bf2d6844688d..412903f0339f3 100644
--- a/src/Symfony/Component/HttpFoundation/HeaderUtils.php
+++ b/src/Symfony/Component/HttpFoundation/HeaderUtils.php
@@ -176,12 +176,12 @@ public static function makeDisposition(string $disposition, string $filename, st
}
// percent characters aren't safe in fallback.
- if (false !== strpos($filenameFallback, '%')) {
+ if (str_contains($filenameFallback, '%')) {
throw new \InvalidArgumentException('The filename fallback cannot contain the "%" character.');
}
// path separators aren't allowed in either.
- if (false !== strpos($filename, '/') || false !== strpos($filename, '\\') || false !== strpos($filenameFallback, '/') || false !== strpos($filenameFallback, '\\')) {
+ if (str_contains($filename, '/') || str_contains($filename, '\\') || str_contains($filenameFallback, '/') || str_contains($filenameFallback, '\\')) {
throw new \InvalidArgumentException('The filename and the fallback cannot contain the "/" and "\\" characters.');
}
diff --git a/src/Symfony/Component/HttpFoundation/IpUtils.php b/src/Symfony/Component/HttpFoundation/IpUtils.php
index b23d8819dd9f3..b28c55b089d06 100644
--- a/src/Symfony/Component/HttpFoundation/IpUtils.php
+++ b/src/Symfony/Component/HttpFoundation/IpUtils.php
@@ -72,7 +72,7 @@ public static function checkIp4($requestIp, $ip)
return self::$checkedIps[$cacheKey] = false;
}
- if (false !== strpos($ip, '/')) {
+ if (str_contains($ip, '/')) {
[$address, $netmask] = explode('/', $ip, 2);
if ('0' === $netmask) {
@@ -120,7 +120,7 @@ public static function checkIp6($requestIp, $ip)
throw new \RuntimeException('Unable to check Ipv6. Check that PHP was not compiled with option "disable-ipv6".');
}
- if (false !== strpos($ip, '/')) {
+ if (str_contains($ip, '/')) {
[$address, $netmask] = explode('/', $ip, 2);
if ('0' === $netmask) {
diff --git a/src/Symfony/Component/HttpFoundation/JsonResponse.php b/src/Symfony/Component/HttpFoundation/JsonResponse.php
index 9786a473ca169..4daea10d4dd18 100644
--- a/src/Symfony/Component/HttpFoundation/JsonResponse.php
+++ b/src/Symfony/Component/HttpFoundation/JsonResponse.php
@@ -155,7 +155,7 @@ public function setData($data = [])
try {
$data = json_encode($data, $this->encodingOptions);
} catch (\Exception $e) {
- if ('Exception' === \get_class($e) && 0 === strpos($e->getMessage(), 'Failed calling ')) {
+ if ('Exception' === \get_class($e) && str_starts_with($e->getMessage(), 'Failed calling ')) {
throw $e->getPrevious() ?: $e;
}
throw $e;
diff --git a/src/Symfony/Component/HttpFoundation/Request.php b/src/Symfony/Component/HttpFoundation/Request.php
index 76a3a269374e3..d1f8461ac8683 100644
--- a/src/Symfony/Component/HttpFoundation/Request.php
+++ b/src/Symfony/Component/HttpFoundation/Request.php
@@ -292,7 +292,7 @@ public static function createFromGlobals()
{
$request = self::createRequestFromFactory($_GET, $_POST, [], $_COOKIE, $_FILES, $_SERVER);
- if (0 === strpos($request->headers->get('CONTENT_TYPE', ''), 'application/x-www-form-urlencoded')
+ if (str_starts_with($request->headers->get('CONTENT_TYPE', ''), 'application/x-www-form-urlencoded')
&& \in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), ['PUT', 'DELETE', 'PATCH'])
) {
parse_str($request->getContent(), $data);
@@ -1647,7 +1647,7 @@ public function getLanguages()
$languages = AcceptHeader::fromString($this->headers->get('Accept-Language'))->all();
$this->languages = [];
foreach ($languages as $lang => $acceptHeaderItem) {
- if (false !== strpos($lang, '-')) {
+ if (str_contains($lang, '-')) {
$codes = explode('-', $lang);
if ('i' === $codes[0]) {
// Language not listed in ISO 639 that are not variants
@@ -1949,7 +1949,7 @@ private function setPhpDefaultLocale(string $locale): void
*/
private function getUrlencodedPrefix(string $string, string $prefix): ?string
{
- if (0 !== strpos(rawurldecode($string), $prefix)) {
+ if (!str_starts_with(rawurldecode($string), $prefix)) {
return null;
}
@@ -2057,7 +2057,7 @@ private function normalizeAndFilterClientIps(array $clientIps, string $ip): arra
if ($i) {
$clientIps[$key] = $clientIp = substr($clientIp, 0, $i);
}
- } elseif (0 === strpos($clientIp, '[')) {
+ } elseif (str_starts_with($clientIp, '[')) {
// Strip brackets and :port from IPv6 addresses.
$i = strpos($clientIp, ']', 1);
$clientIps[$key] = $clientIp = substr($clientIp, 1, $i - 1);
diff --git a/src/Symfony/Component/HttpFoundation/Response.php b/src/Symfony/Component/HttpFoundation/Response.php
index 4ab97aaf90538..a9cea09b39f05 100644
--- a/src/Symfony/Component/HttpFoundation/Response.php
+++ b/src/Symfony/Component/HttpFoundation/Response.php
@@ -311,7 +311,7 @@ public function prepare(Request $request)
}
// Check if we need to send extra expire info headers
- if ('1.0' == $this->getProtocolVersion() && false !== strpos($headers->get('Cache-Control'), 'no-cache')) {
+ if ('1.0' == $this->getProtocolVersion() && str_contains($headers->get('Cache-Control'), 'no-cache')) {
$headers->set('pragma', 'no-cache');
$headers->set('expires', -1);
}
@@ -921,7 +921,7 @@ public function setEtag(string $etag = null, bool $weak = false)
if (null === $etag) {
$this->headers->remove('Etag');
} else {
- if (0 !== strpos($etag, '"')) {
+ if (!str_starts_with($etag, '"')) {
$etag = '"'.$etag.'"';
}
diff --git a/src/Symfony/Component/HttpFoundation/ServerBag.php b/src/Symfony/Component/HttpFoundation/ServerBag.php
index 5e1094d5fe19f..7af111c865154 100644
--- a/src/Symfony/Component/HttpFoundation/ServerBag.php
+++ b/src/Symfony/Component/HttpFoundation/ServerBag.php
@@ -29,7 +29,7 @@ public function getHeaders()
{
$headers = [];
foreach ($this->parameters as $key => $value) {
- if (0 === strpos($key, 'HTTP_')) {
+ if (str_starts_with($key, 'HTTP_')) {
$headers[substr($key, 5)] = $value;
} elseif (\in_array($key, ['CONTENT_TYPE', 'CONTENT_LENGTH', 'CONTENT_MD5'], true)) {
$headers[$key] = $value;
diff --git a/src/Symfony/Component/HttpFoundation/Session/Attribute/NamespacedAttributeBag.php b/src/Symfony/Component/HttpFoundation/Session/Attribute/NamespacedAttributeBag.php
index 2cf0743cf9d5e..7ba224aceebae 100644
--- a/src/Symfony/Component/HttpFoundation/Session/Attribute/NamespacedAttributeBag.php
+++ b/src/Symfony/Component/HttpFoundation/Session/Attribute/NamespacedAttributeBag.php
@@ -102,7 +102,7 @@ public function remove($name)
protected function &resolveAttributePath($name, $writeContext = false)
{
$array = &$this->attributes;
- $name = (0 === strpos($name, $this->namespaceCharacter)) ? substr($name, 1) : $name;
+ $name = (str_starts_with($name, $this->namespaceCharacter)) ? substr($name, 1) : $name;
// Check if there is anything to do, else return
if (!$name) {
diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php
index 5fec9b17ecdc9..e234d147e41a1 100644
--- a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php
+++ b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php
@@ -179,7 +179,7 @@ public function __construct($pdoOrDsn = null, array $options = [])
$this->pdo = $pdoOrDsn;
$this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
- } elseif (\is_string($pdoOrDsn) && false !== strpos($pdoOrDsn, '://')) {
+ } elseif (\is_string($pdoOrDsn) && str_contains($pdoOrDsn, '://')) {
$this->dsn = $this->buildDsnFromUrl($pdoOrDsn);
} else {
$this->dsn = $pdoOrDsn;
@@ -353,7 +353,7 @@ protected function doWrite($sessionId, $data)
$insertStmt->execute();
} catch (\PDOException $e) {
// Handle integrity violation SQLSTATE 23000 (or a subclass like 23505 in Postgres) for duplicate keys
- if (0 === strpos($e->getCode(), '23')) {
+ if (str_starts_with($e->getCode(), '23')) {
$updateStmt->execute();
} else {
throw $e;
@@ -487,7 +487,7 @@ private function buildDsnFromUrl(string $dsnOrUrl): string
$driver = $driverAliasMap[$params['scheme']] ?? $params['scheme'];
// Doctrine DBAL supports passing its internal pdo_* driver names directly too (allowing both dashes and underscores). This allows supporting the same here.
- if (0 === strpos($driver, 'pdo_') || 0 === strpos($driver, 'pdo-')) {
+ if (str_starts_with($driver, 'pdo_') || str_starts_with($driver, 'pdo-')) {
$driver = substr($driver, 4);
}
@@ -661,7 +661,7 @@ protected function doRead($sessionId)
} catch (\PDOException $e) {
// Catch duplicate key error because other connection created the session already.
// It would only not be the case when the other connection destroyed the session.
- if (0 === strpos($e->getCode(), '23')) {
+ if (str_starts_with($e->getCode(), '23')) {
// Retrieve finished session data written by concurrent connection by restarting the loop.
// We have to start a new transaction as a failed query will mark the current transaction as
// aborted in PostgreSQL and disallow further queries within it.
diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/SessionHandlerFactory.php b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/SessionHandlerFactory.php
index 33453c320840f..05e9418c4a0f9 100644
--- a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/SessionHandlerFactory.php
+++ b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/SessionHandlerFactory.php
@@ -47,38 +47,38 @@ public static function createHandler($connection): AbstractSessionHandler
case !\is_string($connection):
throw new \InvalidArgumentException(sprintf('Unsupported Connection: "%s".', \get_class($connection)));
- case 0 === strpos($connection, 'file://'):
+ case str_starts_with($connection, 'file://'):
$savePath = substr($connection, 7);
return new StrictSessionHandler(new NativeFileSessionHandler('' === $savePath ? null : $savePath));
- case 0 === strpos($connection, 'redis:'):
- case 0 === strpos($connection, 'rediss:'):
- case 0 === strpos($connection, 'memcached:'):
+ case str_starts_with($connection, 'redis:'):
+ case str_starts_with($connection, 'rediss:'):
+ case str_starts_with($connection, 'memcached:'):
if (!class_exists(AbstractAdapter::class)) {
throw new \InvalidArgumentException(sprintf('Unsupported DSN "%s". Try running "composer require symfony/cache".', $connection));
}
- $handlerClass = 0 === strpos($connection, 'memcached:') ? MemcachedSessionHandler::class : RedisSessionHandler::class;
+ $handlerClass = str_starts_with($connection, 'memcached:') ? MemcachedSessionHandler::class : RedisSessionHandler::class;
$connection = AbstractAdapter::createConnection($connection, ['lazy' => true]);
return new $handlerClass($connection);
- case 0 === strpos($connection, 'pdo_oci://'):
+ case str_starts_with($connection, 'pdo_oci://'):
if (!class_exists(DriverManager::class)) {
throw new \InvalidArgumentException(sprintf('Unsupported DSN "%s". Try running "composer require doctrine/dbal".', $connection));
}
$connection = DriverManager::getConnection(['url' => $connection])->getWrappedConnection();
// no break;
- case 0 === strpos($connection, 'mssql://'):
- case 0 === strpos($connection, 'mysql://'):
- case 0 === strpos($connection, 'mysql2://'):
- case 0 === strpos($connection, 'pgsql://'):
- case 0 === strpos($connection, 'postgres://'):
- case 0 === strpos($connection, 'postgresql://'):
- case 0 === strpos($connection, 'sqlsrv://'):
- case 0 === strpos($connection, 'sqlite://'):
- case 0 === strpos($connection, 'sqlite3://'):
+ case str_starts_with($connection, 'mssql://'):
+ case str_starts_with($connection, 'mysql://'):
+ case str_starts_with($connection, 'mysql2://'):
+ case str_starts_with($connection, 'pgsql://'):
+ case str_starts_with($connection, 'postgres://'):
+ case str_starts_with($connection, 'postgresql://'):
+ case str_starts_with($connection, 'sqlsrv://'):
+ case str_starts_with($connection, 'sqlite://'):
+ case str_starts_with($connection, 'sqlite3://'):
return new PdoSessionHandler($connection);
}
diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php b/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php
index 8288d3c22d063..97975dba92b4f 100644
--- a/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php
+++ b/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php
@@ -256,7 +256,7 @@ public function save()
// Register error handler to add information about the current save handler
$previousHandler = set_error_handler(function ($type, $msg, $file, $line) use (&$previousHandler) {
- if (\E_WARNING === $type && 0 === strpos($msg, 'session_write_close():')) {
+ if (\E_WARNING === $type && str_starts_with($msg, 'session_write_close():')) {
$handler = $this->saveHandler instanceof SessionHandlerProxy ? $this->saveHandler->getHandler() : $this->saveHandler;
$msg = sprintf('session_write_close(): Failed to write session data with "%s" handler', \get_class($handler));
}
diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php
index 79ab73c1a4d1f..408ce32f33bae 100644
--- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php
+++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php
@@ -156,7 +156,7 @@ public function testReadLockedConvertsStreamToString()
$insertStmt = $this->createMock(\PDOStatement::class);
$pdo->prepareResult = function ($statement) use ($selectStmt, $insertStmt) {
- return 0 === strpos($statement, 'INSERT') ? $insertStmt : $selectStmt;
+ return str_starts_with($statement, 'INSERT') ? $insertStmt : $selectStmt;
};
$content = 'foobar';
diff --git a/src/Symfony/Component/HttpFoundation/UrlHelper.php b/src/Symfony/Component/HttpFoundation/UrlHelper.php
index f114c0a9fb838..3fe053ddbb09c 100644
--- a/src/Symfony/Component/HttpFoundation/UrlHelper.php
+++ b/src/Symfony/Component/HttpFoundation/UrlHelper.php
@@ -31,7 +31,7 @@ public function __construct(RequestStack $requestStack, RequestContext $requestC
public function getAbsoluteUrl(string $path): string
{
- if (false !== strpos($path, '://') || '//' === substr($path, 0, 2)) {
+ if (str_contains($path, '://') || '//' === substr($path, 0, 2)) {
return $path;
}
@@ -60,7 +60,7 @@ public function getAbsoluteUrl(string $path): string
public function getRelativePath(string $path): string
{
- if (false !== strpos($path, '://') || '//' === substr($path, 0, 2)) {
+ if (str_contains($path, '://') || '//' === substr($path, 0, 2)) {
return $path;
}
diff --git a/src/Symfony/Component/HttpKernel/Client.php b/src/Symfony/Component/HttpKernel/Client.php
index f0dd66ece8de9..5c9169ce4bbec 100644
--- a/src/Symfony/Component/HttpKernel/Client.php
+++ b/src/Symfony/Component/HttpKernel/Client.php
@@ -85,7 +85,7 @@ protected function getScript($request)
$requires = '';
foreach (get_declared_classes() as $class) {
- if (0 === strpos($class, 'ComposerAutoloaderInit')) {
+ if (str_starts_with($class, 'ComposerAutoloaderInit')) {
$r = new \ReflectionClass($class);
$file = \dirname($r->getFileName(), 2).'/autoload.php';
if (file_exists($file)) {
diff --git a/src/Symfony/Component/HttpKernel/Config/FileLocator.php b/src/Symfony/Component/HttpKernel/Config/FileLocator.php
index 5dc82b33dc4d1..a30241970179e 100644
--- a/src/Symfony/Component/HttpKernel/Config/FileLocator.php
+++ b/src/Symfony/Component/HttpKernel/Config/FileLocator.php
@@ -70,11 +70,11 @@ public function locate($file, $currentPath = null, $first = true)
// no need to trigger deprecations when the loaded file is given as absolute path
foreach ($this->paths as $deprecatedPath) {
foreach ((array) $locations as $location) {
- if (null !== $currentPath && 0 === strpos($location, $currentPath)) {
+ if (null !== $currentPath && str_starts_with($location, $currentPath)) {
return $locations;
}
- if (0 === strpos($location, $deprecatedPath) && (null === $currentPath || false === strpos($location, $currentPath))) {
+ if (str_starts_with($location, $deprecatedPath) && (null === $currentPath || !str_contains($location, $currentPath))) {
$deprecation = sprintf('Loading the file "%s" from the global resource directory "%s" is deprecated since Symfony 4.4 and will be removed in 5.0.', $file, $deprecatedPath);
}
}
diff --git a/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php b/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php
index 9c2fdd9807000..c3df8f9571d44 100644
--- a/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php
+++ b/src/Symfony/Component/HttpKernel/Controller/ControllerResolver.php
@@ -106,7 +106,7 @@ public function getController(Request $request)
*/
protected function createController($controller)
{
- if (false === strpos($controller, '::')) {
+ if (!str_contains($controller, '::')) {
$controller = $this->instantiateController($controller);
if (!\is_callable($controller)) {
@@ -154,7 +154,7 @@ protected function instantiateController($class)
private function getControllerError($callable): string
{
if (\is_string($callable)) {
- if (false !== strpos($callable, '::')) {
+ if (str_contains($callable, '::')) {
$callable = explode('::', $callable, 2);
} else {
return sprintf('Function "%s" does not exist.', $callable);
@@ -195,7 +195,7 @@ private function getControllerError($callable): string
foreach ($collection as $item) {
$lev = levenshtein($method, $item);
- if ($lev <= \strlen($method) / 3 || false !== strpos($item, $method)) {
+ if ($lev <= \strlen($method) / 3 || str_contains($item, $method)) {
$alternatives[] = $item;
}
}
diff --git a/src/Symfony/Component/HttpKernel/DataCollector/DumpDataCollector.php b/src/Symfony/Component/HttpKernel/DataCollector/DumpDataCollector.php
index a3cf2147cb576..a66224b6f4029 100644
--- a/src/Symfony/Component/HttpKernel/DataCollector/DumpDataCollector.php
+++ b/src/Symfony/Component/HttpKernel/DataCollector/DumpDataCollector.php
@@ -120,11 +120,11 @@ public function collect(Request $request, Response $response/*, \Throwable $exce
if (!$this->requestStack
|| !$response->headers->has('X-Debug-Token')
|| $response->isRedirection()
- || ($response->headers->has('Content-Type') && false === strpos($response->headers->get('Content-Type'), 'html'))
+ || ($response->headers->has('Content-Type') && !str_contains($response->headers->get('Content-Type'), 'html'))
|| 'html' !== $request->getRequestFormat()
|| false === strripos($response->getContent(), '