minor #39959 Changed private static array-properties to const (simonberger)

This PR was merged into the 4.4 branch.

Discussion
----------

Changed private static array-properties to const

| Q             | A
| ------------- | ---
| Branch?       | 4.4
| Bug fix?      | no
| New feature?  | no
| Deprecations? | no
| License       | MIT

This changes all private static properties (just screened arrays) to private const. I left out those which have write access obviously and also those with `static::` access.

It is a new implementation of #38213. Based on 4.4 this time.
If merging it up creates several conflicts, you could ignore all changes of 4.4 and I create a new branch for 5.1 or 5.2. I'll do this anyway if any new private static arrays are existing there.

Commits
-------

aa79381fe4 Changed private static array-properties to const
This commit is contained in:
Nicolas Grekas 2021-01-25 14:56:02 +01:00
commit 4181c431e9
62 changed files with 296 additions and 300 deletions

View File

@ -28,7 +28,7 @@ use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
*/ */
class ServerLogCommand extends Command class ServerLogCommand extends Command
{ {
private static $bgColor = ['black', 'blue', 'cyan', 'green', 'magenta', 'red', 'white', 'yellow']; private const BG_COLOR = ['black', 'blue', 'cyan', 'green', 'magenta', 'red', 'white', 'yellow'];
private $el; private $el;
private $handler; private $handler;
@ -151,7 +151,7 @@ EOF
if (isset($record['log_id'])) { if (isset($record['log_id'])) {
$clientId = unpack('H*', $record['log_id'])[1]; $clientId = unpack('H*', $record['log_id'])[1];
} }
$logBlock = sprintf('<bg=%s> </>', self::$bgColor[$clientId % 8]); $logBlock = sprintf('<bg=%s> </>', self::BG_COLOR[$clientId % 8]);
$output->write($logBlock); $output->write($logBlock);
$this->handler->handle($record); $this->handler->handle($record);

View File

@ -30,7 +30,7 @@ class ConsoleFormatter implements FormatterInterface
public const SIMPLE_FORMAT = "%datetime% %start_tag%%level_name%%end_tag% <comment>[%channel%]</> %message%%context%%extra%\n"; public const SIMPLE_FORMAT = "%datetime% %start_tag%%level_name%%end_tag% <comment>[%channel%]</> %message%%context%%extra%\n";
public const SIMPLE_DATE = 'H:i:s'; public const SIMPLE_DATE = 'H:i:s';
private static $levelColorMap = [ private const LEVEL_COLOR_MAP = [
Logger::DEBUG => 'fg=white', Logger::DEBUG => 'fg=white',
Logger::INFO => 'fg=green', Logger::INFO => 'fg=green',
Logger::NOTICE => 'fg=blue', Logger::NOTICE => 'fg=blue',
@ -104,8 +104,6 @@ class ConsoleFormatter implements FormatterInterface
{ {
$record = $this->replacePlaceHolder($record); $record = $this->replacePlaceHolder($record);
$levelColor = self::$levelColorMap[$record['level']];
if (!$this->options['ignore_empty_context_and_extra'] || !empty($record['context'])) { if (!$this->options['ignore_empty_context_and_extra'] || !empty($record['context'])) {
$context = ($this->options['multiline'] ? "\n" : ' ').$this->dumpData($record['context']); $context = ($this->options['multiline'] ? "\n" : ' ').$this->dumpData($record['context']);
} else { } else {
@ -122,7 +120,7 @@ class ConsoleFormatter implements FormatterInterface
'%datetime%' => $record['datetime'] instanceof \DateTimeInterface '%datetime%' => $record['datetime'] instanceof \DateTimeInterface
? $record['datetime']->format($this->options['date_format']) ? $record['datetime']->format($this->options['date_format'])
: $record['datetime'], : $record['datetime'],
'%start_tag%' => sprintf('<%s>', $levelColor), '%start_tag%' => sprintf('<%s>', self::LEVEL_COLOR_MAP[$record['level']]),
'%level_name%' => sprintf($this->options['level_name_format'], $record['level_name']), '%level_name%' => sprintf($this->options['level_name_format'], $record['level_name']),
'%end_tag%' => '</>', '%end_tag%' => '</>',
'%channel%' => $record['channel'], '%channel%' => $record['channel'],

View File

@ -19,7 +19,7 @@ use Twig\Error\SyntaxError;
*/ */
class UndefinedCallableHandler class UndefinedCallableHandler
{ {
private static $filterComponents = [ private const FILTER_COMPONENTS = [
'humanize' => 'form', 'humanize' => 'form',
'trans' => 'translation', 'trans' => 'translation',
'transchoice' => 'translation', 'transchoice' => 'translation',
@ -27,7 +27,7 @@ class UndefinedCallableHandler
'yaml_dump' => 'yaml', 'yaml_dump' => 'yaml',
]; ];
private static $functionComponents = [ private const FUNCTION_COMPONENTS = [
'asset' => 'asset', 'asset' => 'asset',
'asset_version' => 'asset', 'asset_version' => 'asset',
'dump' => 'debug-bundle', 'dump' => 'debug-bundle',
@ -57,7 +57,7 @@ class UndefinedCallableHandler
'workflow_marked_places' => 'workflow', 'workflow_marked_places' => 'workflow',
]; ];
private static $fullStackEnable = [ private const FULL_STACK_ENABLE = [
'form' => 'enable "framework.form"', 'form' => 'enable "framework.form"',
'security-core' => 'add the "SecurityBundle"', 'security-core' => 'add the "SecurityBundle"',
'security-http' => 'add the "SecurityBundle"', 'security-http' => 'add the "SecurityBundle"',
@ -67,30 +67,30 @@ class UndefinedCallableHandler
public static function onUndefinedFilter(string $name): bool public static function onUndefinedFilter(string $name): bool
{ {
if (!isset(self::$filterComponents[$name])) { if (!isset(self::FILTER_COMPONENTS[$name])) {
return false; return false;
} }
self::onUndefined($name, 'filter', self::$filterComponents[$name]); self::onUndefined($name, 'filter', self::FILTER_COMPONENTS[$name]);
return true; return true;
} }
public static function onUndefinedFunction(string $name): bool public static function onUndefinedFunction(string $name): bool
{ {
if (!isset(self::$functionComponents[$name])) { if (!isset(self::FUNCTION_COMPONENTS[$name])) {
return false; return false;
} }
self::onUndefined($name, 'function', self::$functionComponents[$name]); self::onUndefined($name, 'function', self::FUNCTION_COMPONENTS[$name]);
return true; return true;
} }
private static function onUndefined(string $name, string $type, string $component) private static function onUndefined(string $name, string $type, string $component)
{ {
if (class_exists(FullStack::class) && isset(self::$fullStackEnable[$component])) { if (class_exists(FullStack::class) && isset(self::FULL_STACK_ENABLE[$component])) {
throw new SyntaxError(sprintf('Did you forget to %s? Unknown %s "%s".', self::$fullStackEnable[$component], $type, $name)); throw new SyntaxError(sprintf('Did you forget to %s? Unknown %s "%s".', self::FULL_STACK_ENABLE[$component], $type, $name));
} }
throw new SyntaxError(sprintf('Did you forget to run "composer require symfony/%s"? Unknown %s "%s".', $component, $type, $name)); throw new SyntaxError(sprintf('Did you forget to run "composer require symfony/%s"? Unknown %s "%s".', $component, $type, $name));

View File

@ -30,7 +30,7 @@ use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
*/ */
class ServerLogCommand extends Command class ServerLogCommand extends Command
{ {
private static $bgColor = ['black', 'blue', 'cyan', 'green', 'magenta', 'red', 'white', 'yellow']; private const BG_COLOR = ['black', 'blue', 'cyan', 'green', 'magenta', 'red', 'white', 'yellow'];
private $el; private $el;
private $handler; private $handler;
@ -155,7 +155,7 @@ EOF
if (isset($record['log_id'])) { if (isset($record['log_id'])) {
$clientId = unpack('H*', $record['log_id'])[1]; $clientId = unpack('H*', $record['log_id'])[1];
} }
$logBlock = sprintf('<bg=%s> </>', self::$bgColor[$clientId % 8]); $logBlock = sprintf('<bg=%s> </>', self::BG_COLOR[$clientId % 8]);
$output->write($logBlock); $output->write($logBlock);
$this->handler->handle($record); $this->handler->handle($record);

View File

@ -22,7 +22,7 @@ class Cookie
* Handles dates as defined by RFC 2616 section 3.3.1, and also some other * Handles dates as defined by RFC 2616 section 3.3.1, and also some other
* non-standard, but common formats. * non-standard, but common formats.
*/ */
private static $dateFormats = [ private const DATE_FORMATS = [
'D, d M Y H:i:s T', 'D, d M Y H:i:s T',
'D, d-M-y H:i:s T', 'D, d-M-y H:i:s T',
'D, d-M-Y H:i:s T', 'D, d-M-Y H:i:s T',
@ -92,7 +92,7 @@ class Cookie
if (null !== $this->expires) { if (null !== $this->expires) {
$dateTime = \DateTime::createFromFormat('U', $this->expires, new \DateTimeZone('GMT')); $dateTime = \DateTime::createFromFormat('U', $this->expires, new \DateTimeZone('GMT'));
$cookie .= '; expires='.str_replace('+0000', '', $dateTime->format(self::$dateFormats[0])); $cookie .= '; expires='.str_replace('+0000', '', $dateTime->format(self::DATE_FORMATS[0]));
} }
if ('' !== $this->domain) { if ('' !== $this->domain) {
@ -208,7 +208,7 @@ class Cookie
$dateValue = substr($dateValue, 1, -1); $dateValue = substr($dateValue, 1, -1);
} }
foreach (self::$dateFormats as $dateFormat) { foreach (self::DATE_FORMATS as $dateFormat) {
if (false !== $date = \DateTime::createFromFormat($dateFormat, $dateValue, new \DateTimeZone('GMT'))) { if (false !== $date = \DateTime::createFromFormat($dateFormat, $dateValue, new \DateTimeZone('GMT'))) {
return $date->format('U'); return $date->format('U');
} }

View File

@ -25,7 +25,7 @@ use Symfony\Component\DependencyInjection\Reference;
*/ */
class RegisterEnvVarProcessorsPass implements CompilerPassInterface class RegisterEnvVarProcessorsPass implements CompilerPassInterface
{ {
private static $allowedTypes = ['array', 'bool', 'float', 'int', 'string']; private const ALLOWED_TYPES = ['array', 'bool', 'float', 'int', 'string'];
public function process(ContainerBuilder $container) public function process(ContainerBuilder $container)
{ {
@ -65,8 +65,8 @@ class RegisterEnvVarProcessorsPass implements CompilerPassInterface
$types = explode('|', $types); $types = explode('|', $types);
foreach ($types as $type) { foreach ($types as $type) {
if (!\in_array($type, self::$allowedTypes)) { if (!\in_array($type, self::ALLOWED_TYPES)) {
throw new InvalidArgumentException(sprintf('Invalid type "%s" returned by "%s::getProvidedTypes()", expected one of "%s".', $type, $class, implode('", "', self::$allowedTypes))); throw new InvalidArgumentException(sprintf('Invalid type "%s" returned by "%s::getProvidedTypes()", expected one of "%s".', $type, $class, implode('", "', self::ALLOWED_TYPES)));
} }
} }

View File

@ -26,7 +26,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
*/ */
class ValidateEnvPlaceholdersPass implements CompilerPassInterface class ValidateEnvPlaceholdersPass implements CompilerPassInterface
{ {
private static $typeFixtures = ['array' => [], 'bool' => false, 'float' => 0.0, 'int' => 0, 'string' => '']; private const TYPE_FIXTURES = ['array' => [], 'bool' => false, 'float' => 0.0, 'int' => 0, 'string' => ''];
private $extensionConfig = []; private $extensionConfig = [];
@ -52,13 +52,13 @@ class ValidateEnvPlaceholdersPass implements CompilerPassInterface
foreach ($resolvingBag->getEnvPlaceholders() + $resolvingBag->getUnusedEnvPlaceholders() as $env => $placeholders) { foreach ($resolvingBag->getEnvPlaceholders() + $resolvingBag->getUnusedEnvPlaceholders() as $env => $placeholders) {
$values = []; $values = [];
if (false === $i = strpos($env, ':')) { if (false === $i = strpos($env, ':')) {
$default = $defaultBag->has("env($env)") ? $defaultBag->get("env($env)") : self::$typeFixtures['string']; $default = $defaultBag->has("env($env)") ? $defaultBag->get("env($env)") : self::TYPE_FIXTURES['string'];
$defaultType = null !== $default ? self::getType($default) : 'string'; $defaultType = null !== $default ? self::getType($default) : 'string';
$values[$defaultType] = $default; $values[$defaultType] = $default;
} else { } else {
$prefix = substr($env, 0, $i); $prefix = substr($env, 0, $i);
foreach ($envTypes[$prefix] ?? ['string'] as $type) { foreach ($envTypes[$prefix] ?? ['string'] as $type) {
$values[$type] = self::$typeFixtures[$type] ?? null; $values[$type] = self::TYPE_FIXTURES[$type] ?? null;
} }
} }
foreach ($placeholders as $placeholder) { foreach ($placeholders as $placeholder) {

View File

@ -126,7 +126,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface
private $removedBindingIds = []; private $removedBindingIds = [];
private static $internalTypes = [ private const INTERNAL_TYPES = [
'int' => true, 'int' => true,
'float' => true, 'float' => true,
'string' => true, 'string' => true,
@ -339,7 +339,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface
return null; return null;
} }
if (isset(self::$internalTypes[$class])) { if (isset(self::INTERNAL_TYPES[$class])) {
return null; return null;
} }

View File

@ -38,7 +38,7 @@ use Symfony\Component\Yaml\Yaml;
*/ */
class YamlFileLoader extends FileLoader class YamlFileLoader extends FileLoader
{ {
private static $serviceKeywords = [ private const SERVICE_KEYWORDS = [
'alias' => 'alias', 'alias' => 'alias',
'parent' => 'parent', 'parent' => 'parent',
'class' => 'class', 'class' => 'class',
@ -64,7 +64,7 @@ class YamlFileLoader extends FileLoader
'bind' => 'bind', 'bind' => 'bind',
]; ];
private static $prototypeKeywords = [ private const PROTOTYPE_KEYWORDS = [
'resource' => 'resource', 'resource' => 'resource',
'namespace' => 'namespace', 'namespace' => 'namespace',
'exclude' => 'exclude', 'exclude' => 'exclude',
@ -85,7 +85,7 @@ class YamlFileLoader extends FileLoader
'bind' => 'bind', 'bind' => 'bind',
]; ];
private static $instanceofKeywords = [ private const INSTANCEOF_KEYWORDS = [
'shared' => 'shared', 'shared' => 'shared',
'lazy' => 'lazy', 'lazy' => 'lazy',
'public' => 'public', 'public' => 'public',
@ -97,7 +97,7 @@ class YamlFileLoader extends FileLoader
'bind' => 'bind', 'bind' => 'bind',
]; ];
private static $defaultsKeywords = [ private const DEFAULTS_KEYWORDS = [
'public' => 'public', 'public' => 'public',
'tags' => 'tags', 'tags' => 'tags',
'autowire' => 'autowire', 'autowire' => 'autowire',
@ -250,8 +250,8 @@ class YamlFileLoader extends FileLoader
} }
foreach ($defaults as $key => $default) { foreach ($defaults as $key => $default) {
if (!isset(self::$defaultsKeywords[$key])) { if (!isset(self::DEFAULTS_KEYWORDS[$key])) {
throw new InvalidArgumentException(sprintf('The configuration key "%s" cannot be used to define a default value in "%s". Allowed keys are "%s".', $key, $file, implode('", "', self::$defaultsKeywords))); throw new InvalidArgumentException(sprintf('The configuration key "%s" cannot be used to define a default value in "%s". Allowed keys are "%s".', $key, $file, implode('", "', self::DEFAULTS_KEYWORDS)));
} }
} }
@ -864,11 +864,11 @@ class YamlFileLoader extends FileLoader
private function checkDefinition(string $id, array $definition, string $file) private function checkDefinition(string $id, array $definition, string $file)
{ {
if ($this->isLoadingInstanceof) { if ($this->isLoadingInstanceof) {
$keywords = self::$instanceofKeywords; $keywords = self::INSTANCEOF_KEYWORDS;
} elseif (isset($definition['resource']) || isset($definition['namespace'])) { } elseif (isset($definition['resource']) || isset($definition['namespace'])) {
$keywords = self::$prototypeKeywords; $keywords = self::PROTOTYPE_KEYWORDS;
} else { } else {
$keywords = self::$serviceKeywords; $keywords = self::SERVICE_KEYWORDS;
} }
foreach ($definition as $key => $value) { foreach ($definition as $key => $value) {

View File

@ -20,13 +20,13 @@ use Symfony\Component\ExpressionLanguage\Compiler;
*/ */
class BinaryNode extends Node class BinaryNode extends Node
{ {
private static $operators = [ private const OPERATORS = [
'~' => '.', '~' => '.',
'and' => '&&', 'and' => '&&',
'or' => '||', 'or' => '||',
]; ];
private static $functions = [ private const FUNCTIONS = [
'**' => 'pow', '**' => 'pow',
'..' => 'range', '..' => 'range',
'in' => 'in_array', 'in' => 'in_array',
@ -57,9 +57,9 @@ class BinaryNode extends Node
return; return;
} }
if (isset(self::$functions[$operator])) { if (isset(self::FUNCTIONS[$operator])) {
$compiler $compiler
->raw(sprintf('%s(', self::$functions[$operator])) ->raw(sprintf('%s(', self::FUNCTIONS[$operator]))
->compile($this->nodes['left']) ->compile($this->nodes['left'])
->raw(', ') ->raw(', ')
->compile($this->nodes['right']) ->compile($this->nodes['right'])
@ -69,8 +69,8 @@ class BinaryNode extends Node
return; return;
} }
if (isset(self::$operators[$operator])) { if (isset(self::OPERATORS[$operator])) {
$operator = self::$operators[$operator]; $operator = self::OPERATORS[$operator];
} }
$compiler $compiler
@ -89,13 +89,13 @@ class BinaryNode extends Node
$operator = $this->attributes['operator']; $operator = $this->attributes['operator'];
$left = $this->nodes['left']->evaluate($functions, $values); $left = $this->nodes['left']->evaluate($functions, $values);
if (isset(self::$functions[$operator])) { if (isset(self::FUNCTIONS[$operator])) {
$right = $this->nodes['right']->evaluate($functions, $values); $right = $this->nodes['right']->evaluate($functions, $values);
if ('not in' === $operator) { if ('not in' === $operator) {
return !\in_array($left, $right); return !\in_array($left, $right);
} }
$f = self::$functions[$operator]; $f = self::FUNCTIONS[$operator];
return $f($left, $right); return $f($left, $right);
} }

View File

@ -20,7 +20,7 @@ use Symfony\Component\ExpressionLanguage\Compiler;
*/ */
class UnaryNode extends Node class UnaryNode extends Node
{ {
private static $operators = [ private const OPERATORS = [
'!' => '!', '!' => '!',
'not' => '!', 'not' => '!',
'+' => '+', '+' => '+',
@ -39,7 +39,7 @@ class UnaryNode extends Node
{ {
$compiler $compiler
->raw('(') ->raw('(')
->raw(self::$operators[$this->attributes['operator']]) ->raw(self::OPERATORS[$this->attributes['operator']])
->compile($this->nodes['node']) ->compile($this->nodes['node'])
->raw(')') ->raw(')')
; ;

View File

@ -30,7 +30,7 @@ class DateIntervalToArrayTransformer implements DataTransformerInterface
public const SECONDS = 'seconds'; public const SECONDS = 'seconds';
public const INVERT = 'invert'; public const INVERT = 'invert';
private static $availableFields = [ private const AVAILABLE_FIELDS = [
self::YEARS => 'y', self::YEARS => 'y',
self::MONTHS => 'm', self::MONTHS => 'm',
self::DAYS => 'd', self::DAYS => 'd',
@ -85,7 +85,7 @@ class DateIntervalToArrayTransformer implements DataTransformerInterface
throw new UnexpectedTypeException($dateInterval, \DateInterval::class); throw new UnexpectedTypeException($dateInterval, \DateInterval::class);
} }
$result = []; $result = [];
foreach (self::$availableFields as $field => $char) { foreach (self::AVAILABLE_FIELDS as $field => $char) {
$result[$field] = $dateInterval->format('%'.($this->pad ? strtoupper($char) : $char)); $result[$field] = $dateInterval->format('%'.($this->pad ? strtoupper($char) : $char));
} }
if (\in_array('weeks', $this->fields, true)) { if (\in_array('weeks', $this->fields, true)) {
@ -134,7 +134,7 @@ class DateIntervalToArrayTransformer implements DataTransformerInterface
if (isset($value['invert']) && !\is_bool($value['invert'])) { if (isset($value['invert']) && !\is_bool($value['invert'])) {
throw new TransformationFailedException('The value of "invert" must be boolean.'); throw new TransformationFailedException('The value of "invert" must be boolean.');
} }
foreach (self::$availableFields as $field => $char) { foreach (self::AVAILABLE_FIELDS as $field => $char) {
if ('invert' !== $field && isset($value[$field]) && !ctype_digit((string) $value[$field])) { if ('invert' !== $field && isset($value[$field]) && !ctype_digit((string) $value[$field])) {
throw new TransformationFailedException(sprintf('This amount of "%s" is invalid.', $field)); throw new TransformationFailedException(sprintf('This amount of "%s" is invalid.', $field));
} }

View File

@ -37,7 +37,7 @@ class DateIntervalType extends AbstractType
'minutes', 'minutes',
'seconds', 'seconds',
]; ];
private static $widgets = [ private const WIDGETS = [
'text' => TextType::class, 'text' => TextType::class,
'integer' => IntegerType::class, 'integer' => IntegerType::class,
'choice' => ChoiceType::class, 'choice' => ChoiceType::class,
@ -112,7 +112,7 @@ class DateIntervalType extends AbstractType
$childOptions['choices'] = $options[$part]; $childOptions['choices'] = $options[$part];
$childOptions['placeholder'] = $options['placeholder'][$part]; $childOptions['placeholder'] = $options['placeholder'][$part];
} }
$childForm = $builder->create($part, self::$widgets[$options['widget']], $childOptions); $childForm = $builder->create($part, self::WIDGETS[$options['widget']], $childOptions);
if ('integer' === $options['widget']) { if ('integer' === $options['widget']) {
$childForm->addModelTransformer( $childForm->addModelTransformer(
new ReversedTransformer( new ReversedTransformer(

View File

@ -40,7 +40,7 @@ class DateTimeType extends AbstractType
*/ */
public const HTML5_FORMAT = "yyyy-MM-dd'T'HH:mm:ss"; public const HTML5_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
private static $acceptedFormats = [ private const ACCEPTED_FORMATS = [
\IntlDateFormatter::FULL, \IntlDateFormatter::FULL,
\IntlDateFormatter::LONG, \IntlDateFormatter::LONG,
\IntlDateFormatter::MEDIUM, \IntlDateFormatter::MEDIUM,
@ -71,7 +71,7 @@ class DateTimeType extends AbstractType
$calendar = \IntlDateFormatter::GREGORIAN; $calendar = \IntlDateFormatter::GREGORIAN;
$pattern = \is_string($options['format']) ? $options['format'] : null; $pattern = \is_string($options['format']) ? $options['format'] : null;
if (!\in_array($dateFormat, self::$acceptedFormats, true)) { if (!\in_array($dateFormat, self::ACCEPTED_FORMATS, true)) {
throw new InvalidOptionsException('The "date_format" option must be one of the IntlDateFormatter constants (FULL, LONG, MEDIUM, SHORT) or a string representing a custom format.'); throw new InvalidOptionsException('The "date_format" option must be one of the IntlDateFormatter constants (FULL, LONG, MEDIUM, SHORT) or a string representing a custom format.');
} }

View File

@ -31,14 +31,14 @@ class DateType extends AbstractType
public const DEFAULT_FORMAT = \IntlDateFormatter::MEDIUM; public const DEFAULT_FORMAT = \IntlDateFormatter::MEDIUM;
public const HTML5_FORMAT = 'yyyy-MM-dd'; public const HTML5_FORMAT = 'yyyy-MM-dd';
private static $acceptedFormats = [ private const ACCEPTED_FORMATS = [
\IntlDateFormatter::FULL, \IntlDateFormatter::FULL,
\IntlDateFormatter::LONG, \IntlDateFormatter::LONG,
\IntlDateFormatter::MEDIUM, \IntlDateFormatter::MEDIUM,
\IntlDateFormatter::SHORT, \IntlDateFormatter::SHORT,
]; ];
private static $widgets = [ private const WIDGETS = [
'text' => 'Symfony\Component\Form\Extension\Core\Type\TextType', 'text' => 'Symfony\Component\Form\Extension\Core\Type\TextType',
'choice' => 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', 'choice' => 'Symfony\Component\Form\Extension\Core\Type\ChoiceType',
]; ];
@ -53,7 +53,7 @@ class DateType extends AbstractType
$calendar = \IntlDateFormatter::GREGORIAN; $calendar = \IntlDateFormatter::GREGORIAN;
$pattern = \is_string($options['format']) ? $options['format'] : ''; $pattern = \is_string($options['format']) ? $options['format'] : '';
if (!\in_array($dateFormat, self::$acceptedFormats, true)) { if (!\in_array($dateFormat, self::ACCEPTED_FORMATS, true)) {
throw new InvalidOptionsException('The "format" option must be one of the IntlDateFormatter constants (FULL, LONG, MEDIUM, SHORT) or a string representing a custom format.'); throw new InvalidOptionsException('The "format" option must be one of the IntlDateFormatter constants (FULL, LONG, MEDIUM, SHORT) or a string representing a custom format.');
} }
@ -155,9 +155,9 @@ class DateType extends AbstractType
} }
$builder $builder
->add('year', self::$widgets[$options['widget']], $yearOptions) ->add('year', self::WIDGETS[$options['widget']], $yearOptions)
->add('month', self::$widgets[$options['widget']], $monthOptions) ->add('month', self::WIDGETS[$options['widget']], $monthOptions)
->add('day', self::$widgets[$options['widget']], $dayOptions) ->add('day', self::WIDGETS[$options['widget']], $dayOptions)
->addViewTransformer(new DateTimeToArrayTransformer( ->addViewTransformer(new DateTimeToArrayTransformer(
$options['model_timezone'], $options['view_timezone'], ['year', 'month', 'day'] $options['model_timezone'], $options['view_timezone'], ['year', 'month', 'day']
)) ))

View File

@ -28,7 +28,7 @@ class FileType extends AbstractType
public const KIB_BYTES = 1024; public const KIB_BYTES = 1024;
public const MIB_BYTES = 1048576; public const MIB_BYTES = 1048576;
private static $suffixes = [ private const SUFFIXES = [
1 => 'bytes', 1 => 'bytes',
self::KIB_BYTES => 'KiB', self::KIB_BYTES => 'KiB',
self::MIB_BYTES => 'MiB', self::MIB_BYTES => 'MiB',
@ -244,7 +244,7 @@ class FileType extends AbstractType
$sizeAsString = (string) round($size / $coef, 2); $sizeAsString = (string) round($size / $coef, 2);
} }
return [$limitAsString, self::$suffixes[$coef]]; return [$limitAsString, self::SUFFIXES[$coef]];
} }
/** /**

View File

@ -28,7 +28,7 @@ use Symfony\Component\OptionsResolver\OptionsResolver;
class TimeType extends AbstractType class TimeType extends AbstractType
{ {
private static $widgets = [ private const WIDGETS = [
'text' => 'Symfony\Component\Form\Extension\Core\Type\TextType', 'text' => 'Symfony\Component\Form\Extension\Core\Type\TextType',
'choice' => 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', 'choice' => 'Symfony\Component\Form\Extension\Core\Type\ChoiceType',
]; ];
@ -169,7 +169,7 @@ class TimeType extends AbstractType
} }
} }
$builder->add('hour', self::$widgets[$options['widget']], $hourOptions); $builder->add('hour', self::WIDGETS[$options['widget']], $hourOptions);
if ($options['with_minutes']) { if ($options['with_minutes']) {
if ($emptyData instanceof \Closure) { if ($emptyData instanceof \Closure) {
@ -177,7 +177,7 @@ class TimeType extends AbstractType
} elseif (isset($emptyData['minute'])) { } elseif (isset($emptyData['minute'])) {
$minuteOptions['empty_data'] = $emptyData['minute']; $minuteOptions['empty_data'] = $emptyData['minute'];
} }
$builder->add('minute', self::$widgets[$options['widget']], $minuteOptions); $builder->add('minute', self::WIDGETS[$options['widget']], $minuteOptions);
} }
if ($options['with_seconds']) { if ($options['with_seconds']) {
@ -186,7 +186,7 @@ class TimeType extends AbstractType
} elseif (isset($emptyData['second'])) { } elseif (isset($emptyData['second'])) {
$secondOptions['empty_data'] = $emptyData['second']; $secondOptions['empty_data'] = $emptyData['second'];
} }
$builder->add('second', self::$widgets[$options['widget']], $secondOptions); $builder->add('second', self::WIDGETS[$options['widget']], $secondOptions);
} }
$builder->addViewTransformer(new DateTimeToArrayTransformer($options['model_timezone'], $options['view_timezone'], $parts, 'text' === $options['widget'], $options['reference_date'])); $builder->addViewTransformer(new DateTimeToArrayTransformer($options['model_timezone'], $options['view_timezone'], $parts, 'text' === $options['widget'], $options['reference_date']));

View File

@ -23,7 +23,7 @@ use Symfony\Component\OptionsResolver\OptionsResolver;
class WeekType extends AbstractType class WeekType extends AbstractType
{ {
private static $widgets = [ private const WIDGETS = [
'text' => IntegerType::class, 'text' => IntegerType::class,
'choice' => ChoiceType::class, 'choice' => ChoiceType::class,
]; ];
@ -78,8 +78,8 @@ class WeekType extends AbstractType
} }
} }
$builder->add('year', self::$widgets[$options['widget']], $yearOptions); $builder->add('year', self::WIDGETS[$options['widget']], $yearOptions);
$builder->add('week', self::$widgets[$options['widget']], $weekOptions); $builder->add('week', self::WIDGETS[$options['widget']], $weekOptions);
} }
} }

View File

@ -26,7 +26,7 @@ class NativeRequestHandler implements RequestHandlerInterface
/** /**
* The allowed keys of the $_FILES array. * The allowed keys of the $_FILES array.
*/ */
private static $fileKeys = [ private const FILE_KEYS = [
'error', 'error',
'name', 'name',
'size', 'size',
@ -201,12 +201,12 @@ class NativeRequestHandler implements RequestHandlerInterface
$keys = array_keys($data); $keys = array_keys($data);
sort($keys); sort($keys);
if (self::$fileKeys !== $keys || !isset($data['name']) || !\is_array($data['name'])) { if (self::FILE_KEYS !== $keys || !isset($data['name']) || !\is_array($data['name'])) {
return $data; return $data;
} }
$files = $data; $files = $data;
foreach (self::$fileKeys as $k) { foreach (self::FILE_KEYS as $k) {
unset($files[$k]); unset($files[$k]);
} }
@ -237,7 +237,7 @@ class NativeRequestHandler implements RequestHandlerInterface
$keys = array_keys($data); $keys = array_keys($data);
sort($keys); sort($keys);
if (self::$fileKeys === $keys) { if (self::FILE_KEYS === $keys) {
if (\UPLOAD_ERR_NO_FILE === $data['error']) { if (\UPLOAD_ERR_NO_FILE === $data['error']) {
return null; return null;
} }

View File

@ -35,8 +35,8 @@ class Cookie
private $secureDefault = false; private $secureDefault = false;
private static $reservedCharsList = "=,; \t\r\n\v\f"; private static $reservedCharsList = "=,; \t\r\n\v\f";
private static $reservedCharsFrom = ['=', ',', ';', ' ', "\t", "\r", "\n", "\v", "\f"]; private const RESERVED_CHARS_FROM = ['=', ',', ';', ' ', "\t", "\r", "\n", "\v", "\f"];
private static $reservedCharsTo = ['%3D', '%2C', '%3B', '%20', '%09', '%0D', '%0A', '%0B', '%0C']; private const RESERVED_CHARS_TO = ['%3D', '%2C', '%3B', '%20', '%09', '%0D', '%0A', '%0B', '%0C'];
/** /**
* Creates cookie from raw header string. * Creates cookie from raw header string.
@ -149,7 +149,7 @@ class Cookie
if ($this->isRaw()) { if ($this->isRaw()) {
$str = $this->getName(); $str = $this->getName();
} else { } else {
$str = str_replace(self::$reservedCharsFrom, self::$reservedCharsTo, $this->getName()); $str = str_replace(self::RESERVED_CHARS_FROM, self::RESERVED_CHARS_TO, $this->getName());
} }
$str .= '='; $str .= '=';

View File

@ -21,7 +21,7 @@ use Symfony\Component\HttpFoundation\File\UploadedFile;
*/ */
class FileBag extends ParameterBag class FileBag extends ParameterBag
{ {
private static $fileKeys = ['error', 'name', 'size', 'tmp_name', 'type']; private const FILE_KEYS = ['error', 'name', 'size', 'tmp_name', 'type'];
/** /**
* @param array|UploadedFile[] $parameters An array of HTTP files * @param array|UploadedFile[] $parameters An array of HTTP files
@ -80,7 +80,7 @@ class FileBag extends ParameterBag
$keys = array_keys($file); $keys = array_keys($file);
sort($keys); sort($keys);
if ($keys == self::$fileKeys) { if (self::FILE_KEYS == $keys) {
if (\UPLOAD_ERR_NO_FILE == $file['error']) { if (\UPLOAD_ERR_NO_FILE == $file['error']) {
$file = null; $file = null;
} else { } else {
@ -118,12 +118,12 @@ class FileBag extends ParameterBag
$keys = array_keys($data); $keys = array_keys($data);
sort($keys); sort($keys);
if (self::$fileKeys != $keys || !isset($data['name']) || !\is_array($data['name'])) { if (self::FILE_KEYS != $keys || !isset($data['name']) || !\is_array($data['name'])) {
return $data; return $data;
} }
$files = $data; $files = $data;
foreach (self::$fileKeys as $k) { foreach (self::FILE_KEYS as $k) {
unset($files[$k]); unset($files[$k]);
} }

View File

@ -209,7 +209,7 @@ class Request
private static $trustedHeaderSet = -1; private static $trustedHeaderSet = -1;
private static $forwardedParams = [ private const FORWARDED_PARAMS = [
self::HEADER_X_FORWARDED_FOR => 'for', self::HEADER_X_FORWARDED_FOR => 'for',
self::HEADER_X_FORWARDED_HOST => 'host', self::HEADER_X_FORWARDED_HOST => 'host',
self::HEADER_X_FORWARDED_PROTO => 'proto', self::HEADER_X_FORWARDED_PROTO => 'proto',
@ -225,7 +225,7 @@ class Request
* The other headers are non-standard, but widely used * The other headers are non-standard, but widely used
* by popular reverse proxies (like Apache mod_proxy or Amazon EC2). * by popular reverse proxies (like Apache mod_proxy or Amazon EC2).
*/ */
private static $trustedHeaders = [ private const TRUSTED_HEADERS = [
self::HEADER_FORWARDED => 'FORWARDED', self::HEADER_FORWARDED => 'FORWARDED',
self::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR', self::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR',
self::HEADER_X_FORWARDED_HOST => 'X_FORWARDED_HOST', self::HEADER_X_FORWARDED_HOST => 'X_FORWARDED_HOST',
@ -1994,17 +1994,17 @@ class Request
$clientValues = []; $clientValues = [];
$forwardedValues = []; $forwardedValues = [];
if ((self::$trustedHeaderSet & $type) && $this->headers->has(self::$trustedHeaders[$type])) { if ((self::$trustedHeaderSet & $type) && $this->headers->has(self::TRUSTED_HEADERS[$type])) {
foreach (explode(',', $this->headers->get(self::$trustedHeaders[$type])) as $v) { foreach (explode(',', $this->headers->get(self::TRUSTED_HEADERS[$type])) as $v) {
$clientValues[] = (self::HEADER_X_FORWARDED_PORT === $type ? '0.0.0.0:' : '').trim($v); $clientValues[] = (self::HEADER_X_FORWARDED_PORT === $type ? '0.0.0.0:' : '').trim($v);
} }
} }
if ((self::$trustedHeaderSet & self::HEADER_FORWARDED) && $this->headers->has(self::$trustedHeaders[self::HEADER_FORWARDED])) { if ((self::$trustedHeaderSet & self::HEADER_FORWARDED) && $this->headers->has(self::TRUSTED_HEADERS[self::HEADER_FORWARDED])) {
$forwarded = $this->headers->get(self::$trustedHeaders[self::HEADER_FORWARDED]); $forwarded = $this->headers->get(self::TRUSTED_HEADERS[self::HEADER_FORWARDED]);
$parts = HeaderUtils::split($forwarded, ',;='); $parts = HeaderUtils::split($forwarded, ',;=');
$forwardedValues = []; $forwardedValues = [];
$param = self::$forwardedParams[$type]; $param = self::FORWARDED_PARAMS[$type];
foreach ($parts as $subParts) { foreach ($parts as $subParts) {
if (null === $v = HeaderUtils::combine($subParts)[$param] ?? null) { if (null === $v = HeaderUtils::combine($subParts)[$param] ?? null) {
continue; continue;
@ -2037,7 +2037,7 @@ class Request
} }
$this->isForwardedValid = false; $this->isForwardedValid = false;
throw new ConflictingHeadersException(sprintf('The request has both a trusted "%s" header and a trusted "%s" header, conflicting with each other. You should either configure your proxy to remove one of them, or configure your project to distrust the offending one.', self::$trustedHeaders[self::HEADER_FORWARDED], self::$trustedHeaders[$type])); throw new ConflictingHeadersException(sprintf('The request has both a trusted "%s" header and a trusted "%s" header, conflicting with each other. You should either configure your proxy to remove one of them, or configure your project to distrust the offending one.', self::TRUSTED_HEADERS[self::HEADER_FORWARDED], self::TRUSTED_HEADERS[$type]));
} }
private function normalizeAndFilterClientIps(array $clientIps, string $ip): array private function normalizeAndFilterClientIps(array $clientIps, string $ip): array

View File

@ -27,12 +27,12 @@ class ResponseCacheStrategy implements ResponseCacheStrategyInterface
/** /**
* Cache-Control headers that are sent to the final response if they appear in ANY of the responses. * Cache-Control headers that are sent to the final response if they appear in ANY of the responses.
*/ */
private static $overrideDirectives = ['private', 'no-cache', 'no-store', 'no-transform', 'must-revalidate', 'proxy-revalidate']; private const OVERRIDE_DIRECTIVES = ['private', 'no-cache', 'no-store', 'no-transform', 'must-revalidate', 'proxy-revalidate'];
/** /**
* Cache-Control headers that are sent to the final response if they appear in ALL of the responses. * Cache-Control headers that are sent to the final response if they appear in ALL of the responses.
*/ */
private static $inheritDirectives = ['public', 'immutable']; private const INHERIT_DIRECTIVES = ['public', 'immutable'];
private $embeddedResponses = 0; private $embeddedResponses = 0;
private $isNotCacheableResponseEmbedded = false; private $isNotCacheableResponseEmbedded = false;
@ -60,13 +60,13 @@ class ResponseCacheStrategy implements ResponseCacheStrategyInterface
{ {
++$this->embeddedResponses; ++$this->embeddedResponses;
foreach (self::$overrideDirectives as $directive) { foreach (self::OVERRIDE_DIRECTIVES as $directive) {
if ($response->headers->hasCacheControlDirective($directive)) { if ($response->headers->hasCacheControlDirective($directive)) {
$this->flagDirectives[$directive] = true; $this->flagDirectives[$directive] = true;
} }
} }
foreach (self::$inheritDirectives as $directive) { foreach (self::INHERIT_DIRECTIVES as $directive) {
if (false !== $this->flagDirectives[$directive]) { if (false !== $this->flagDirectives[$directive]) {
$this->flagDirectives[$directive] = $response->headers->hasCacheControlDirective($directive); $this->flagDirectives[$directive] = $response->headers->hasCacheControlDirective($directive);
} }

View File

@ -22,7 +22,7 @@ use Psr\Log\LogLevel;
*/ */
class Logger extends AbstractLogger class Logger extends AbstractLogger
{ {
private static $levels = [ private const LEVELS = [
LogLevel::DEBUG => 0, LogLevel::DEBUG => 0,
LogLevel::INFO => 1, LogLevel::INFO => 1,
LogLevel::NOTICE => 2, LogLevel::NOTICE => 2,
@ -52,11 +52,11 @@ class Logger extends AbstractLogger
} }
} }
if (!isset(self::$levels[$minLevel])) { if (!isset(self::LEVELS[$minLevel])) {
throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $minLevel)); throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $minLevel));
} }
$this->minLevelIndex = self::$levels[$minLevel]; $this->minLevelIndex = self::LEVELS[$minLevel];
$this->formatter = $formatter ?: [$this, 'format']; $this->formatter = $formatter ?: [$this, 'format'];
if ($output && false === $this->handle = \is_resource($output) ? $output : @fopen($output, 'a')) { if ($output && false === $this->handle = \is_resource($output) ? $output : @fopen($output, 'a')) {
throw new InvalidArgumentException(sprintf('Unable to open "%s".', $output)); throw new InvalidArgumentException(sprintf('Unable to open "%s".', $output));
@ -70,11 +70,11 @@ class Logger extends AbstractLogger
*/ */
public function log($level, $message, array $context = []) public function log($level, $message, array $context = [])
{ {
if (!isset(self::$levels[$level])) { if (!isset(self::LEVELS[$level])) {
throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $level)); throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $level));
} }
if (self::$levels[$level] < $this->minLevelIndex) { if (self::LEVELS[$level] < $this->minLevelIndex) {
return; return;
} }

View File

@ -23,7 +23,7 @@ final class Inflector
* *
* @see http://english-zone.com/spelling/plurals.html * @see http://english-zone.com/spelling/plurals.html
*/ */
private static $pluralMap = [ private const PLURAL_MAP = [
// First entry: plural suffix, reversed // First entry: plural suffix, reversed
// Second entry: length of plural suffix // Second entry: length of plural suffix
// Third entry: Whether the suffix may succeed a vocal // Third entry: Whether the suffix may succeed a vocal
@ -143,7 +143,7 @@ final class Inflector
* *
* @see http://english-zone.com/spelling/plurals.html * @see http://english-zone.com/spelling/plurals.html
*/ */
private static $singularMap = [ private const SINGULAR_MAP = [
// First entry: singular suffix, reversed // First entry: singular suffix, reversed
// Second entry: length of singular suffix // Second entry: length of singular suffix
// Third entry: Whether the suffix may succeed a vocal // Third entry: Whether the suffix may succeed a vocal
@ -309,7 +309,7 @@ final class Inflector
/** /**
* A list of words which should not be inflected, reversed. * A list of words which should not be inflected, reversed.
*/ */
private static $uninflected = [ private const UNINFLECTED = [
'', '',
'atad', 'atad',
'reed', 'reed',
@ -346,7 +346,7 @@ final class Inflector
$pluralLength = \strlen($lowerPluralRev); $pluralLength = \strlen($lowerPluralRev);
// Check if the word is one which is not inflected, return early if so // Check if the word is one which is not inflected, return early if so
if (\in_array($lowerPluralRev, self::$uninflected, true)) { if (\in_array($lowerPluralRev, self::UNINFLECTED, true)) {
return $plural; return $plural;
} }
@ -354,7 +354,7 @@ final class Inflector
// The inner loop $j iterates over the characters of the plural suffix // The inner loop $j iterates over the characters of the plural suffix
// in the plural table to compare them with the characters of the actual // in the plural table to compare them with the characters of the actual
// given plural suffix // given plural suffix
foreach (self::$pluralMap as $map) { foreach (self::PLURAL_MAP as $map) {
$suffix = $map[0]; $suffix = $map[0];
$suffixLength = $map[1]; $suffixLength = $map[1];
$j = 0; $j = 0;
@ -432,7 +432,7 @@ final class Inflector
$singularLength = \strlen($lowerSingularRev); $singularLength = \strlen($lowerSingularRev);
// Check if the word is one which is not inflected, return early if so // Check if the word is one which is not inflected, return early if so
if (\in_array($lowerSingularRev, self::$uninflected, true)) { if (\in_array($lowerSingularRev, self::UNINFLECTED, true)) {
return $singular; return $singular;
} }
@ -440,7 +440,7 @@ final class Inflector
// The inner loop $j iterates over the characters of the singular suffix // The inner loop $j iterates over the characters of the singular suffix
// in the singular table to compare them with the characters of the actual // in the singular table to compare them with the characters of the actual
// given singular suffix // given singular suffix
foreach (self::$singularMap as $map) { foreach (self::SINGULAR_MAP as $map) {
$suffix = $map[0]; $suffix = $map[0];
$suffixLength = $map[1]; $suffixLength = $map[1];
$j = 0; $j = 0;

View File

@ -25,7 +25,7 @@ use Symfony\Component\Intl\Data\Util\LocaleScanner;
*/ */
class CurrencyDataGenerator extends AbstractDataGenerator class CurrencyDataGenerator extends AbstractDataGenerator
{ {
private static $denylist = [ private const DENYLIST = [
'XBA' => true, // European Composite Unit 'XBA' => true, // European Composite Unit
'XBB' => true, // European Monetary Unit 'XBB' => true, // European Monetary Unit
'XBC' => true, // European Unit of Account (XBC) 'XBC' => true, // European Unit of Account (XBC)
@ -133,7 +133,7 @@ class CurrencyDataGenerator extends AbstractDataGenerator
$symbolNamePairs = iterator_to_array($rootBundle['Currencies']); $symbolNamePairs = iterator_to_array($rootBundle['Currencies']);
// Remove unwanted currencies // Remove unwanted currencies
$symbolNamePairs = array_diff_key($symbolNamePairs, self::$denylist); $symbolNamePairs = array_diff_key($symbolNamePairs, self::DENYLIST);
return $symbolNamePairs; return $symbolNamePairs;
} }

View File

@ -29,7 +29,7 @@ class LanguageDataGenerator extends AbstractDataGenerator
/** /**
* Source: https://iso639-3.sil.org/code_tables/639/data. * Source: https://iso639-3.sil.org/code_tables/639/data.
*/ */
private static $preferredAlpha2ToAlpha3Mapping = [ private const PREFERRED_ALPHA2_TO_ALPHA3_MAPPING = [
'ak' => 'aka', 'ak' => 'aka',
'ar' => 'ara', 'ar' => 'ara',
'ay' => 'aym', 'ay' => 'aym',
@ -83,7 +83,7 @@ class LanguageDataGenerator extends AbstractDataGenerator
'za' => 'zha', 'za' => 'zha',
'zh' => 'zho', 'zh' => 'zho',
]; ];
private static $denylist = [ private const DENYLIST = [
'root' => true, // Absolute root language 'root' => true, // Absolute root language
'mul' => true, // Multiple languages 'mul' => true, // Multiple languages
'mis' => true, // Uncoded language 'mis' => true, // Uncoded language
@ -182,7 +182,7 @@ class LanguageDataGenerator extends AbstractDataGenerator
private static function generateLanguageNames(ArrayAccessibleResourceBundle $localeBundle): array private static function generateLanguageNames(ArrayAccessibleResourceBundle $localeBundle): array
{ {
return array_diff_key(iterator_to_array($localeBundle['Languages']), self::$denylist); return array_diff_key(iterator_to_array($localeBundle['Languages']), self::DENYLIST);
} }
private function generateAlpha3Codes(array $languageCodes, ArrayAccessibleResourceBundle $metadataBundle): array private function generateAlpha3Codes(array $languageCodes, ArrayAccessibleResourceBundle $metadataBundle): array
@ -210,13 +210,13 @@ class LanguageDataGenerator extends AbstractDataGenerator
foreach ($aliases as $alias => $data) { foreach ($aliases as $alias => $data) {
$language = $data['replacement']; $language = $data['replacement'];
if (2 === \strlen($language) && 3 === \strlen($alias) && 'overlong' === $data['reason']) { if (2 === \strlen($language) && 3 === \strlen($alias) && 'overlong' === $data['reason']) {
if (isset(self::$preferredAlpha2ToAlpha3Mapping[$language])) { if (isset(self::PREFERRED_ALPHA2_TO_ALPHA3_MAPPING[$language])) {
// Validate to prevent typos // Validate to prevent typos
if (!isset($aliases[self::$preferredAlpha2ToAlpha3Mapping[$language]])) { if (!isset($aliases[self::PREFERRED_ALPHA2_TO_ALPHA3_MAPPING[$language]])) {
throw new RuntimeException('The statically set three-letter mapping '.self::$preferredAlpha2ToAlpha3Mapping[$language].' for the language code '.$language.' seems to be invalid. Typo?'); throw new RuntimeException('The statically set three-letter mapping '.self::PREFERRED_ALPHA2_TO_ALPHA3_MAPPING[$language].' for the language code '.$language.' seems to be invalid. Typo?');
} }
$alpha3 = self::$preferredAlpha2ToAlpha3Mapping[$language]; $alpha3 = self::PREFERRED_ALPHA2_TO_ALPHA3_MAPPING[$language];
$alpha2 = $aliases[$alpha3]['replacement']; $alpha2 = $aliases[$alpha3]['replacement'];
if ($language !== $alpha2) { if ($language !== $alpha2) {
@ -225,7 +225,7 @@ class LanguageDataGenerator extends AbstractDataGenerator
$alpha2ToAlpha3[$language] = $alpha3; $alpha2ToAlpha3[$language] = $alpha3;
} elseif (isset($alpha2ToAlpha3[$language])) { } elseif (isset($alpha2ToAlpha3[$language])) {
throw new RuntimeException('Multiple three-letter mappings exist for the language code '.$language.'. Please add one of them to the property $preferredAlpha2ToAlpha3Mapping.'); throw new RuntimeException('Multiple three-letter mappings exist for the language code '.$language.'. Please add one of them to the const PREFERRED_ALPHA2_TO_ALPHA3_MAPPING.');
} else { } else {
$alpha2ToAlpha3[$language] = $alias; $alpha2ToAlpha3[$language] = $alias;
} }

View File

@ -31,7 +31,7 @@ class RegionDataGenerator extends AbstractDataGenerator
/** /**
* Source: https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes. * Source: https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes.
*/ */
private static $preferredAlpha2ToAlpha3Mapping = [ private const PREFERRED_ALPHA2_TO_ALPHA3_MAPPING = [
'CD' => 'COD', 'CD' => 'COD',
'DE' => 'DEU', 'DE' => 'DEU',
'FR' => 'FRA', 'FR' => 'FRA',
@ -40,7 +40,7 @@ class RegionDataGenerator extends AbstractDataGenerator
'YE' => 'YEM', 'YE' => 'YEM',
]; ];
private static $denylist = [ private const DENYLIST = [
// Exceptional reservations // Exceptional reservations
'AC' => true, // Ascension Island 'AC' => true, // Ascension Island
'CP' => true, // Clipperton Island 'CP' => true, // Clipperton Island
@ -69,7 +69,7 @@ class RegionDataGenerator extends AbstractDataGenerator
public static function isValidCountryCode($region) public static function isValidCountryCode($region)
{ {
if (isset(self::$denylist[$region])) { if (isset(self::DENYLIST[$region])) {
return false; return false;
} }
@ -181,13 +181,13 @@ class RegionDataGenerator extends AbstractDataGenerator
foreach ($aliases as $alias => $data) { foreach ($aliases as $alias => $data) {
$country = $data['replacement']; $country = $data['replacement'];
if (2 === \strlen($country) && 3 === \strlen($alias) && 'overlong' === $data['reason']) { if (2 === \strlen($country) && 3 === \strlen($alias) && 'overlong' === $data['reason']) {
if (isset(self::$preferredAlpha2ToAlpha3Mapping[$country])) { if (isset(self::PREFERRED_ALPHA2_TO_ALPHA3_MAPPING[$country])) {
// Validate to prevent typos // Validate to prevent typos
if (!isset($aliases[self::$preferredAlpha2ToAlpha3Mapping[$country]])) { if (!isset($aliases[self::PREFERRED_ALPHA2_TO_ALPHA3_MAPPING[$country]])) {
throw new RuntimeException('The statically set three-letter mapping '.self::$preferredAlpha2ToAlpha3Mapping[$country].' for the country code '.$country.' seems to be invalid. Typo?'); throw new RuntimeException('The statically set three-letter mapping '.self::PREFERRED_ALPHA2_TO_ALPHA3_MAPPING[$country].' for the country code '.$country.' seems to be invalid. Typo?');
} }
$alpha3 = self::$preferredAlpha2ToAlpha3Mapping[$country]; $alpha3 = self::PREFERRED_ALPHA2_TO_ALPHA3_MAPPING[$country];
$alpha2 = $aliases[$alpha3]['replacement']; $alpha2 = $aliases[$alpha3]['replacement'];
if ($country !== $alpha2) { if ($country !== $alpha2) {
@ -196,7 +196,7 @@ class RegionDataGenerator extends AbstractDataGenerator
$alpha2ToAlpha3[$country] = $alpha3; $alpha2ToAlpha3[$country] = $alpha3;
} elseif (isset($alpha2ToAlpha3[$country])) { } elseif (isset($alpha2ToAlpha3[$country])) {
throw new RuntimeException('Multiple three-letter mappings exist for the country code '.$country.'. Please add one of them to the property $preferredAlpha2ToAlpha3Mapping.'); throw new RuntimeException('Multiple three-letter mappings exist for the country code '.$country.'. Please add one of them to the const PREFERRED_ALPHA2_TO_ALPHA3_MAPPING.');
} elseif (isset($countries[$country]) && self::isValidCountryCode($alias)) { } elseif (isset($countries[$country]) && self::isValidCountryCode($alias)) {
$alpha2ToAlpha3[$country] = $alias; $alpha2ToAlpha3[$country] = $alias;
} }

View File

@ -24,7 +24,7 @@ use Symfony\Component\Intl\Data\Util\LocaleScanner;
*/ */
class ScriptDataGenerator extends AbstractDataGenerator class ScriptDataGenerator extends AbstractDataGenerator
{ {
private static $denylist = [ private const DENYLIST = [
'Zzzz' => true, // Unknown Script 'Zzzz' => true, // Unknown Script
]; ];
@ -69,7 +69,7 @@ class ScriptDataGenerator extends AbstractDataGenerator
// isset() on \ResourceBundle returns true even if the value is null // isset() on \ResourceBundle returns true even if the value is null
if (isset($localeBundle['Scripts']) && null !== $localeBundle['Scripts']) { if (isset($localeBundle['Scripts']) && null !== $localeBundle['Scripts']) {
$data = [ $data = [
'Names' => array_diff_key(iterator_to_array($localeBundle['Scripts']), self::$denylist), 'Names' => array_diff_key(iterator_to_array($localeBundle['Scripts']), self::DENYLIST),
]; ];
$this->scriptCodes = array_merge($this->scriptCodes, array_keys($data['Names'])); $this->scriptCodes = array_merge($this->scriptCodes, array_keys($data['Names']));

View File

@ -38,7 +38,7 @@ abstract class IntlGlobals
/** /**
* All known error codes. * All known error codes.
*/ */
private static $errorCodes = [ private const ERROR_CODES = [
self::U_ZERO_ERROR => 'U_ZERO_ERROR', self::U_ZERO_ERROR => 'U_ZERO_ERROR',
self::U_ILLEGAL_ARGUMENT_ERROR => 'U_ILLEGAL_ARGUMENT_ERROR', self::U_ILLEGAL_ARGUMENT_ERROR => 'U_ILLEGAL_ARGUMENT_ERROR',
self::U_PARSE_ERROR => 'U_PARSE_ERROR', self::U_PARSE_ERROR => 'U_PARSE_ERROR',
@ -61,7 +61,7 @@ abstract class IntlGlobals
*/ */
public static function isFailure(int $errorCode): bool public static function isFailure(int $errorCode): bool
{ {
return isset(self::$errorCodes[$errorCode]) return isset(self::ERROR_CODES[$errorCode])
&& $errorCode > self::U_ZERO_ERROR; && $errorCode > self::U_ZERO_ERROR;
} }
@ -94,7 +94,7 @@ abstract class IntlGlobals
*/ */
public static function getErrorName(int $code): string public static function getErrorName(int $code): string
{ {
return self::$errorCodes[$code] ?? '[BOGUS UErrorCode]'; return self::ERROR_CODES[$code] ?? '[BOGUS UErrorCode]';
} }
/** /**
@ -107,11 +107,11 @@ abstract class IntlGlobals
*/ */
public static function setError(int $code, string $message = '') public static function setError(int $code, string $message = '')
{ {
if (!isset(self::$errorCodes[$code])) { if (!isset(self::ERROR_CODES[$code])) {
throw new \InvalidArgumentException(sprintf('No such error code: "%s".', $code)); throw new \InvalidArgumentException(sprintf('No such error code: "%s".', $code));
} }
self::$errorMessage = $message ? sprintf('%s: %s', $message, self::$errorCodes[$code]) : self::$errorCodes[$code]; self::$errorMessage = $message ? sprintf('%s: %s', $message, self::ERROR_CODES[$code]) : self::ERROR_CODES[$code];
self::$errorCode = $code; self::$errorCode = $code;
} }
} }

View File

@ -165,7 +165,7 @@ abstract class NumberFormatter
/** /**
* The supported styles to the constructor $styles argument. * The supported styles to the constructor $styles argument.
*/ */
private static $supportedStyles = [ private const SUPPORTED_STYLES = [
'CURRENCY' => self::CURRENCY, 'CURRENCY' => self::CURRENCY,
'DECIMAL' => self::DECIMAL, 'DECIMAL' => self::DECIMAL,
]; ];
@ -173,7 +173,7 @@ abstract class NumberFormatter
/** /**
* Supported attributes to the setAttribute() $attr argument. * Supported attributes to the setAttribute() $attr argument.
*/ */
private static $supportedAttributes = [ private const SUPPORTED_ATTRIBUTES = [
'FRACTION_DIGITS' => self::FRACTION_DIGITS, 'FRACTION_DIGITS' => self::FRACTION_DIGITS,
'GROUPING_USED' => self::GROUPING_USED, 'GROUPING_USED' => self::GROUPING_USED,
'ROUNDING_MODE' => self::ROUNDING_MODE, 'ROUNDING_MODE' => self::ROUNDING_MODE,
@ -184,7 +184,7 @@ abstract class NumberFormatter
* NumberFormatter::ROUNDING_MODE. NumberFormatter::ROUND_DOWN * NumberFormatter::ROUNDING_MODE. NumberFormatter::ROUND_DOWN
* and NumberFormatter::ROUND_UP does not have a PHP only equivalent. * and NumberFormatter::ROUND_UP does not have a PHP only equivalent.
*/ */
private static $roundingModes = [ private const ROUNDING_MODES = [
'ROUND_HALFEVEN' => self::ROUND_HALFEVEN, 'ROUND_HALFEVEN' => self::ROUND_HALFEVEN,
'ROUND_HALFDOWN' => self::ROUND_HALFDOWN, 'ROUND_HALFDOWN' => self::ROUND_HALFDOWN,
'ROUND_HALFUP' => self::ROUND_HALFUP, 'ROUND_HALFUP' => self::ROUND_HALFUP,
@ -200,7 +200,7 @@ abstract class NumberFormatter
* *
* @see https://php.net/round * @see https://php.net/round
*/ */
private static $phpRoundingMap = [ private const PHP_ROUNDING_MAP = [
self::ROUND_HALFDOWN => \PHP_ROUND_HALF_DOWN, self::ROUND_HALFDOWN => \PHP_ROUND_HALF_DOWN,
self::ROUND_HALFEVEN => \PHP_ROUND_HALF_EVEN, self::ROUND_HALFEVEN => \PHP_ROUND_HALF_EVEN,
self::ROUND_HALFUP => \PHP_ROUND_HALF_UP, self::ROUND_HALFUP => \PHP_ROUND_HALF_UP,
@ -211,7 +211,7 @@ abstract class NumberFormatter
* PHP's round() function, but there's an equivalent. Keys are rounding * PHP's round() function, but there's an equivalent. Keys are rounding
* modes, values does not matter. * modes, values does not matter.
*/ */
private static $customRoundingList = [ private const CUSTOM_ROUNDING_LIST = [
self::ROUND_CEILING => true, self::ROUND_CEILING => true,
self::ROUND_FLOOR => true, self::ROUND_FLOOR => true,
self::ROUND_DOWN => true, self::ROUND_DOWN => true,
@ -230,12 +230,12 @@ abstract class NumberFormatter
*/ */
private static $int64Max = 9223372036854775807; private static $int64Max = 9223372036854775807;
private static $enSymbols = [ private const EN_SYMBOLS = [
self::DECIMAL => ['.', ',', ';', '%', '0', '#', '-', '+', '¤', '¤¤', '.', 'E', '‰', '*', '∞', 'NaN', '@', ','], self::DECIMAL => ['.', ',', ';', '%', '0', '#', '-', '+', '¤', '¤¤', '.', 'E', '‰', '*', '∞', 'NaN', '@', ','],
self::CURRENCY => ['.', ',', ';', '%', '0', '#', '-', '+', '¤', '¤¤', '.', 'E', '‰', '*', '∞', 'NaN', '@', ','], self::CURRENCY => ['.', ',', ';', '%', '0', '#', '-', '+', '¤', '¤¤', '.', 'E', '‰', '*', '∞', 'NaN', '@', ','],
]; ];
private static $enTextAttributes = [ private const EN_TEXT_ATTRIBUTES = [
self::DECIMAL => ['', '', '-', '', ' ', 'XXX', ''], self::DECIMAL => ['', '', '-', '', ' ', 'XXX', ''],
self::CURRENCY => ['¤', '', '-¤', '', ' ', 'XXX'], self::CURRENCY => ['¤', '', '-¤', '', ' ', 'XXX'],
]; ];
@ -263,8 +263,8 @@ abstract class NumberFormatter
throw new MethodArgumentValueNotImplementedException(__METHOD__, 'locale', $locale, 'Only the locale "en" is supported'); throw new MethodArgumentValueNotImplementedException(__METHOD__, 'locale', $locale, 'Only the locale "en" is supported');
} }
if (!\in_array($style, self::$supportedStyles)) { if (!\in_array($style, self::SUPPORTED_STYLES)) {
$message = sprintf('The available styles are: %s.', implode(', ', array_keys(self::$supportedStyles))); $message = sprintf('The available styles are: %s.', implode(', ', array_keys(self::SUPPORTED_STYLES)));
throw new MethodArgumentValueNotImplementedException(__METHOD__, 'style', $style, $message); throw new MethodArgumentValueNotImplementedException(__METHOD__, 'style', $style, $message);
} }
@ -466,7 +466,7 @@ abstract class NumberFormatter
*/ */
public function getSymbol($attr) public function getSymbol($attr)
{ {
return \array_key_exists($this->style, self::$enSymbols) && \array_key_exists($attr, self::$enSymbols[$this->style]) ? self::$enSymbols[$this->style][$attr] : false; return \array_key_exists($this->style, self::EN_SYMBOLS) && \array_key_exists($attr, self::EN_SYMBOLS[$this->style]) ? self::EN_SYMBOLS[$this->style][$attr] : false;
} }
/** /**
@ -480,7 +480,7 @@ abstract class NumberFormatter
*/ */
public function getTextAttribute($attr) public function getTextAttribute($attr)
{ {
return \array_key_exists($this->style, self::$enTextAttributes) && \array_key_exists($attr, self::$enTextAttributes[$this->style]) ? self::$enTextAttributes[$this->style][$attr] : false; return \array_key_exists($this->style, self::EN_TEXT_ATTRIBUTES) && \array_key_exists($attr, self::EN_TEXT_ATTRIBUTES[$this->style]) ? self::EN_TEXT_ATTRIBUTES[$this->style][$attr] : false;
} }
/** /**
@ -579,29 +579,29 @@ abstract class NumberFormatter
{ {
$attr = (int) $attr; $attr = (int) $attr;
if (!\in_array($attr, self::$supportedAttributes)) { if (!\in_array($attr, self::SUPPORTED_ATTRIBUTES)) {
$message = sprintf( $message = sprintf(
'The available attributes are: %s', 'The available attributes are: %s',
implode(', ', array_keys(self::$supportedAttributes)) implode(', ', array_keys(self::SUPPORTED_ATTRIBUTES))
); );
throw new MethodArgumentValueNotImplementedException(__METHOD__, 'attr', $value, $message); throw new MethodArgumentValueNotImplementedException(__METHOD__, 'attr', $value, $message);
} }
if (self::$supportedAttributes['ROUNDING_MODE'] === $attr && $this->isInvalidRoundingMode($value)) { if (self::SUPPORTED_ATTRIBUTES['ROUNDING_MODE'] === $attr && $this->isInvalidRoundingMode($value)) {
$message = sprintf( $message = sprintf(
'The supported values for ROUNDING_MODE are: %s', 'The supported values for ROUNDING_MODE are: %s',
implode(', ', array_keys(self::$roundingModes)) implode(', ', array_keys(self::ROUNDING_MODES))
); );
throw new MethodArgumentValueNotImplementedException(__METHOD__, 'attr', $value, $message); throw new MethodArgumentValueNotImplementedException(__METHOD__, 'attr', $value, $message);
} }
if (self::$supportedAttributes['GROUPING_USED'] === $attr) { if (self::SUPPORTED_ATTRIBUTES['GROUPING_USED'] === $attr) {
$value = $this->normalizeGroupingUsedValue($value); $value = $this->normalizeGroupingUsedValue($value);
} }
if (self::$supportedAttributes['FRACTION_DIGITS'] === $attr) { if (self::SUPPORTED_ATTRIBUTES['FRACTION_DIGITS'] === $attr) {
$value = $this->normalizeFractionDigitsValue($value); $value = $this->normalizeFractionDigitsValue($value);
if ($value < 0) { if ($value < 0) {
// ignore negative values but do not raise an error // ignore negative values but do not raise an error
@ -718,9 +718,9 @@ abstract class NumberFormatter
$precision = $this->getUninitializedPrecision($value, $precision); $precision = $this->getUninitializedPrecision($value, $precision);
$roundingModeAttribute = $this->getAttribute(self::ROUNDING_MODE); $roundingModeAttribute = $this->getAttribute(self::ROUNDING_MODE);
if (isset(self::$phpRoundingMap[$roundingModeAttribute])) { if (isset(self::PHP_ROUNDING_MAP[$roundingModeAttribute])) {
$value = round($value, $precision, self::$phpRoundingMap[$roundingModeAttribute]); $value = round($value, $precision, self::PHP_ROUNDING_MAP[$roundingModeAttribute]);
} elseif (isset(self::$customRoundingList[$roundingModeAttribute])) { } elseif (isset(self::CUSTOM_ROUNDING_LIST[$roundingModeAttribute])) {
$roundingCoef = 10 ** $precision; $roundingCoef = 10 ** $precision;
$value *= $roundingCoef; $value *= $roundingCoef;
$value = (float) (string) $value; $value = (float) (string) $value;
@ -846,7 +846,7 @@ abstract class NumberFormatter
*/ */
private function isInvalidRoundingMode(int $value): bool private function isInvalidRoundingMode(int $value): bool
{ {
if (\in_array($value, self::$roundingModes, true)) { if (\in_array($value, self::ROUNDING_MODES, true)) {
return false; return false;
} }

View File

@ -21,7 +21,7 @@ class CountriesTest extends ResourceBundleTestCase
{ {
// The below arrays document the state of the ICU data bundled with this package. // The below arrays document the state of the ICU data bundled with this package.
private static $countries = [ private const COUNTRIES = [
'AD', 'AD',
'AE', 'AE',
'AF', 'AF',
@ -273,7 +273,7 @@ class CountriesTest extends ResourceBundleTestCase
'ZW', 'ZW',
]; ];
private static $alpha2ToAlpha3 = [ private const ALPHA2_TO_ALPHA3 = [
'AW' => 'ABW', 'AW' => 'ABW',
'AF' => 'AFG', 'AF' => 'AFG',
'AO' => 'AGO', 'AO' => 'AGO',
@ -527,7 +527,7 @@ class CountriesTest extends ResourceBundleTestCase
public function testGetCountryCodes() public function testGetCountryCodes()
{ {
$this->assertSame(self::$countries, Countries::getCountryCodes()); $this->assertSame(self::COUNTRIES, Countries::getCountryCodes());
} }
/** /**
@ -539,7 +539,7 @@ class CountriesTest extends ResourceBundleTestCase
sort($countries); sort($countries);
$this->assertSame(self::$countries, $countries); $this->assertSame(self::COUNTRIES, $countries);
} }
public function testGetNamesDefaultLocale() public function testGetNamesDefaultLocale()
@ -604,20 +604,20 @@ class CountriesTest extends ResourceBundleTestCase
public function testGetAlpha3Codes() public function testGetAlpha3Codes()
{ {
$this->assertSame(self::$alpha2ToAlpha3, Countries::getAlpha3Codes()); $this->assertSame(self::ALPHA2_TO_ALPHA3, Countries::getAlpha3Codes());
} }
public function testGetAlpha3Code() public function testGetAlpha3Code()
{ {
foreach (self::$countries as $country) { foreach (self::COUNTRIES as $country) {
$this->assertSame(self::$alpha2ToAlpha3[$country], Countries::getAlpha3Code($country)); $this->assertSame(self::ALPHA2_TO_ALPHA3[$country], Countries::getAlpha3Code($country));
} }
} }
public function testGetAlpha2Code() public function testGetAlpha2Code()
{ {
foreach (self::$countries as $alpha2Code) { foreach (self::COUNTRIES as $alpha2Code) {
$alpha3Code = self::$alpha2ToAlpha3[$alpha2Code]; $alpha3Code = self::ALPHA2_TO_ALPHA3[$alpha2Code];
$this->assertSame($alpha2Code, Countries::getAlpha2Code($alpha3Code)); $this->assertSame($alpha2Code, Countries::getAlpha2Code($alpha3Code));
} }
} }
@ -639,7 +639,7 @@ class CountriesTest extends ResourceBundleTestCase
$names = Countries::getNames($displayLocale); $names = Countries::getNames($displayLocale);
foreach ($names as $alpha2 => $name) { foreach ($names as $alpha2 => $name) {
$alpha3 = self::$alpha2ToAlpha3[$alpha2]; $alpha3 = self::ALPHA2_TO_ALPHA3[$alpha2];
$this->assertSame($name, Countries::getAlpha3Name($alpha3, $displayLocale)); $this->assertSame($name, Countries::getAlpha3Name($alpha3, $displayLocale));
} }
} }
@ -660,7 +660,7 @@ class CountriesTest extends ResourceBundleTestCase
$alpha3Codes = array_keys($names); $alpha3Codes = array_keys($names);
sort($alpha3Codes); sort($alpha3Codes);
$this->assertSame(array_values(self::$alpha2ToAlpha3), $alpha3Codes); $this->assertSame(array_values(self::ALPHA2_TO_ALPHA3), $alpha3Codes);
$alpha2Names = Countries::getNames($displayLocale); $alpha2Names = Countries::getNames($displayLocale);
$this->assertSame(array_values($alpha2Names), array_values($names)); $this->assertSame(array_values($alpha2Names), array_values($names));

View File

@ -20,7 +20,7 @@ class CurrenciesTest extends ResourceBundleTestCase
{ {
// The below arrays document the state of the ICU data bundled with this package. // The below arrays document the state of the ICU data bundled with this package.
private static $currencies = [ private const CURRENCIES = [
'ADP', 'ADP',
'AED', 'AED',
'AFA', 'AFA',
@ -313,7 +313,7 @@ class CurrenciesTest extends ResourceBundleTestCase
'ZWR', 'ZWR',
]; ];
private static $alpha3ToNumeric = [ private const ALPHA3_TO_NUMERIC = [
'AFA' => 4, 'AFA' => 4,
'ALK' => 8, 'ALK' => 8,
'ALL' => 8, 'ALL' => 8,
@ -586,7 +586,7 @@ class CurrenciesTest extends ResourceBundleTestCase
public function testGetCurrencyCodes() public function testGetCurrencyCodes()
{ {
$this->assertSame(self::$currencies, Currencies::getCurrencyCodes()); $this->assertSame(self::CURRENCIES, Currencies::getCurrencyCodes());
} }
/** /**
@ -600,7 +600,7 @@ class CurrenciesTest extends ResourceBundleTestCase
sort($keys); sort($keys);
$this->assertSame(self::$currencies, $keys); $this->assertSame(self::CURRENCIES, $keys);
// Names should be sorted // Names should be sorted
$sortedNames = $names; $sortedNames = $names;
@ -673,7 +673,7 @@ class CurrenciesTest extends ResourceBundleTestCase
{ {
return array_map( return array_map(
function ($currency) { return [$currency]; }, function ($currency) { return [$currency]; },
self::$currencies self::CURRENCIES
); );
} }
@ -700,7 +700,7 @@ class CurrenciesTest extends ResourceBundleTestCase
{ {
return array_map( return array_map(
function ($value) { return [$value]; }, function ($value) { return [$value]; },
array_keys(self::$alpha3ToNumeric) array_keys(self::ALPHA3_TO_NUMERIC)
); );
} }
@ -709,14 +709,14 @@ class CurrenciesTest extends ResourceBundleTestCase
*/ */
public function testGetNumericCode($currency) public function testGetNumericCode($currency)
{ {
$this->assertSame(self::$alpha3ToNumeric[$currency], Currencies::getNumericCode($currency)); $this->assertSame(self::ALPHA3_TO_NUMERIC[$currency], Currencies::getNumericCode($currency));
} }
public function provideCurrenciesWithoutNumericEquivalent() public function provideCurrenciesWithoutNumericEquivalent()
{ {
return array_map( return array_map(
function ($value) { return [$value]; }, function ($value) { return [$value]; },
array_diff(self::$currencies, array_keys(self::$alpha3ToNumeric)) array_diff(self::CURRENCIES, array_keys(self::ALPHA3_TO_NUMERIC))
); );
} }
@ -790,7 +790,7 @@ class CurrenciesTest extends ResourceBundleTestCase
{ {
$numericToAlpha3 = []; $numericToAlpha3 = [];
foreach (self::$alpha3ToNumeric as $alpha3 => $numeric) { foreach (self::ALPHA3_TO_NUMERIC as $alpha3 => $numeric) {
if (!isset($numericToAlpha3[$numeric])) { if (!isset($numericToAlpha3[$numeric])) {
$numericToAlpha3[$numeric] = []; $numericToAlpha3[$numeric] = [];
} }

View File

@ -33,7 +33,7 @@ class BundleEntryReaderTest extends TestCase
*/ */
private $readerImpl; private $readerImpl;
private static $data = [ private const DATA = [
'Entries' => [ 'Entries' => [
'Foo' => 'Bar', 'Foo' => 'Bar',
'Bar' => 'Baz', 'Bar' => 'Baz',
@ -42,7 +42,7 @@ class BundleEntryReaderTest extends TestCase
'Version' => '2.0', 'Version' => '2.0',
]; ];
private static $fallbackData = [ private const FALLBACK_DATA = [
'Entries' => [ 'Entries' => [
'Foo' => 'Foo', 'Foo' => 'Foo',
'Bam' => 'Lah', 'Bam' => 'Lah',
@ -51,7 +51,7 @@ class BundleEntryReaderTest extends TestCase
'Version' => '1.0', 'Version' => '1.0',
]; ];
private static $mergedData = [ private const MERGED_DATA = [
// no recursive merging -> too complicated // no recursive merging -> too complicated
'Entries' => [ 'Entries' => [
'Foo' => 'Bar', 'Foo' => 'Bar',
@ -73,9 +73,9 @@ class BundleEntryReaderTest extends TestCase
$this->readerImpl->expects($this->once()) $this->readerImpl->expects($this->once())
->method('read') ->method('read')
->with(self::RES_DIR, 'root') ->with(self::RES_DIR, 'root')
->willReturn(self::$data); ->willReturn(self::DATA);
$this->assertSame(self::$data, $this->reader->read(self::RES_DIR, 'root')); $this->assertSame(self::DATA, $this->reader->read(self::RES_DIR, 'root'));
} }
public function testReadEntireDataFileIfNoIndicesGiven() public function testReadEntireDataFileIfNoIndicesGiven()
@ -86,9 +86,9 @@ class BundleEntryReaderTest extends TestCase
[self::RES_DIR, 'en'], [self::RES_DIR, 'en'],
[self::RES_DIR, 'root'] [self::RES_DIR, 'root']
) )
->willReturnOnConsecutiveCalls(self::$data, self::$fallbackData); ->willReturnOnConsecutiveCalls(self::DATA, self::FALLBACK_DATA);
$this->assertSame(self::$mergedData, $this->reader->readEntry(self::RES_DIR, 'en', [])); $this->assertSame(self::MERGED_DATA, $this->reader->readEntry(self::RES_DIR, 'en', []));
} }
public function testReadExistingEntry() public function testReadExistingEntry()
@ -96,7 +96,7 @@ class BundleEntryReaderTest extends TestCase
$this->readerImpl->expects($this->once()) $this->readerImpl->expects($this->once())
->method('read') ->method('read')
->with(self::RES_DIR, 'root') ->with(self::RES_DIR, 'root')
->willReturn(self::$data); ->willReturn(self::DATA);
$this->assertSame('Bar', $this->reader->readEntry(self::RES_DIR, 'root', ['Entries', 'Foo'])); $this->assertSame('Bar', $this->reader->readEntry(self::RES_DIR, 'root', ['Entries', 'Foo']));
} }
@ -107,7 +107,7 @@ class BundleEntryReaderTest extends TestCase
$this->readerImpl->expects($this->once()) $this->readerImpl->expects($this->once())
->method('read') ->method('read')
->with(self::RES_DIR, 'root') ->with(self::RES_DIR, 'root')
->willReturn(self::$data); ->willReturn(self::DATA);
$this->reader->readEntry(self::RES_DIR, 'root', ['Entries', 'NonExisting']); $this->reader->readEntry(self::RES_DIR, 'root', ['Entries', 'NonExisting']);
} }
@ -120,7 +120,7 @@ class BundleEntryReaderTest extends TestCase
[self::RES_DIR, 'en_GB'], [self::RES_DIR, 'en_GB'],
[self::RES_DIR, 'en'] [self::RES_DIR, 'en']
) )
->willReturnOnConsecutiveCalls(self::$data, self::$fallbackData); ->willReturnOnConsecutiveCalls(self::DATA, self::FALLBACK_DATA);
$this->assertSame('Lah', $this->reader->readEntry(self::RES_DIR, 'en_GB', ['Entries', 'Bam'])); $this->assertSame('Lah', $this->reader->readEntry(self::RES_DIR, 'en_GB', ['Entries', 'Bam']));
} }
@ -131,7 +131,7 @@ class BundleEntryReaderTest extends TestCase
$this->readerImpl->expects($this->once()) $this->readerImpl->expects($this->once())
->method('read') ->method('read')
->with(self::RES_DIR, 'en_GB') ->with(self::RES_DIR, 'en_GB')
->willReturn(self::$data); ->willReturn(self::DATA);
$this->reader->readEntry(self::RES_DIR, 'en_GB', ['Entries', 'Bam'], false); $this->reader->readEntry(self::RES_DIR, 'en_GB', ['Entries', 'Bam'], false);
} }
@ -146,7 +146,7 @@ class BundleEntryReaderTest extends TestCase
) )
->willReturnOnConsecutiveCalls( ->willReturnOnConsecutiveCalls(
$this->throwException(new ResourceBundleNotFoundException()), $this->throwException(new ResourceBundleNotFoundException()),
self::$fallbackData self::FALLBACK_DATA
); );
$this->assertSame('Lah', $this->reader->readEntry(self::RES_DIR, 'en_GB', ['Entries', 'Bam'])); $this->assertSame('Lah', $this->reader->readEntry(self::RES_DIR, 'en_GB', ['Entries', 'Bam']));

View File

@ -28,7 +28,7 @@ abstract class AbstractDataProviderTest extends TestCase
// not loaded, because it is NOT possible to skip the execution of data // not loaded, because it is NOT possible to skip the execution of data
// providers. // providers.
private static $locales = [ private const LOCALES = [
'af', 'af',
'af_NA', 'af_NA',
'af_ZA', 'af_ZA',
@ -684,7 +684,7 @@ abstract class AbstractDataProviderTest extends TestCase
'zu_ZA', 'zu_ZA',
]; ];
private static $localeAliases = [ private const LOCALE_ALIASES = [
'az_AZ' => 'az_Latn_AZ', 'az_AZ' => 'az_Latn_AZ',
'bs_BA' => 'bs_Latn_BA', 'bs_BA' => 'bs_Latn_BA',
'en_NH' => 'en_VU', 'en_NH' => 'en_VU',
@ -766,12 +766,12 @@ abstract class AbstractDataProviderTest extends TestCase
protected function getLocales() protected function getLocales()
{ {
return self::$locales; return self::LOCALES;
} }
protected function getLocaleAliases() protected function getLocaleAliases()
{ {
return self::$localeAliases; return self::LOCALE_ALIASES;
} }
protected function getRootLocales() protected function getRootLocales()

View File

@ -21,7 +21,7 @@ class LanguagesTest extends ResourceBundleTestCase
{ {
// The below arrays document the state of the ICU data bundled with this package. // The below arrays document the state of the ICU data bundled with this package.
private static $languages = [ private const LANGUAGES = [
'aa', 'aa',
'ab', 'ab',
'ace', 'ace',
@ -618,7 +618,7 @@ class LanguagesTest extends ResourceBundleTestCase
'zza', 'zza',
]; ];
private static $alpha3Codes = [ private const ALPHA3_CODES = [
'aar', 'aar',
'abk', 'abk',
'ace', 'ace',
@ -1219,7 +1219,7 @@ class LanguagesTest extends ResourceBundleTestCase
'zza', 'zza',
]; ];
private static $alpha2ToAlpha3 = [ private const ALPHA2_TO_ALPHA3 = [
'aa' => 'aar', 'aa' => 'aar',
'ab' => 'abk', 'ab' => 'abk',
'af' => 'afr', 'af' => 'afr',
@ -1402,7 +1402,7 @@ class LanguagesTest extends ResourceBundleTestCase
'zu' => 'zul', 'zu' => 'zul',
]; ];
private static $alpha3ToAlpha2 = [ private const ALPHA3_TO_ALPHA2 = [
'aar' => 'aa', 'aar' => 'aa',
'abk' => 'ab', 'abk' => 'ab',
'ave' => 'ae', 'ave' => 'ae',
@ -1590,7 +1590,7 @@ class LanguagesTest extends ResourceBundleTestCase
public function testGetLanguageCodes() public function testGetLanguageCodes()
{ {
$this->assertEquals(self::$languages, Languages::getLanguageCodes()); $this->assertEquals(self::LANGUAGES, Languages::getLanguageCodes());
} }
/** /**
@ -1603,10 +1603,10 @@ class LanguagesTest extends ResourceBundleTestCase
sort($languages); sort($languages);
$this->assertNotEmpty($languages); $this->assertNotEmpty($languages);
$this->assertEmpty(array_diff($languages, self::$languages)); $this->assertEmpty(array_diff($languages, self::LANGUAGES));
foreach (Languages::getAlpha3Names($displayLocale) as $alpha3Code => $name) { foreach (Languages::getAlpha3Names($displayLocale) as $alpha3Code => $name) {
$alpha2Code = self::$alpha3ToAlpha2[$alpha3Code] ?? null; $alpha2Code = self::ALPHA3_TO_ALPHA2[$alpha3Code] ?? null;
if (null !== $alpha2Code) { if (null !== $alpha2Code) {
$this->assertSame($name, $names[$alpha2Code]); $this->assertSame($name, $names[$alpha2Code]);
} }
@ -1665,7 +1665,7 @@ class LanguagesTest extends ResourceBundleTestCase
{ {
return array_map( return array_map(
function ($value) { return [$value]; }, function ($value) { return [$value]; },
array_keys(self::$alpha2ToAlpha3) array_keys(self::ALPHA2_TO_ALPHA3)
); );
} }
@ -1674,14 +1674,14 @@ class LanguagesTest extends ResourceBundleTestCase
*/ */
public function testGetAlpha3Code($language) public function testGetAlpha3Code($language)
{ {
$this->assertSame(self::$alpha2ToAlpha3[$language], Languages::getAlpha3Code($language)); $this->assertSame(self::ALPHA2_TO_ALPHA3[$language], Languages::getAlpha3Code($language));
} }
public function provideLanguagesWithoutAlpha3Equivalent() public function provideLanguagesWithoutAlpha3Equivalent()
{ {
return array_map( return array_map(
function ($value) { return [$value]; }, function ($value) { return [$value]; },
array_diff(self::$languages, array_keys(self::$alpha2ToAlpha3)) array_diff(self::LANGUAGES, array_keys(self::ALPHA2_TO_ALPHA3))
); );
} }
@ -1708,14 +1708,14 @@ class LanguagesTest extends ResourceBundleTestCase
public function testGetAlpha3Codes() public function testGetAlpha3Codes()
{ {
$this->assertSame(self::$alpha3Codes, Languages::getAlpha3Codes()); $this->assertSame(self::ALPHA3_CODES, Languages::getAlpha3Codes());
} }
public function provideLanguagesWithAlpha2Equivalent() public function provideLanguagesWithAlpha2Equivalent()
{ {
return array_map( return array_map(
function ($value) { return [$value]; }, function ($value) { return [$value]; },
array_keys(self::$alpha3ToAlpha2) array_keys(self::ALPHA3_TO_ALPHA2)
); );
} }
@ -1724,14 +1724,14 @@ class LanguagesTest extends ResourceBundleTestCase
*/ */
public function testGetAlpha2Code($language) public function testGetAlpha2Code($language)
{ {
$this->assertSame(self::$alpha3ToAlpha2[$language], Languages::getAlpha2Code($language)); $this->assertSame(self::ALPHA3_TO_ALPHA2[$language], Languages::getAlpha2Code($language));
} }
public function provideLanguagesWithoutAlpha2Equivalent() public function provideLanguagesWithoutAlpha2Equivalent()
{ {
return array_map( return array_map(
function ($value) { return [$value]; }, function ($value) { return [$value]; },
array_diff(self::$alpha3Codes, array_keys(self::$alpha3ToAlpha2)) array_diff(self::ALPHA3_CODES, array_keys(self::ALPHA3_TO_ALPHA2))
); );
} }
@ -1786,10 +1786,10 @@ class LanguagesTest extends ResourceBundleTestCase
sort($languages); sort($languages);
$this->assertNotEmpty($languages); $this->assertNotEmpty($languages);
$this->assertEmpty(array_diff($languages, self::$alpha3Codes)); $this->assertEmpty(array_diff($languages, self::ALPHA3_CODES));
foreach (Languages::getNames($displayLocale) as $alpha2Code => $name) { foreach (Languages::getNames($displayLocale) as $alpha2Code => $name) {
$alpha3Code = self::$alpha2ToAlpha3[$alpha2Code] ?? (3 === \strlen($alpha2Code) ? $alpha2Code : null); $alpha3Code = self::ALPHA2_TO_ALPHA3[$alpha2Code] ?? (3 === \strlen($alpha2Code) ? $alpha2Code : null);
if (null !== $alpha3Code) { if (null !== $alpha3Code) {
$this->assertSame($name, $names[$alpha3Code]); $this->assertSame($name, $names[$alpha3Code]);
} }

View File

@ -614,8 +614,7 @@ abstract class AbstractNumberFormatterTest extends TestCase
$decimalFormatter = $this->getNumberFormatter('en', NumberFormatter::DECIMAL); $decimalFormatter = $this->getNumberFormatter('en', NumberFormatter::DECIMAL);
$currencyFormatter = $this->getNumberFormatter('en', NumberFormatter::CURRENCY); $currencyFormatter = $this->getNumberFormatter('en', NumberFormatter::CURRENCY);
$r = new \ReflectionProperty(NumberFormatter::class, 'enSymbols'); $r = new \ReflectionClassConstant(NumberFormatter::class, 'EN_SYMBOLS');
$r->setAccessible(true);
$expected = $r->getValue(); $expected = $r->getValue();
for ($i = 0; $i <= 17; ++$i) { for ($i = 0; $i <= 17; ++$i) {
@ -631,8 +630,7 @@ abstract class AbstractNumberFormatterTest extends TestCase
$decimalFormatter = $this->getNumberFormatter('en', NumberFormatter::DECIMAL); $decimalFormatter = $this->getNumberFormatter('en', NumberFormatter::DECIMAL);
$currencyFormatter = $this->getNumberFormatter('en', NumberFormatter::CURRENCY); $currencyFormatter = $this->getNumberFormatter('en', NumberFormatter::CURRENCY);
$r = new \ReflectionProperty(NumberFormatter::class, 'enTextAttributes'); $r = new \ReflectionClassConstant(NumberFormatter::class, 'EN_TEXT_ATTRIBUTES');
$r->setAccessible(true);
$expected = $r->getValue(); $expected = $r->getValue();
for ($i = 0; $i <= 5; ++$i) { for ($i = 0; $i <= 5; ++$i) {

View File

@ -21,7 +21,7 @@ abstract class ResourceBundleTestCase extends TestCase
// not loaded, because it is NOT possible to skip the execution of data // not loaded, because it is NOT possible to skip the execution of data
// providers. // providers.
private static $locales = [ private const LOCALES = [
'af', 'af',
'af_NA', 'af_NA',
'af_ZA', 'af_ZA',
@ -677,7 +677,7 @@ abstract class ResourceBundleTestCase extends TestCase
'zu_ZA', 'zu_ZA',
]; ];
private static $localeAliases = [ private const LOCALE_ALIASES = [
'az_AZ' => 'az_Latn_AZ', 'az_AZ' => 'az_Latn_AZ',
'bs_BA' => 'bs_Latn_BA', 'bs_BA' => 'bs_Latn_BA',
'en_NH' => 'en_VU', 'en_NH' => 'en_VU',
@ -759,12 +759,12 @@ abstract class ResourceBundleTestCase extends TestCase
protected function getLocales() protected function getLocales()
{ {
return self::$locales; return self::LOCALES;
} }
protected function getLocaleAliases() protected function getLocaleAliases()
{ {
return self::$localeAliases; return self::LOCALE_ALIASES;
} }
protected function getRootLocales() protected function getRootLocales()

View File

@ -22,7 +22,7 @@ class TimezonesTest extends ResourceBundleTestCase
{ {
// The below arrays document the state of the ICU data bundled with this package. // The below arrays document the state of the ICU data bundled with this package.
private static $zones = [ private const ZONES = [
'Africa/Abidjan', 'Africa/Abidjan',
'Africa/Accra', 'Africa/Accra',
'Africa/Addis_Ababa', 'Africa/Addis_Ababa',
@ -458,7 +458,7 @@ class TimezonesTest extends ResourceBundleTestCase
'Pacific/Wake', 'Pacific/Wake',
'Pacific/Wallis', 'Pacific/Wallis',
]; ];
private static $zonesNoCountry = [ private const ZONES_NO_COUNTRY = [
'Antarctica/Troll', 'Antarctica/Troll',
'CST6CDT', 'CST6CDT',
'EST5EDT', 'EST5EDT',
@ -470,7 +470,7 @@ class TimezonesTest extends ResourceBundleTestCase
public function testGetIds() public function testGetIds()
{ {
$this->assertEquals(self::$zones, Timezones::getIds()); $this->assertEquals(self::ZONES, Timezones::getIds());
} }
/** /**
@ -483,7 +483,7 @@ class TimezonesTest extends ResourceBundleTestCase
sort($zones); sort($zones);
$this->assertNotEmpty($zones); $this->assertNotEmpty($zones);
$this->assertEmpty(array_diff($zones, self::$zones)); $this->assertEmpty(array_diff($zones, self::ZONES));
} }
public function testGetNamesDefaultLocale() public function testGetNamesDefaultLocale()
@ -631,7 +631,7 @@ class TimezonesTest extends ResourceBundleTestCase
$this->addToAssertionCount(1); $this->addToAssertionCount(1);
} catch (MissingResourceException $e) { } catch (MissingResourceException $e) {
if (\in_array($timezone, self::$zonesNoCountry, true)) { if (\in_array($timezone, self::ZONES_NO_COUNTRY, true)) {
$this->markTestSkipped(); $this->markTestSkipped();
} else { } else {
$this->fail(); $this->fail();
@ -643,7 +643,7 @@ class TimezonesTest extends ResourceBundleTestCase
{ {
return array_map(function ($timezone) { return array_map(function ($timezone) {
return [$timezone]; return [$timezone];
}, self::$zones); }, self::ZONES);
} }
/** /**

View File

@ -23,7 +23,7 @@ final class Ldap implements LdapInterface
{ {
private $adapter; private $adapter;
private static $adapterMap = [ private const ADAPTER_MAP = [
'ext_ldap' => 'Symfony\Component\Ldap\Adapter\ExtLdap\Adapter', 'ext_ldap' => 'Symfony\Component\Ldap\Adapter\ExtLdap\Adapter',
]; ];
@ -74,11 +74,11 @@ final class Ldap implements LdapInterface
*/ */
public static function create($adapter, array $config = []): self public static function create($adapter, array $config = []): self
{ {
if (!isset(self::$adapterMap[$adapter])) { if (!isset(self::ADAPTER_MAP[$adapter])) {
throw new DriverNotFoundException(sprintf('Adapter "%s" not found. You should use one of: "%s".', $adapter, implode('", "', self::$adapterMap))); throw new DriverNotFoundException(sprintf('Adapter "%s" not found. You should use one of: "%s".', $adapter, implode('", "', self::ADAPTER_MAP)));
} }
$class = self::$adapterMap[$adapter]; $class = self::ADAPTER_MAP[$adapter];
return new self(new $class($config)); return new self(new $class($config));
} }

View File

@ -21,7 +21,7 @@ class QpEncoder implements EncoderInterface
/** /**
* Pre-computed QP for HUGE optimization. * Pre-computed QP for HUGE optimization.
*/ */
private static $qpMap = [ private const QP_MAP = [
0 => '=00', 1 => '=01', 2 => '=02', 3 => '=03', 4 => '=04', 0 => '=00', 1 => '=01', 2 => '=02', 3 => '=03', 4 => '=04',
5 => '=05', 6 => '=06', 7 => '=07', 8 => '=08', 9 => '=09', 5 => '=05', 6 => '=06', 7 => '=07', 8 => '=08', 9 => '=09',
10 => '=0A', 11 => '=0B', 12 => '=0C', 13 => '=0D', 14 => '=0E', 10 => '=0A', 11 => '=0B', 12 => '=0C', 13 => '=0D', 14 => '=0E',
@ -170,7 +170,7 @@ class QpEncoder implements EncoderInterface
$ret .= $this->safeMap[$b]; $ret .= $this->safeMap[$b];
++$size; ++$size;
} else { } else {
$ret .= self::$qpMap[$b]; $ret .= self::QP_MAP[$b];
$size += 3; $size += 3;
} }
} }
@ -187,7 +187,7 @@ class QpEncoder implements EncoderInterface
switch ($end = \ord(substr($string, -1))) { switch ($end = \ord(substr($string, -1))) {
case 0x09: case 0x09:
case 0x20: case 0x20:
$string = substr_replace($string, self::$qpMap[$end], -1); $string = substr_replace($string, self::QP_MAP[$end], -1);
} }
return $string; return $string;

View File

@ -21,7 +21,7 @@ use Symfony\Component\Mime\Exception\LogicException;
*/ */
final class Headers final class Headers
{ {
private static $uniqueHeaders = [ private const UNIQUE_HEADERS = [
'date', 'from', 'sender', 'reply-to', 'to', 'cc', 'bcc', 'date', 'from', 'sender', 'reply-to', 'to', 'cc', 'bcc',
'message-id', 'in-reply-to', 'references', 'subject', 'message-id', 'in-reply-to', 'references', 'subject',
]; ];
@ -153,7 +153,7 @@ final class Headers
throw new LogicException(sprintf('The "%s" header must be an instance of "%s" (got "%s").', $header->getName(), $map[$name], \get_class($header))); throw new LogicException(sprintf('The "%s" header must be an instance of "%s" (got "%s").', $header->getName(), $map[$name], \get_class($header)));
} }
if (\in_array($name, self::$uniqueHeaders, true) && isset($this->headers[$name]) && \count($this->headers[$name]) > 0) { if (\in_array($name, self::UNIQUE_HEADERS, true) && isset($this->headers[$name]) && \count($this->headers[$name]) > 0) {
throw new LogicException(sprintf('Impossible to set header "%s" as it\'s already defined and must be unique.', $header->getName())); throw new LogicException(sprintf('Impossible to set header "%s" as it\'s already defined and must be unique.', $header->getName()));
} }
@ -201,7 +201,7 @@ final class Headers
public static function isUniqueHeader(string $name): bool public static function isUniqueHeader(string $name): bool
{ {
return \in_array($name, self::$uniqueHeaders, true); return \in_array($name, self::UNIQUE_HEADERS, true);
} }
public function toString(): string public function toString(): string

View File

@ -87,7 +87,7 @@ final class MimeTypes implements MimeTypesInterface
$extensions = $this->extensions[$mimeType] ?? $this->extensions[$lcMimeType = strtolower($mimeType)] ?? null; $extensions = $this->extensions[$mimeType] ?? $this->extensions[$lcMimeType = strtolower($mimeType)] ?? null;
} }
return $extensions ?? self::$map[$mimeType] ?? self::$map[$lcMimeType ?? strtolower($mimeType)] ?? []; return $extensions ?? self::MAP[$mimeType] ?? self::MAP[$lcMimeType ?? strtolower($mimeType)] ?? [];
} }
/** /**
@ -99,7 +99,7 @@ final class MimeTypes implements MimeTypesInterface
$mimeTypes = $this->mimeTypes[$ext] ?? $this->mimeTypes[$lcExt = strtolower($ext)] ?? null; $mimeTypes = $this->mimeTypes[$ext] ?? $this->mimeTypes[$lcExt = strtolower($ext)] ?? null;
} }
return $mimeTypes ?? self::$reverseMap[$ext] ?? self::$reverseMap[$lcExt ?? strtolower($ext)] ?? []; return $mimeTypes ?? self::REVERSE_MAP[$ext] ?? self::REVERSE_MAP[$lcExt ?? strtolower($ext)] ?? [];
} }
/** /**
@ -150,7 +150,7 @@ final class MimeTypes implements MimeTypesInterface
* *
* @see Resources/bin/update_mime_types.php * @see Resources/bin/update_mime_types.php
*/ */
private static $map = [ private const MAP = [
'application/acrobat' => ['pdf'], 'application/acrobat' => ['pdf'],
'application/andrew-inset' => ['ez'], 'application/andrew-inset' => ['ez'],
'application/annodex' => ['anx'], 'application/annodex' => ['anx'],
@ -1611,7 +1611,7 @@ final class MimeTypes implements MimeTypesInterface
'zz-application/zz-winassoc-xls' => ['xls', 'xlc', 'xll', 'xlm', 'xlw', 'xla', 'xlt', 'xld'], 'zz-application/zz-winassoc-xls' => ['xls', 'xlc', 'xll', 'xlm', 'xlw', 'xla', 'xlt', 'xld'],
]; ];
private static $reverseMap = [ private const REVERSE_MAP = [
'32x' => ['application/x-genesis-32x-rom'], '32x' => ['application/x-genesis-32x-rom'],
'3dml' => ['text/vnd.in3d.3dml'], '3dml' => ['text/vnd.in3d.3dml'],
'3ds' => ['image/x-3ds'], '3ds' => ['image/x-3ds'],

View File

@ -105,7 +105,7 @@ class OptionsResolver implements Options
private $parentsOptions = []; private $parentsOptions = [];
private static $typeAliases = [ private const TYPE_ALIASES = [
'boolean' => 'bool', 'boolean' => 'bool',
'integer' => 'int', 'integer' => 'int',
'double' => 'float', 'double' => 'float',
@ -926,7 +926,7 @@ class OptionsResolver implements Options
$invalidTypes = []; $invalidTypes = [];
foreach ($this->allowedTypes[$option] as $type) { foreach ($this->allowedTypes[$option] as $type) {
$type = self::$typeAliases[$type] ?? $type; $type = self::TYPE_ALIASES[$type] ?? $type;
if ($valid = $this->verifyTypes($type, $value, $invalidTypes)) { if ($valid = $this->verifyTypes($type, $value, $invalidTypes)) {
break; break;
@ -938,7 +938,7 @@ class OptionsResolver implements Options
$fmtAllowedTypes = implode('" or "', $this->allowedTypes[$option]); $fmtAllowedTypes = implode('" or "', $this->allowedTypes[$option]);
$fmtProvidedTypes = implode('|', array_keys($invalidTypes)); $fmtProvidedTypes = implode('|', array_keys($invalidTypes));
$allowedContainsArrayType = \count(array_filter($this->allowedTypes[$option], static function ($item) { $allowedContainsArrayType = \count(array_filter($this->allowedTypes[$option], static function ($item) {
return '[]' === substr(self::$typeAliases[$item] ?? $item, -2); return '[]' === substr(self::TYPE_ALIASES[$item] ?? $item, -2);
})) > 0; })) > 0;
if (\is_array($value) && $allowedContainsArrayType) { if (\is_array($value) && $allowedContainsArrayType) {

View File

@ -66,7 +66,7 @@ class PropertyAccessor implements PropertyAccessorInterface
private $propertyPathCache = []; private $propertyPathCache = [];
private $readPropertyCache = []; private $readPropertyCache = [];
private $writePropertyCache = []; private $writePropertyCache = [];
private static $resultProto = [self::VALUE => null]; private const RESULT_PROTO = [self::VALUE => null];
/** /**
* Should not be used by application code. Use * Should not be used by application code. Use
@ -355,7 +355,7 @@ class PropertyAccessor implements PropertyAccessorInterface
throw new NoSuchIndexException(sprintf('Cannot read index "%s" from object of type "%s" because it doesn\'t implement \ArrayAccess.', $index, \get_class($zval[self::VALUE]))); throw new NoSuchIndexException(sprintf('Cannot read index "%s" from object of type "%s" because it doesn\'t implement \ArrayAccess.', $index, \get_class($zval[self::VALUE])));
} }
$result = self::$resultProto; $result = self::RESULT_PROTO;
if (isset($zval[self::VALUE][$index])) { if (isset($zval[self::VALUE][$index])) {
$result[self::VALUE] = $zval[self::VALUE][$index]; $result[self::VALUE] = $zval[self::VALUE][$index];
@ -383,7 +383,7 @@ class PropertyAccessor implements PropertyAccessorInterface
throw new NoSuchPropertyException(sprintf('Cannot read property "%s" from an array. Maybe you intended to write the property path as "[%1$s]" instead.', $property)); throw new NoSuchPropertyException(sprintf('Cannot read property "%s" from an array. Maybe you intended to write the property path as "[%1$s]" instead.', $property));
} }
$result = self::$resultProto; $result = self::RESULT_PROTO;
$object = $zval[self::VALUE]; $object = $zval[self::VALUE];
$access = $this->getReadAccessInfo(\get_class($object), $property); $access = $this->getReadAccessInfo(\get_class($object), $property);

View File

@ -28,7 +28,7 @@ use Symfony\Component\Yaml\Yaml;
*/ */
class YamlFileLoader extends FileLoader class YamlFileLoader extends FileLoader
{ {
private static $availableKeys = [ private const AVAILABLE_KEYS = [
'resource', 'type', 'prefix', 'path', 'host', 'schemes', 'methods', 'defaults', 'requirements', 'options', 'condition', 'controller', 'name_prefix', 'trailing_slash_on_root', 'locale', 'format', 'utf8', 'exclude', 'resource', 'type', 'prefix', 'path', 'host', 'schemes', 'methods', 'defaults', 'requirements', 'options', 'condition', 'controller', 'name_prefix', 'trailing_slash_on_root', 'locale', 'format', 'utf8', 'exclude',
]; ];
private $yamlParser; private $yamlParser;
@ -269,8 +269,8 @@ class YamlFileLoader extends FileLoader
if (!\is_array($config)) { if (!\is_array($config)) {
throw new \InvalidArgumentException(sprintf('The definition of "%s" in "%s" must be a YAML array.', $name, $path)); throw new \InvalidArgumentException(sprintf('The definition of "%s" in "%s" must be a YAML array.', $name, $path));
} }
if ($extraKeys = array_diff(array_keys($config), self::$availableKeys)) { if ($extraKeys = array_diff(array_keys($config), self::AVAILABLE_KEYS)) {
throw new \InvalidArgumentException(sprintf('The routing file "%s" contains unsupported keys for "%s": "%s". Expected one of: "%s".', $path, $name, implode('", "', $extraKeys), implode('", "', self::$availableKeys))); throw new \InvalidArgumentException(sprintf('The routing file "%s" contains unsupported keys for "%s": "%s". Expected one of: "%s".', $path, $name, implode('", "', $extraKeys), implode('", "', self::AVAILABLE_KEYS)));
} }
if (isset($config['resource']) && isset($config['path'])) { if (isset($config['resource']) && isset($config['path'])) {
throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "resource" key and the "path" key for "%s". Choose between an import and a route definition.', $path, $name)); throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "resource" key and the "path" key for "%s". Choose between an import and a route definition.', $path, $name));

View File

@ -27,7 +27,7 @@ use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
*/ */
class DataUriNormalizer implements NormalizerInterface, DenormalizerInterface, CacheableSupportsMethodInterface class DataUriNormalizer implements NormalizerInterface, DenormalizerInterface, CacheableSupportsMethodInterface
{ {
private static $supportedTypes = [ private const SUPPORTED_TYPES = [
\SplFileInfo::class => true, \SplFileInfo::class => true,
\SplFileObject::class => true, \SplFileObject::class => true,
File::class => true, File::class => true,
@ -134,7 +134,7 @@ class DataUriNormalizer implements NormalizerInterface, DenormalizerInterface, C
*/ */
public function supportsDenormalization($data, $type, $format = null) public function supportsDenormalization($data, $type, $format = null)
{ {
return isset(self::$supportedTypes[$type]); return isset(self::SUPPORTED_TYPES[$type]);
} }
/** /**

View File

@ -27,7 +27,7 @@ class DateTimeNormalizer implements NormalizerInterface, DenormalizerInterface,
private $defaultContext; private $defaultContext;
private static $supportedTypes = [ private const SUPPORTED_TYPES = [
\DateTimeInterface::class => true, \DateTimeInterface::class => true,
\DateTimeImmutable::class => true, \DateTimeImmutable::class => true,
\DateTime::class => true, \DateTime::class => true,
@ -125,7 +125,7 @@ class DateTimeNormalizer implements NormalizerInterface, DenormalizerInterface,
*/ */
public function supportsDenormalization($data, $type, $format = null) public function supportsDenormalization($data, $type, $format = null)
{ {
return isset(self::$supportedTypes[$type]); return isset(self::SUPPORTED_TYPES[$type]);
} }
/** /**

View File

@ -35,7 +35,7 @@ class EmailValidator extends ConstraintValidator
*/ */
public const PATTERN_LOOSE = '/^.+\@\S+\.\S+$/'; public const PATTERN_LOOSE = '/^.+\@\S+\.\S+$/';
private static $emailPatterns = [ private const EMAIL_PATTERNS = [
Email::VALIDATION_MODE_LOOSE => self::PATTERN_LOOSE, Email::VALIDATION_MODE_LOOSE => self::PATTERN_LOOSE,
Email::VALIDATION_MODE_HTML5 => self::PATTERN_HTML5, Email::VALIDATION_MODE_HTML5 => self::PATTERN_HTML5,
]; ];
@ -129,7 +129,7 @@ class EmailValidator extends ConstraintValidator
return; return;
} }
} elseif (!preg_match(self::$emailPatterns[$constraint->mode], $value)) { } elseif (!preg_match(self::EMAIL_PATTERNS[$constraint->mode], $value)) {
$this->context->buildViolation($constraint->message) $this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value)) ->setParameter('{{ value }}', $this->formatValue($value))
->setCode(Email::INVALID_FORMAT_ERROR) ->setCode(Email::INVALID_FORMAT_ERROR)

View File

@ -30,7 +30,7 @@ class FileValidator extends ConstraintValidator
public const KIB_BYTES = 1024; public const KIB_BYTES = 1024;
public const MIB_BYTES = 1048576; public const MIB_BYTES = 1048576;
private static $suffices = [ private const SUFFICES = [
1 => 'bytes', 1 => 'bytes',
self::KB_BYTES => 'kB', self::KB_BYTES => 'kB',
self::MB_BYTES => 'MB', self::MB_BYTES => 'MB',
@ -247,6 +247,6 @@ class FileValidator extends ConstraintValidator
$sizeAsString = (string) round($size / $coef, 2); $sizeAsString = (string) round($size / $coef, 2);
} }
return [$sizeAsString, $limitAsString, self::$suffices[$coef]]; return [$sizeAsString, $limitAsString, self::SUFFICES[$coef]];
} }
} }

View File

@ -36,7 +36,7 @@ class IbanValidator extends ConstraintValidator
* *
* @see https://www.swift.com/sites/default/files/resources/iban_registry.pdf * @see https://www.swift.com/sites/default/files/resources/iban_registry.pdf
*/ */
private static $formats = [ private const FORMATS = [
'AD' => 'AD\d{2}\d{4}\d{4}[\dA-Z]{12}', // Andorra 'AD' => 'AD\d{2}\d{4}\d{4}[\dA-Z]{12}', // Andorra
'AE' => 'AE\d{2}\d{3}\d{16}', // United Arab Emirates 'AE' => 'AE\d{2}\d{3}\d{16}', // United Arab Emirates
'AL' => 'AL\d{2}\d{8}[\dA-Z]{16}', // Albania 'AL' => 'AL\d{2}\d{8}[\dA-Z]{16}', // Albania
@ -182,7 +182,7 @@ class IbanValidator extends ConstraintValidator
} }
// ...have a format available // ...have a format available
if (!\array_key_exists($countryCode, self::$formats)) { if (!\array_key_exists($countryCode, self::FORMATS)) {
$this->context->buildViolation($constraint->message) $this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value)) ->setParameter('{{ value }}', $this->formatValue($value))
->setCode(Iban::NOT_SUPPORTED_COUNTRY_CODE_ERROR) ->setCode(Iban::NOT_SUPPORTED_COUNTRY_CODE_ERROR)
@ -192,7 +192,7 @@ class IbanValidator extends ConstraintValidator
} }
// ...and have a valid format // ...and have a valid format
if (!preg_match('/^'.self::$formats[$countryCode].'$/', $canonicalized) if (!preg_match('/^'.self::FORMATS[$countryCode].'$/', $canonicalized)
) { ) {
$this->context->buildViolation($constraint->message) $this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value)) ->setParameter('{{ value }}', $this->formatValue($value))

View File

@ -22,7 +22,7 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/ */
class AmqpCaster class AmqpCaster
{ {
private static $flags = [ private const FLAGS = [
\AMQP_DURABLE => 'AMQP_DURABLE', \AMQP_DURABLE => 'AMQP_DURABLE',
\AMQP_PASSIVE => 'AMQP_PASSIVE', \AMQP_PASSIVE => 'AMQP_PASSIVE',
\AMQP_EXCLUSIVE => 'AMQP_EXCLUSIVE', \AMQP_EXCLUSIVE => 'AMQP_EXCLUSIVE',
@ -39,7 +39,7 @@ class AmqpCaster
\AMQP_REQUEUE => 'AMQP_REQUEUE', \AMQP_REQUEUE => 'AMQP_REQUEUE',
]; ];
private static $exchangeTypes = [ private const EXCHANGE_TYPES = [
\AMQP_EX_TYPE_DIRECT => 'AMQP_EX_TYPE_DIRECT', \AMQP_EX_TYPE_DIRECT => 'AMQP_EX_TYPE_DIRECT',
\AMQP_EX_TYPE_FANOUT => 'AMQP_EX_TYPE_FANOUT', \AMQP_EX_TYPE_FANOUT => 'AMQP_EX_TYPE_FANOUT',
\AMQP_EX_TYPE_TOPIC => 'AMQP_EX_TYPE_TOPIC', \AMQP_EX_TYPE_TOPIC => 'AMQP_EX_TYPE_TOPIC',
@ -133,7 +133,7 @@ class AmqpCaster
$prefix.'flags' => self::extractFlags($c->getFlags()), $prefix.'flags' => self::extractFlags($c->getFlags()),
]; ];
$type = isset(self::$exchangeTypes[$c->getType()]) ? new ConstStub(self::$exchangeTypes[$c->getType()], $c->getType()) : $c->getType(); $type = isset(self::EXCHANGE_TYPES[$c->getType()]) ? new ConstStub(self::EXCHANGE_TYPES[$c->getType()], $c->getType()) : $c->getType();
// Recent version of the extension already expose private properties // Recent version of the extension already expose private properties
if (isset($a["\x00AMQPExchange\x00name"])) { if (isset($a["\x00AMQPExchange\x00name"])) {
@ -197,7 +197,7 @@ class AmqpCaster
{ {
$flagsArray = []; $flagsArray = [];
foreach (self::$flags as $value => $name) { foreach (self::FLAGS as $value => $name) {
if ($flags & $value) { if ($flags & $value) {
$flagsArray[] = $name; $flagsArray[] = $name;
} }

View File

@ -22,7 +22,7 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/ */
class DOMCaster class DOMCaster
{ {
private static $errorCodes = [ private const ERROR_CODES = [
\DOM_PHP_ERR => 'DOM_PHP_ERR', \DOM_PHP_ERR => 'DOM_PHP_ERR',
\DOM_INDEX_SIZE_ERR => 'DOM_INDEX_SIZE_ERR', \DOM_INDEX_SIZE_ERR => 'DOM_INDEX_SIZE_ERR',
\DOMSTRING_SIZE_ERR => 'DOMSTRING_SIZE_ERR', \DOMSTRING_SIZE_ERR => 'DOMSTRING_SIZE_ERR',
@ -42,7 +42,7 @@ class DOMCaster
\DOM_VALIDATION_ERR => 'DOM_VALIDATION_ERR', \DOM_VALIDATION_ERR => 'DOM_VALIDATION_ERR',
]; ];
private static $nodeTypes = [ private const NODE_TYPES = [
\XML_ELEMENT_NODE => 'XML_ELEMENT_NODE', \XML_ELEMENT_NODE => 'XML_ELEMENT_NODE',
\XML_ATTRIBUTE_NODE => 'XML_ATTRIBUTE_NODE', \XML_ATTRIBUTE_NODE => 'XML_ATTRIBUTE_NODE',
\XML_TEXT_NODE => 'XML_TEXT_NODE', \XML_TEXT_NODE => 'XML_TEXT_NODE',
@ -66,8 +66,8 @@ class DOMCaster
public static function castException(\DOMException $e, array $a, Stub $stub, $isNested) public static function castException(\DOMException $e, array $a, Stub $stub, $isNested)
{ {
$k = Caster::PREFIX_PROTECTED.'code'; $k = Caster::PREFIX_PROTECTED.'code';
if (isset($a[$k], self::$errorCodes[$a[$k]])) { if (isset($a[$k], self::ERROR_CODES[$a[$k]])) {
$a[$k] = new ConstStub(self::$errorCodes[$a[$k]], $a[$k]); $a[$k] = new ConstStub(self::ERROR_CODES[$a[$k]], $a[$k]);
} }
return $a; return $a;
@ -97,7 +97,7 @@ class DOMCaster
$a += [ $a += [
'nodeName' => $dom->nodeName, 'nodeName' => $dom->nodeName,
'nodeValue' => new CutStub($dom->nodeValue), 'nodeValue' => new CutStub($dom->nodeValue),
'nodeType' => new ConstStub(self::$nodeTypes[$dom->nodeType], $dom->nodeType), 'nodeType' => new ConstStub(self::NODE_TYPES[$dom->nodeType], $dom->nodeType),
'parentNode' => new CutStub($dom->parentNode), 'parentNode' => new CutStub($dom->parentNode),
'childNodes' => $dom->childNodes, 'childNodes' => $dom->childNodes,
'firstChild' => new CutStub($dom->firstChild), 'firstChild' => new CutStub($dom->firstChild),
@ -121,7 +121,7 @@ class DOMCaster
$a += [ $a += [
'nodeName' => $dom->nodeName, 'nodeName' => $dom->nodeName,
'nodeValue' => new CutStub($dom->nodeValue), 'nodeValue' => new CutStub($dom->nodeValue),
'nodeType' => new ConstStub(self::$nodeTypes[$dom->nodeType], $dom->nodeType), 'nodeType' => new ConstStub(self::NODE_TYPES[$dom->nodeType], $dom->nodeType),
'prefix' => $dom->prefix, 'prefix' => $dom->prefix,
'localName' => $dom->localName, 'localName' => $dom->localName,
'namespaceURI' => $dom->namespaceURI, 'namespaceURI' => $dom->namespaceURI,

View File

@ -22,7 +22,7 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/ */
class PdoCaster class PdoCaster
{ {
private static $pdoAttributes = [ private const PDO_ATTRIBUTES = [
'CASE' => [ 'CASE' => [
\PDO::CASE_LOWER => 'LOWER', \PDO::CASE_LOWER => 'LOWER',
\PDO::CASE_NATURAL => 'NATURAL', \PDO::CASE_NATURAL => 'NATURAL',
@ -65,7 +65,7 @@ class PdoCaster
$errmode = $c->getAttribute(\PDO::ATTR_ERRMODE); $errmode = $c->getAttribute(\PDO::ATTR_ERRMODE);
$c->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $c->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
foreach (self::$pdoAttributes as $k => $v) { foreach (self::PDO_ATTRIBUTES as $k => $v) {
if (!isset($k[0])) { if (!isset($k[0])) {
$k = $v; $k = $v;
$v = []; $v = [];

View File

@ -22,7 +22,7 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/ */
class PgSqlCaster class PgSqlCaster
{ {
private static $paramCodes = [ private const PARAM_CODES = [
'server_encoding', 'server_encoding',
'client_encoding', 'client_encoding',
'is_superuser', 'is_superuser',
@ -35,7 +35,7 @@ class PgSqlCaster
'standard_conforming_strings', 'standard_conforming_strings',
]; ];
private static $transactionStatus = [ private const TRANSACTION_STATUS = [
\PGSQL_TRANSACTION_IDLE => 'PGSQL_TRANSACTION_IDLE', \PGSQL_TRANSACTION_IDLE => 'PGSQL_TRANSACTION_IDLE',
\PGSQL_TRANSACTION_ACTIVE => 'PGSQL_TRANSACTION_ACTIVE', \PGSQL_TRANSACTION_ACTIVE => 'PGSQL_TRANSACTION_ACTIVE',
\PGSQL_TRANSACTION_INTRANS => 'PGSQL_TRANSACTION_INTRANS', \PGSQL_TRANSACTION_INTRANS => 'PGSQL_TRANSACTION_INTRANS',
@ -43,7 +43,7 @@ class PgSqlCaster
\PGSQL_TRANSACTION_UNKNOWN => 'PGSQL_TRANSACTION_UNKNOWN', \PGSQL_TRANSACTION_UNKNOWN => 'PGSQL_TRANSACTION_UNKNOWN',
]; ];
private static $resultStatus = [ private const RESULT_STATUS = [
\PGSQL_EMPTY_QUERY => 'PGSQL_EMPTY_QUERY', \PGSQL_EMPTY_QUERY => 'PGSQL_EMPTY_QUERY',
\PGSQL_COMMAND_OK => 'PGSQL_COMMAND_OK', \PGSQL_COMMAND_OK => 'PGSQL_COMMAND_OK',
\PGSQL_TUPLES_OK => 'PGSQL_TUPLES_OK', \PGSQL_TUPLES_OK => 'PGSQL_TUPLES_OK',
@ -54,7 +54,7 @@ class PgSqlCaster
\PGSQL_FATAL_ERROR => 'PGSQL_FATAL_ERROR', \PGSQL_FATAL_ERROR => 'PGSQL_FATAL_ERROR',
]; ];
private static $diagCodes = [ private const DIAG_CODES = [
'severity' => \PGSQL_DIAG_SEVERITY, 'severity' => \PGSQL_DIAG_SEVERITY,
'sqlstate' => \PGSQL_DIAG_SQLSTATE, 'sqlstate' => \PGSQL_DIAG_SQLSTATE,
'message' => \PGSQL_DIAG_MESSAGE_PRIMARY, 'message' => \PGSQL_DIAG_MESSAGE_PRIMARY,
@ -83,8 +83,8 @@ class PgSqlCaster
$a['busy'] = pg_connection_busy($link); $a['busy'] = pg_connection_busy($link);
$a['transaction'] = pg_transaction_status($link); $a['transaction'] = pg_transaction_status($link);
if (isset(self::$transactionStatus[$a['transaction']])) { if (isset(self::TRANSACTION_STATUS[$a['transaction']])) {
$a['transaction'] = new ConstStub(self::$transactionStatus[$a['transaction']], $a['transaction']); $a['transaction'] = new ConstStub(self::TRANSACTION_STATUS[$a['transaction']], $a['transaction']);
} }
$a['pid'] = pg_get_pid($link); $a['pid'] = pg_get_pid($link);
@ -96,7 +96,7 @@ class PgSqlCaster
$a['options'] = pg_options($link); $a['options'] = pg_options($link);
$a['version'] = pg_version($link); $a['version'] = pg_version($link);
foreach (self::$paramCodes as $v) { foreach (self::PARAM_CODES as $v) {
if (false !== $s = pg_parameter_status($link, $v)) { if (false !== $s = pg_parameter_status($link, $v)) {
$a['param'][$v] = $s; $a['param'][$v] = $s;
} }
@ -112,13 +112,13 @@ class PgSqlCaster
{ {
$a['num rows'] = pg_num_rows($result); $a['num rows'] = pg_num_rows($result);
$a['status'] = pg_result_status($result); $a['status'] = pg_result_status($result);
if (isset(self::$resultStatus[$a['status']])) { if (isset(self::RESULT_STATUS[$a['status']])) {
$a['status'] = new ConstStub(self::$resultStatus[$a['status']], $a['status']); $a['status'] = new ConstStub(self::RESULT_STATUS[$a['status']], $a['status']);
} }
$a['command-completion tag'] = pg_result_status($result, \PGSQL_STATUS_STRING); $a['command-completion tag'] = pg_result_status($result, \PGSQL_STATUS_STRING);
if (-1 === $a['num rows']) { if (-1 === $a['num rows']) {
foreach (self::$diagCodes as $k => $v) { foreach (self::DIAG_CODES as $k => $v) {
$a['error'][$k] = pg_result_error_field($result, $v); $a['error'][$k] = pg_result_error_field($result, $v);
} }
} }

View File

@ -22,24 +22,24 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/ */
class RedisCaster class RedisCaster
{ {
private static $serializer = [ private const SERIALIZERS = [
\Redis::SERIALIZER_NONE => 'NONE', \Redis::SERIALIZER_NONE => 'NONE',
\Redis::SERIALIZER_PHP => 'PHP', \Redis::SERIALIZER_PHP => 'PHP',
2 => 'IGBINARY', // Optional Redis::SERIALIZER_IGBINARY 2 => 'IGBINARY', // Optional Redis::SERIALIZER_IGBINARY
]; ];
private static $mode = [ private const MODES = [
\Redis::ATOMIC => 'ATOMIC', \Redis::ATOMIC => 'ATOMIC',
\Redis::MULTI => 'MULTI', \Redis::MULTI => 'MULTI',
\Redis::PIPELINE => 'PIPELINE', \Redis::PIPELINE => 'PIPELINE',
]; ];
private static $compression = [ private const COMPRESSION_MODES = [
0 => 'NONE', // Redis::COMPRESSION_NONE 0 => 'NONE', // Redis::COMPRESSION_NONE
1 => 'LZF', // Redis::COMPRESSION_LZF 1 => 'LZF', // Redis::COMPRESSION_LZF
]; ];
private static $failover = [ private const FAILOVER_OPTIONS = [
\RedisCluster::FAILOVER_NONE => 'NONE', \RedisCluster::FAILOVER_NONE => 'NONE',
\RedisCluster::FAILOVER_ERROR => 'ERROR', \RedisCluster::FAILOVER_ERROR => 'ERROR',
\RedisCluster::FAILOVER_DISTRIBUTE => 'DISTRIBUTE', \RedisCluster::FAILOVER_DISTRIBUTE => 'DISTRIBUTE',
@ -63,7 +63,7 @@ class RedisCaster
$prefix.'host' => $c->getHost(), $prefix.'host' => $c->getHost(),
$prefix.'port' => $c->getPort(), $prefix.'port' => $c->getPort(),
$prefix.'auth' => $c->getAuth(), $prefix.'auth' => $c->getAuth(),
$prefix.'mode' => isset(self::$mode[$mode]) ? new ConstStub(self::$mode[$mode], $mode) : $mode, $prefix.'mode' => isset(self::MODES[$mode]) ? new ConstStub(self::MODES[$mode], $mode) : $mode,
$prefix.'dbNum' => $c->getDbNum(), $prefix.'dbNum' => $c->getDbNum(),
$prefix.'timeout' => $c->getTimeout(), $prefix.'timeout' => $c->getTimeout(),
$prefix.'lastError' => $c->getLastError(), $prefix.'lastError' => $c->getLastError(),
@ -95,7 +95,7 @@ class RedisCaster
$prefix.'mode' => new ConstStub($c->getMode() ? 'MULTI' : 'ATOMIC', $c->getMode()), $prefix.'mode' => new ConstStub($c->getMode() ? 'MULTI' : 'ATOMIC', $c->getMode()),
$prefix.'lastError' => $c->getLastError(), $prefix.'lastError' => $c->getLastError(),
$prefix.'options' => self::getRedisOptions($c, [ $prefix.'options' => self::getRedisOptions($c, [
'SLAVE_FAILOVER' => isset(self::$failover[$failover]) ? new ConstStub(self::$failover[$failover], $failover) : $failover, 'SLAVE_FAILOVER' => isset(self::FAILOVER_OPTIONS[$failover]) ? new ConstStub(self::FAILOVER_OPTIONS[$failover], $failover) : $failover,
]), ]),
]; ];
@ -110,23 +110,23 @@ class RedisCaster
$serializer = $redis->getOption(\Redis::OPT_SERIALIZER); $serializer = $redis->getOption(\Redis::OPT_SERIALIZER);
if (\is_array($serializer)) { if (\is_array($serializer)) {
foreach ($serializer as &$v) { foreach ($serializer as &$v) {
if (isset(self::$serializer[$v])) { if (isset(self::SERIALIZERS[$v])) {
$v = new ConstStub(self::$serializer[$v], $v); $v = new ConstStub(self::SERIALIZERS[$v], $v);
} }
} }
} elseif (isset(self::$serializer[$serializer])) { } elseif (isset(self::SERIALIZERS[$serializer])) {
$serializer = new ConstStub(self::$serializer[$serializer], $serializer); $serializer = new ConstStub(self::SERIALIZERS[$serializer], $serializer);
} }
$compression = \defined('Redis::OPT_COMPRESSION') ? $redis->getOption(\Redis::OPT_COMPRESSION) : 0; $compression = \defined('Redis::OPT_COMPRESSION') ? $redis->getOption(\Redis::OPT_COMPRESSION) : 0;
if (\is_array($compression)) { if (\is_array($compression)) {
foreach ($compression as &$v) { foreach ($compression as &$v) {
if (isset(self::$compression[$v])) { if (isset(self::COMPRESSION_MODES[$v])) {
$v = new ConstStub(self::$compression[$v], $v); $v = new ConstStub(self::COMPRESSION_MODES[$v], $v);
} }
} }
} elseif (isset(self::$compression[$compression])) { } elseif (isset(self::COMPRESSION_MODES[$compression])) {
$compression = new ConstStub(self::$compression[$compression], $compression); $compression = new ConstStub(self::COMPRESSION_MODES[$compression], $compression);
} }
$retry = \defined('Redis::OPT_SCAN') ? $redis->getOption(\Redis::OPT_SCAN) : 0; $retry = \defined('Redis::OPT_SCAN') ? $redis->getOption(\Redis::OPT_SCAN) : 0;

View File

@ -24,7 +24,7 @@ class ReflectionCaster
{ {
public const UNSET_CLOSURE_FILE_INFO = ['Closure' => __CLASS__.'::unsetClosureFileInfo']; public const UNSET_CLOSURE_FILE_INFO = ['Closure' => __CLASS__.'::unsetClosureFileInfo'];
private static $extraMap = [ private const EXTRA_MAP = [
'docComment' => 'getDocComment', 'docComment' => 'getDocComment',
'extension' => 'getExtensionName', 'extension' => 'getExtensionName',
'isDisabled' => 'isDisabled', 'isDisabled' => 'isDisabled',
@ -370,7 +370,7 @@ class ReflectionCaster
$x['line'] = $c->getStartLine().' to '.$c->getEndLine(); $x['line'] = $c->getStartLine().' to '.$c->getEndLine();
} }
self::addMap($x, $c, self::$extraMap, ''); self::addMap($x, $c, self::EXTRA_MAP, '');
if ($x) { if ($x) {
$a[Caster::PREFIX_VIRTUAL.'extra'] = new EnumStub($x); $a[Caster::PREFIX_VIRTUAL.'extra'] = new EnumStub($x);

View File

@ -22,7 +22,7 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/ */
class SplCaster class SplCaster
{ {
private static $splFileObjectFlags = [ private const SPL_FILE_OBJECT_FLAGS = [
\SplFileObject::DROP_NEW_LINE => 'DROP_NEW_LINE', \SplFileObject::DROP_NEW_LINE => 'DROP_NEW_LINE',
\SplFileObject::READ_AHEAD => 'READ_AHEAD', \SplFileObject::READ_AHEAD => 'READ_AHEAD',
\SplFileObject::SKIP_EMPTY => 'SKIP_EMPTY', \SplFileObject::SKIP_EMPTY => 'SKIP_EMPTY',
@ -169,7 +169,7 @@ class SplCaster
if (isset($a[$prefix.'flags'])) { if (isset($a[$prefix.'flags'])) {
$flagsArray = []; $flagsArray = [];
foreach (self::$splFileObjectFlags as $value => $name) { foreach (self::SPL_FILE_OBJECT_FLAGS as $value => $name) {
if ($a[$prefix.'flags'] & $value) { if ($a[$prefix.'flags'] & $value) {
$flagsArray[] = $name; $flagsArray[] = $name;
} }

View File

@ -19,7 +19,7 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/ */
class SymfonyCaster class SymfonyCaster
{ {
private static $requestGetters = [ private const REQUEST_GETTERS = [
'pathInfo' => 'getPathInfo', 'pathInfo' => 'getPathInfo',
'requestUri' => 'getRequestUri', 'requestUri' => 'getRequestUri',
'baseUrl' => 'getBaseUrl', 'baseUrl' => 'getBaseUrl',
@ -32,7 +32,7 @@ class SymfonyCaster
{ {
$clone = null; $clone = null;
foreach (self::$requestGetters as $prop => $getter) { foreach (self::REQUEST_GETTERS as $prop => $getter) {
$key = Caster::PREFIX_PROTECTED.$prop; $key = Caster::PREFIX_PROTECTED.$prop;
if (\array_key_exists($key, $a) && null === $a[$key]) { if (\array_key_exists($key, $a) && null === $a[$key]) {
if (null === $clone) { if (null === $clone) {

View File

@ -21,7 +21,7 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/ */
class XmlReaderCaster class XmlReaderCaster
{ {
private static $nodeTypes = [ private const NODE_TYPES = [
\XMLReader::NONE => 'NONE', \XMLReader::NONE => 'NONE',
\XMLReader::ELEMENT => 'ELEMENT', \XMLReader::ELEMENT => 'ELEMENT',
\XMLReader::ATTRIBUTE => 'ATTRIBUTE', \XMLReader::ATTRIBUTE => 'ATTRIBUTE',
@ -48,7 +48,7 @@ class XmlReaderCaster
$info = [ $info = [
'localName' => $reader->localName, 'localName' => $reader->localName,
'prefix' => $reader->prefix, 'prefix' => $reader->prefix,
'nodeType' => new ConstStub(self::$nodeTypes[$reader->nodeType], $reader->nodeType), 'nodeType' => new ConstStub(self::NODE_TYPES[$reader->nodeType], $reader->nodeType),
'depth' => $reader->depth, 'depth' => $reader->depth,
'isDefault' => $reader->isDefault, 'isDefault' => $reader->isDefault,
'isEmptyElement' => \XMLReader::NONE === $reader->nodeType ? null : $reader->isEmptyElement, 'isEmptyElement' => \XMLReader::NONE === $reader->nodeType ? null : $reader->isEmptyElement,

View File

@ -22,7 +22,7 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/ */
class XmlResourceCaster class XmlResourceCaster
{ {
private static $xmlErrors = [ private const XML_ERRORS = [
\XML_ERROR_NONE => 'XML_ERROR_NONE', \XML_ERROR_NONE => 'XML_ERROR_NONE',
\XML_ERROR_NO_MEMORY => 'XML_ERROR_NO_MEMORY', \XML_ERROR_NO_MEMORY => 'XML_ERROR_NO_MEMORY',
\XML_ERROR_SYNTAX => 'XML_ERROR_SYNTAX', \XML_ERROR_SYNTAX => 'XML_ERROR_SYNTAX',
@ -54,8 +54,8 @@ class XmlResourceCaster
$a['current_line_number'] = xml_get_current_line_number($h); $a['current_line_number'] = xml_get_current_line_number($h);
$a['error_code'] = xml_get_error_code($h); $a['error_code'] = xml_get_error_code($h);
if (isset(self::$xmlErrors[$a['error_code']])) { if (isset(self::XML_ERRORS[$a['error_code']])) {
$a['error_code'] = new ConstStub(self::$xmlErrors[$a['error_code']], $a['error_code']); $a['error_code'] = new ConstStub(self::XML_ERRORS[$a['error_code']], $a['error_code']);
} }
return $a; return $a;

View File

@ -28,7 +28,7 @@ class Escaper
// first to ensure proper escaping because str_replace operates iteratively // first to ensure proper escaping because str_replace operates iteratively
// on the input arrays. This ordering of the characters avoids the use of strtr, // on the input arrays. This ordering of the characters avoids the use of strtr,
// which performs more slowly. // which performs more slowly.
private static $escapees = ['\\', '\\\\', '\\"', '"', private const ESCAPEES = ['\\', '\\\\', '\\"', '"',
"\x00", "\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07", "\x00", "\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07",
"\x08", "\x09", "\x0a", "\x0b", "\x0c", "\x0d", "\x0e", "\x0f", "\x08", "\x09", "\x0a", "\x0b", "\x0c", "\x0d", "\x0e", "\x0f",
"\x10", "\x11", "\x12", "\x13", "\x14", "\x15", "\x16", "\x17", "\x10", "\x11", "\x12", "\x13", "\x14", "\x15", "\x16", "\x17",
@ -36,7 +36,7 @@ class Escaper
"\x7f", "\x7f",
"\xc2\x85", "\xc2\xa0", "\xe2\x80\xa8", "\xe2\x80\xa9", "\xc2\x85", "\xc2\xa0", "\xe2\x80\xa8", "\xe2\x80\xa9",
]; ];
private static $escaped = ['\\\\', '\\"', '\\\\', '\\"', private const ESCAPED = ['\\\\', '\\"', '\\\\', '\\"',
'\\0', '\\x01', '\\x02', '\\x03', '\\x04', '\\x05', '\\x06', '\\a', '\\0', '\\x01', '\\x02', '\\x03', '\\x04', '\\x05', '\\x06', '\\a',
'\\b', '\\t', '\\n', '\\v', '\\f', '\\r', '\\x0e', '\\x0f', '\\b', '\\t', '\\n', '\\v', '\\f', '\\r', '\\x0e', '\\x0f',
'\\x10', '\\x11', '\\x12', '\\x13', '\\x14', '\\x15', '\\x16', '\\x17', '\\x10', '\\x11', '\\x12', '\\x13', '\\x14', '\\x15', '\\x16', '\\x17',
@ -66,7 +66,7 @@ class Escaper
*/ */
public static function escapeWithDoubleQuotes(string $value): string public static function escapeWithDoubleQuotes(string $value): string
{ {
return sprintf('"%s"', str_replace(self::$escapees, self::$escaped, $value)); return sprintf('"%s"', str_replace(self::ESCAPEES, self::ESCAPED, $value));
} }
/** /**