minor #41576 Leverage str_contains/str_starts_with (derrabus)

This PR was merged into the 4.4 branch.

Discussion
----------

Leverage str_contains/str_starts_with

| Q             | A
| ------------- | ---
| Branch?       | 4.4
| Bug fix?      | no
| New feature?  | no
| Deprecations? | no
| Tickets       | N/A
| License       | MIT
| Doc PR        | N/A

I'd like to use `str_contains()` and `str_starts_with()` whenever possible. On PHP 8, this is a native function and for all earlier versions, we can maintain the most efficient way to perform those operations in the polyfill package. And apart from that, I find the new functions more intuitive than the `strpos()` expressions I'm replacing here.

All code changes in this PR were automated, see FriendsOfPHP/PHP-CS-Fixer#5754

Of course, this is more than just a CS change. If you don't feel comfortable merging this change into 4.4, I can easily redo the PR for 5.4.

Commits
-------

e585b26730 Leverage str_contains/str_starts_with
This commit is contained in:
Nicolas Grekas 2021-07-21 14:20:00 +02:00
commit c7dc7f8240
280 changed files with 538 additions and 511 deletions

View File

@ -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": {

View File

@ -228,7 +228,7 @@ abstract class AbstractDoctrineExtension extends Extension
]);
}
$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']);
}

View File

@ -68,7 +68,7 @@ class DoctrineExtractor implements PropertyListExtractorInterface, PropertyTypeE
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));

View File

@ -144,7 +144,7 @@ class EntityUserProvider implements UserProviderInterface, PasswordUpgraderInter
if (null === $this->class) {
$class = $this->classOrAlias;
if (false !== strpos($class, ':')) {
if (str_contains($class, ':')) {
$class = $this->getClassMetadata()->getName();
}

View File

@ -104,7 +104,7 @@ final class DoctrineLoader implements LoaderInterface
}
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'])) {

View File

@ -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": {

View File

@ -96,7 +96,7 @@ EOF
'multiline' => OutputInterface::VERBOSITY_DEBUG <= $output->getVerbosity(),
]));
if (false === strpos($host = $input->getOption('host'), '://')) {
if (!str_contains($host = $input->getOption('host'), '://')) {
$host = 'tcp://'.$host;
}

View File

@ -163,7 +163,7 @@ class ConsoleFormatter implements FormatterInterface
{
$message = $record['message'];
if (false === strpos($message, '{')) {
if (!str_contains($message, '{')) {
return $record;
}

View File

@ -32,7 +32,7 @@ class ServerLogHandler extends AbstractHandler
{
parent::__construct($level, $bubble);
if (false === strpos($host, '://')) {
if (!str_contains($host, '://')) {
$host = 'tcp://'.$host;
}

View File

@ -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",

View File

@ -28,12 +28,12 @@ class LazyLoadingValueHolderGenerator extends BaseGenerator
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()));

View File

@ -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"

View File

@ -225,7 +225,7 @@ EOF
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 @@ EOF
$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 @@ EOF
$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 @@ EOF
$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 @@ EOF
$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 @@ EOF
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);
}

View File

@ -71,7 +71,7 @@ class CodeExtension extends AbstractExtension
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 @@ class CodeExtension extends AbstractExtension
{
$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 @@ class CodeExtension extends AbstractExtension
*/
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)) {

View File

@ -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"
},

View File

@ -59,7 +59,7 @@ class DebugExtension extends Extension
$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'))
;

View File

@ -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"
},

View File

@ -167,7 +167,7 @@ class Client extends HttpKernelBrowser
$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)) {

View File

@ -142,7 +142,7 @@ EOF
}
$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;

View File

@ -270,7 +270,7 @@ EOF
$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 @@ EOF
}
// if the id has a \, assume it is a class
if (false !== strpos($serviceId, '\\')) {
if (str_contains($serviceId, '\\')) {
return true;
}

View File

@ -104,7 +104,7 @@ final class ContainerLintCommand extends Command
$skippedIds = [];
foreach ($container->getServiceIds() as $serviceId) {
if (0 === strpos($serviceId, '.errored.')) {
if (str_starts_with($serviceId, '.errored.')) {
$skippedIds[$serviceId] = true;
}
}

View File

@ -80,7 +80,7 @@ EOF
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 @@ EOF
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])) {

View File

@ -37,7 +37,7 @@ class XliffLintCommand extends BaseLintCommand
};
$isReadableProvider = function ($fileOrDirectory, $default) {
return 0 === strpos($fileOrDirectory, '@') || $default($fileOrDirectory);
return str_starts_with($fileOrDirectory, '@') || $default($fileOrDirectory);
};
parent::__construct(null, $directoryIteratorProvider, $isReadableProvider);

View File

@ -36,7 +36,7 @@ class YamlLintCommand extends BaseLintCommand
};
$isReadableProvider = function ($fileOrDirectory, $default) {
return 0 === strpos($fileOrDirectory, '@') || $default($fileOrDirectory);
return str_starts_with($fileOrDirectory, '@') || $default($fileOrDirectory);
};
parent::__construct(null, $directoryIteratorProvider, $isReadableProvider);

View File

@ -286,7 +286,7 @@ class JsonDescriptor extends Descriptor
$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 @@ class JsonDescriptor extends Descriptor
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 @@ class JsonDescriptor extends Descriptor
$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;

View File

@ -300,7 +300,7 @@ class MarkdownDescriptor extends Descriptor
$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 @@ class MarkdownDescriptor extends Descriptor
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 @@ class MarkdownDescriptor extends Descriptor
$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);

View File

@ -514,7 +514,7 @@ class TextDescriptor extends Descriptor
$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 @@ class TextDescriptor extends Descriptor
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()) {

View File

@ -469,7 +469,7 @@ class XmlDescriptor extends Descriptor
$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 @@ class XmlDescriptor extends Descriptor
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 @@ class XmlDescriptor extends Descriptor
$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);

View File

@ -107,7 +107,7 @@ class ControllerNameParser
$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 @@ class ControllerNameParser
$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;
}

View File

@ -51,7 +51,7 @@ class ControllerResolver extends ContainerControllerResolver
*/
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);

View File

@ -128,7 +128,7 @@ class RedirectController
}
if ($qs = $request->server->get('QUERY_STRING') ?: $request->getQueryString()) {
if (false === strpos($path, '?')) {
if (!str_contains($path, '?')) {
$qs = '?'.$qs;
} else {
$qs = '&'.$qs;

View File

@ -99,7 +99,7 @@ class UnusedTagsPass implements CompilerPassInterface
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;
}
}

View File

@ -1266,7 +1266,7 @@ class FrameworkExtension extends Extension
'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),
],
]

View File

@ -55,7 +55,7 @@ class ResolveControllerNameSubscriber implements EventSubscriberInterface
$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));

View File

@ -95,7 +95,7 @@ class DelegatingLoader extends BaseDelegatingLoader
continue;
}
if (false !== strpos($controller, '::')) {
if (str_contains($controller, '::')) {
continue;
}

View File

@ -54,7 +54,7 @@ class DotenvVault extends AbstractVault
{
$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));

View File

@ -63,7 +63,7 @@ class CodeHelper extends Helper
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 @@ class CodeHelper extends Helper
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('<abbr title="%s">kernel.project_dir</abbr>/%s', htmlspecialchars($this->rootDir, $flags, $this->charset), $fileStr);

View File

@ -50,11 +50,11 @@ class TemplateNameParser extends BaseTemplateNameParser
// 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);
}

View File

@ -35,12 +35,12 @@ class CachePoolsTest extends AbstractWebTestCase
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 @@ class CachePoolsTest extends AbstractWebTestCase
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());

View File

@ -226,7 +226,7 @@ class MainConfiguration implements ConfigurationInterface
->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 @@ class MainConfiguration implements ConfigurationInterface
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']));
}
}

View File

@ -42,7 +42,7 @@ abstract class CompleteConfigurationTest extends TestCase
{
$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',

View File

@ -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",

View File

@ -44,7 +44,7 @@ EOF
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');

View File

@ -43,7 +43,7 @@ class TwigEnvironmentPass implements CompilerPassInterface
$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;

View File

@ -92,9 +92,9 @@ class Configuration implements ConfigurationInterface
->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);
}

View File

@ -186,7 +186,7 @@ class TwigExtensionTest extends TestCase
$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 @@ class TwigExtensionTest extends TestCase
$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];
}
}

View File

@ -101,7 +101,7 @@ class WebDebugToolbarListener implements EventSubscriberInterface
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;')
) {

View File

@ -98,7 +98,7 @@ class WebProfilerExtension extends ProfilerExtension
$message = twig_escape_filter($env, $message);
$message = preg_replace('/&quot;(.*?)&quot;/', '&quot;<b>$1</b>&quot;', $message);
if (null === $context || false === strpos($message, '{')) {
if (null === $context || !str_contains($message, '{')) {
return '<span class="dump-inline">'.$message.'</span>';
}

View File

@ -100,7 +100,7 @@ EOF
'multiline' => OutputInterface::VERBOSITY_DEBUG <= $output->getVerbosity(),
]));
if (false === strpos($host = $input->getOption('host'), '://')) {
if (!str_contains($host = $input->getOption('host'), '://')) {
$host = 'tcp://'.$host;
}

View File

@ -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": {

View File

@ -73,6 +73,6 @@ class Package implements PackageInterface
*/
protected function isAbsoluteUrl($url)
{
return false !== strpos($url, '://') || '//' === substr($url, 0, 2);
return str_contains($url, '://') || '//' === substr($url, 0, 2);
}
}

View File

@ -16,7 +16,8 @@
}
],
"require": {
"php": ">=7.1.3"
"php": ">=7.1.3",
"symfony/polyfill-php80": "^1.16"
},
"suggest": {
"symfony/http-foundation": ""

View File

@ -662,7 +662,7 @@ abstract class Client
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 @@ abstract class Client
}
// protocol relative URL
if (0 === strpos($uri, '//')) {
if (str_starts_with($uri, '//')) {
return parse_url($currentUri, \PHP_URL_SCHEME).':'.$uri;
}

View File

@ -132,7 +132,7 @@ class Cookie
{
$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]));
}

View File

@ -52,7 +52,7 @@ class CookieJar
}
foreach ($pathCookies as $cookiePath => $namedCookies) {
if (0 !== strpos($path, $cookiePath)) {
if (!str_starts_with($path, $cookiePath)) {
continue;
}
if (isset($namedCookies[$name])) {

View File

@ -100,7 +100,7 @@ class HttpBrowser extends AbstractBrowser
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_

View File

@ -134,10 +134,10 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg
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);
}

View File

@ -88,7 +88,7 @@ class RedisTagAwareAdapter extends AbstractTagAwareAdapter
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));
}

View File

@ -237,7 +237,7 @@ class TagAwareAdapter implements TagAwareAdapterInterface, TagAwareCacheInterfac
if ('' !== $prefix) {
foreach ($this->deferred as $key => $item) {
if (0 === strpos($key, $prefix)) {
if (str_starts_with($key, $prefix)) {
unset($this->deferred[$key]);
}
}

View File

@ -34,7 +34,7 @@ class FilesystemAdapterTest extends AdapterTestCase
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(

View File

@ -79,7 +79,7 @@ trait ArrayTrait
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]);
}
}

View File

@ -58,7 +58,7 @@ trait FilesystemCommonTrait
$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 @@ trait FilesystemCommonTrait
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;
}

View File

@ -106,7 +106,7 @@ trait MemcachedTrait
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) {

View File

@ -90,9 +90,9 @@ trait RedisTrait
*/
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));

View File

@ -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"
},

View File

@ -55,7 +55,7 @@ class ArrayNode extends BaseNode implements PrototypeNodeInterface
$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;

View File

@ -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 @@ abstract class BaseNode implements NodeInterface
}
foreach (self::$placeholderUniquePrefixes as $placeholderUniquePrefix) {
if (0 === strpos($value, $placeholderUniquePrefix)) {
if (str_starts_with($value, $placeholderUniquePrefix)) {
return [];
}
}

View File

@ -73,12 +73,12 @@ abstract class FileLoader extends Loader
*/
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 @@ abstract class FileLoader extends Loader
}
$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 @@ abstract class FileLoader extends Loader
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 {

View File

@ -55,7 +55,7 @@ class ComposerResource implements SelfCheckingResourceInterface
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')) {

View File

@ -110,10 +110,10 @@ class GlobResource implements \IteratorAggregate, SelfCheckingResourceInterface
$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 @@ class GlobResource implements \IteratorAggregate, SelfCheckingResourceInterface
$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;

View File

@ -83,7 +83,7 @@ class ReflectionClassResource implements SelfCheckingResourceInterface
$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;
}

View File

@ -25,7 +25,7 @@ class ComposerResourceTest extends TestCase
$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;
}

View File

@ -877,7 +877,7 @@ class Application implements ResetInterface
$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 @@ class Application implements ResetInterface
}
$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 @@ class Application implements ResetInterface
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;
}
}

View File

@ -613,7 +613,7 @@ class Command
*/
public function addUsage($usage)
{
if (0 !== strpos($usage, $this->name)) {
if (!str_starts_with($usage, $this->name)) {
$usage = sprintf('%s %s', $this->name, $usage);
}

View File

@ -180,7 +180,7 @@ class OutputFormatter implements WrappableOutputFormatterInterface
$output .= $this->applyCurrentStyle(substr($message, $offset), $output, $width, $currentLineLength);
if (false !== strpos($output, "\0")) {
if (str_contains($output, "\0")) {
return strtr($output, ["\0" => '\\', '\\<' => '<']);
}

View File

@ -311,7 +311,7 @@ class QuestionHelper extends Helper
$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 @@ class QuestionHelper extends Helper
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 @@ class QuestionHelper extends Helper
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;
}

View File

@ -75,7 +75,7 @@ class ArgvInput extends Input
$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 @@ class ArgvInput extends Input
$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 @@ class ArgvInput extends Input
// 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 @@ class ArgvInput extends Input
// 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));
}
}

View File

@ -133,9 +133,9 @@ class ArrayInput extends Input
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);

View File

@ -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);
}

View File

@ -104,7 +104,7 @@ class ConsoleLogger extends AbstractLogger
*/
private function interpolate(string $message, array $context): string
{
if (false === strpos($message, '{')) {
if (!str_contains($message, '{')) {
return $message;
}

View File

@ -79,7 +79,7 @@ class Parser implements ParserInterface
return [2, 0];
case 'n' === $joined:
return [1, 0];
case false === strpos($joined, 'n'):
case !str_contains($joined, 'n'):
return [0, $int($joined)];
}

View File

@ -63,11 +63,11 @@ class Translator implements TranslatorInterface
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.'"';
}

View File

@ -20,7 +20,8 @@
}
],
"require": {
"php": ">=7.1.3"
"php": ">=7.1.3",
"symfony/polyfill-php80": "^1.16"
},
"autoload": {
"psr-4": { "Symfony\\Component\\CssSelector\\": "" },

View File

@ -210,7 +210,7 @@ class DebugClassLoader
}
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 @@ class DebugClassLoader
// 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 @@ class DebugClassLoader
$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)) {

View File

@ -385,7 +385,7 @@ class ErrorHandler
*/
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 @@ class ErrorHandler
}
$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 @@ class ErrorHandler
$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 @@ class ErrorHandler
$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);

View File

@ -134,7 +134,7 @@ class FlattenException
*/
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 @@ class FlattenException
*/
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);

View File

@ -401,7 +401,7 @@ EOF;
$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;
}

View File

@ -149,7 +149,7 @@ class ClassNotFoundFatalErrorHandler implements FatalErrorHandlerInterface
];
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

View File

@ -43,7 +43,7 @@ class UndefinedFunctionFatalErrorHandler implements FatalErrorHandlerInterface
$prefix = 'Call to undefined function ';
$prefixLen = \strlen($prefix);
if (0 !== strpos($error['message'], $prefix)) {
if (!str_starts_with($error['message'], $prefix)) {
return null;
}

View File

@ -48,7 +48,7 @@ class UndefinedMethodFatalErrorHandler implements FatalErrorHandlerInterface
$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;
}
}

View File

@ -103,7 +103,7 @@ class Alias
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.');
}

View File

@ -97,7 +97,7 @@ class ChildDefinition extends Definition
{
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.');

View File

@ -297,7 +297,7 @@ class AutowirePass extends AbstractRecursivePass
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());
}
}

View File

@ -49,7 +49,7 @@ class CheckDefinitionValidityPass implements CompilerPassInterface
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)));
}

View File

@ -231,7 +231,7 @@ final class CheckTypeDeclarationsPass extends AbstractRecursivePass
$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) {

View File

@ -67,7 +67,7 @@ class Compiler
*/
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));
}

View File

@ -209,7 +209,7 @@ class MergeExtensionConfigurationContainerBuilder extends ContainerBuilder
}
foreach ($bag->getEnvPlaceholders() as $env => $placeholders) {
if (false === strpos($env, ':')) {
if (!str_contains($env, ':')) {
continue;
}
foreach ($placeholders as $placeholder) {

View File

@ -91,7 +91,7 @@ class RegisterServiceSubscribersPass extends AbstractRecursivePass
if ($name) {
if (false !== $i = strpos($name, '::get')) {
$name = lcfirst(substr($name, 5 + $i));
} elseif (false !== strpos($name, '::')) {
} elseif (str_contains($name, '::')) {
$name = null;
}
}

View File

@ -44,7 +44,7 @@ class ResolveBindingsPass extends AbstractRecursivePass
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;

View File

@ -158,7 +158,7 @@ class ResolveChildDefinitionsPass extends AbstractRecursivePass
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);

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