Browse Source

Merge pull request #16399 from cakephp/5.x-match

Use "match()" instead of "switch()".
Mark Story 4 years ago
parent
commit
af99cb4c91

+ 15 - 0
phpstan-baseline.neon

@@ -321,6 +321,21 @@ parameters:
 			path: src/TestSuite/TestEmailTransport.php
 
 		-
+			message: "#^Dead catch \\- UnhandledMatchError is never thrown in the try block\\.$#"
+			count: 1
+			path: src/Validation/Validation.php
+
+		-
+			message: "#^Match expression does not handle remaining value\\: string$#"
+			count: 1
+			path: src/Validation/Validation.php
+
+		-
+			message: "#^Unreachable statement \\- code above always terminates\\.$#"
+			count: 1
+			path: src/Validation/Validation.php
+
+		-
 			message: "#^Dead catch \\- Error is never thrown in the try block\\.$#"
 			count: 1
 			path: src/View/Cell.php

+ 7 - 15
src/Command/CompletionCommand.php

@@ -97,21 +97,13 @@ class CompletionCommand extends Command implements CommandCollectionAwareInterfa
      */
     public function execute(Arguments $args, ConsoleIo $io): ?int
     {
-        $mode = $args->getArgument('mode');
-        switch ($mode) {
-            case 'commands':
-                return $this->getCommands($args, $io);
-            case 'subcommands':
-                return $this->getSubcommands($args, $io);
-            case 'options':
-                return $this->getOptions($args, $io);
-            case 'fuzzy':
-                return static::CODE_SUCCESS;
-            default:
-                $io->err('Invalid mode chosen.');
-        }
-
-        return static::CODE_SUCCESS;
+        return match ($args->getArgument('mode')) {
+            'commands' => $this->getCommands($args, $io),
+            'subcommands' => $this->getSubcommands($args, $io),
+            'options' => $this->getOptions($args, $io),
+            'fuzzy' => static::CODE_SUCCESS,
+            default => $io->err('Invalid mode chosen.')
+        };
     }
 
     /**

+ 8 - 14
src/Controller/ControllerFactory.php

@@ -261,20 +261,14 @@ class ControllerFactory implements ControllerFactoryInterface, RequestHandlerInt
      */
     protected function coerceStringToType(string $argument, ReflectionNamedType $type): array|string|float|int|bool|null
     {
-        switch ($type->getName()) {
-            case 'string':
-                return $argument;
-            case 'float':
-                return is_numeric($argument) ? (float)$argument : null;
-            case 'int':
-                return ctype_digit($argument) ? (int)$argument : null;
-            case 'bool':
-                return $argument === '0' ? false : ($argument === '1' ? true : null);
-            case 'array':
-                return $argument === '' ? [] : explode(',', $argument);
-        }
-
-        return null;
+        return match ($type->getName()) {
+            'string' => $argument,
+            'float' => is_numeric($argument) ? (float)$argument : null,
+            'int' => ctype_digit($argument) ? (int)$argument : null,
+            'bool' => $argument === '0' ? false : ($argument === '1' ? true : null),
+            'array' => $argument === '' ? [] : explode(',', $argument),
+            default => null,
+        };
     }
 
     /**

+ 6 - 8
src/Database/Driver.php

@@ -487,14 +487,12 @@ abstract class Driver implements DriverInterface
      */
     public function supports(string $feature): bool
     {
-        switch ($feature) {
-            case static::FEATURE_DISABLE_CONSTRAINT_WITHOUT_TRANSACTION:
-            case static::FEATURE_QUOTE:
-            case static::FEATURE_SAVEPOINT:
-                return true;
-        }
-
-        return false;
+        return match ($feature) {
+            static::FEATURE_DISABLE_CONSTRAINT_WITHOUT_TRANSACTION,
+            static::FEATURE_QUOTE,
+            static::FEATURE_SAVEPOINT => true,
+            default => false,
+        };
     }
 
     /**

+ 10 - 12
src/Database/Driver/Mysql.php

@@ -209,18 +209,16 @@ class Mysql extends Driver
      */
     public function supports(string $feature): bool
     {
-        switch ($feature) {
-            case static::FEATURE_CTE:
-            case static::FEATURE_JSON:
-            case static::FEATURE_WINDOW:
-                return version_compare(
-                    $this->version(),
-                    $this->featureVersions[$this->serverType][$feature],
-                    '>='
-                );
-        }
-
-        return parent::supports($feature);
+        return match ($feature) {
+            static::FEATURE_CTE,
+            static::FEATURE_JSON,
+            static::FEATURE_WINDOW => version_compare(
+                $this->version(),
+                $this->featureVersions[$this->serverType][$feature],
+                '>='
+            ),
+            default => parent::supports($feature),
+        };
     }
 
     /**

+ 8 - 12
src/Database/Driver/Postgres.php

@@ -178,18 +178,14 @@ class Postgres extends Driver
      */
     public function supports(string $feature): bool
     {
-        switch ($feature) {
-            case static::FEATURE_CTE:
-            case static::FEATURE_JSON:
-            case static::FEATURE_TRUNCATE_WITH_CONSTRAINTS:
-            case static::FEATURE_WINDOW:
-                return true;
-
-            case static::FEATURE_DISABLE_CONSTRAINT_WITHOUT_TRANSACTION:
-                return false;
-        }
-
-        return parent::supports($feature);
+        return match ($feature) {
+            static::FEATURE_CTE,
+            static::FEATURE_JSON,
+            static::FEATURE_TRUNCATE_WITH_CONSTRAINTS,
+            static::FEATURE_WINDOW => true,
+            static::FEATURE_DISABLE_CONSTRAINT_WITHOUT_TRANSACTION => false,
+            default => parent::supports($feature),
+        };
     }
 
     /**

+ 10 - 14
src/Database/Driver/Sqlite.php

@@ -193,20 +193,16 @@ class Sqlite extends Driver
      */
     public function supports(string $feature): bool
     {
-        switch ($feature) {
-            case static::FEATURE_CTE:
-            case static::FEATURE_WINDOW:
-                return version_compare(
-                    $this->version(),
-                    $this->featureVersions[$feature],
-                    '>='
-                );
-
-            case static::FEATURE_TRUNCATE_WITH_CONSTRAINTS:
-                return true;
-        }
-
-        return parent::supports($feature);
+        return match ($feature) {
+            static::FEATURE_CTE,
+            static::FEATURE_WINDOW => version_compare(
+                $this->version(),
+                $this->featureVersions[$feature],
+                '>='
+            ),
+            static::FEATURE_TRUNCATE_WITH_CONSTRAINTS => true,
+            default => parent::supports($feature),
+        };
     }
 
     /**

+ 7 - 11
src/Database/Driver/Sqlserver.php

@@ -260,17 +260,13 @@ class Sqlserver extends Driver
      */
     public function supports(string $feature): bool
     {
-        switch ($feature) {
-            case static::FEATURE_CTE:
-            case static::FEATURE_TRUNCATE_WITH_CONSTRAINTS:
-            case static::FEATURE_WINDOW:
-                return true;
-
-            case static::FEATURE_QUOTE:
-                return $this->getPdo()->getAttribute(PDO::ATTR_DRIVER_NAME) !== 'odbc';
-        }
-
-        return parent::supports($feature);
+        return match ($feature) {
+            static::FEATURE_CTE,
+            static::FEATURE_TRUNCATE_WITH_CONSTRAINTS,
+            static::FEATURE_WINDOW => true,
+            static::FEATURE_QUOTE => $this->getPdo()->getAttribute(PDO::ATTR_DRIVER_NAME) !== 'odbc',
+            default => parent::supports($feature),
+        };
     }
 
     /**

+ 7 - 12
src/Database/Schema/SqlserverSchemaDialect.php

@@ -388,18 +388,13 @@ class SqlserverSchemaDialect extends SchemaDialect
      */
     protected function _convertOnClause(string $clause): string
     {
-        switch ($clause) {
-            case 'NO_ACTION':
-                return TableSchema::ACTION_NO_ACTION;
-            case 'CASCADE':
-                return TableSchema::ACTION_CASCADE;
-            case 'SET_NULL':
-                return TableSchema::ACTION_SET_NULL;
-            case 'SET_DEFAULT':
-                return TableSchema::ACTION_SET_DEFAULT;
-        }
-
-        return TableSchema::ACTION_SET_NULL;
+        return match ($clause) {
+            'NO_ACTION' => TableSchema::ACTION_NO_ACTION,
+            'CASCADE' => TableSchema::ACTION_CASCADE,
+            'SET_NULL' => TableSchema::ACTION_SET_NULL,
+            'SET_DEFAULT' => TableSchema::ACTION_SET_DEFAULT,
+            default => TableSchema::ACTION_SET_NULL,
+        };
     }
 
     /**

+ 8 - 14
src/Error/Debug/ConsoleFormatter.php

@@ -120,20 +120,14 @@ class ConsoleFormatter implements FormatterInterface
     protected function export(NodeInterface $var, int $indent): string
     {
         if ($var instanceof ScalarNode) {
-            switch ($var->getType()) {
-                case 'bool':
-                    return $this->style('const', $var->getValue() ? 'true' : 'false');
-                case 'null':
-                    return $this->style('const', 'null');
-                case 'string':
-                    return $this->style('string', "'" . (string)$var->getValue() . "'");
-                case 'int':
-                case 'float':
-                    return $this->style('visibility', "({$var->getType()})") .
-                        ' ' . $this->style('number', "{$var->getValue()}");
-                default:
-                    return "({$var->getType()}) {$var->getValue()}";
-            }
+            return match ($var->getType()) {
+                'bool' => $this->style('const', $var->getValue() ? 'true' : 'false'),
+                'null' => $this->style('const', 'null'),
+                'string' => $this->style('string', "'" . (string)$var->getValue() . "'"),
+                'int', 'float' => $this->style('visibility', "({$var->getType()})") .
+                        ' ' . $this->style('number', "{$var->getValue()}"),
+                default => "({$var->getType()}) {$var->getValue()}",
+            };
         }
         if ($var instanceof ArrayNode) {
             return $this->exportArray($var, $indent + 1);

+ 8 - 14
src/Error/Debug/HtmlFormatter.php

@@ -125,20 +125,14 @@ class HtmlFormatter implements FormatterInterface
     protected function export(NodeInterface $var, int $indent): string
     {
         if ($var instanceof ScalarNode) {
-            switch ($var->getType()) {
-                case 'bool':
-                    return $this->style('const', $var->getValue() ? 'true' : 'false');
-                case 'null':
-                    return $this->style('const', 'null');
-                case 'string':
-                    return $this->style('string', "'" . (string)$var->getValue() . "'");
-                case 'int':
-                case 'float':
-                    return $this->style('visibility', "({$var->getType()})") .
-                        ' ' . $this->style('number', "{$var->getValue()}");
-                default:
-                    return "({$var->getType()}) {$var->getValue()}";
-            }
+            return match ($var->getType()) {
+                'bool' => $this->style('const', $var->getValue() ? 'true' : 'false'),
+                'null' => $this->style('const', 'null'),
+                'string' => $this->style('string', "'" . (string)$var->getValue() . "'"),
+                'int', 'float' => $this->style('visibility', "({$var->getType()})") .
+                        ' ' . $this->style('number', "{$var->getValue()}"),
+                default => "({$var->getType()}) {$var->getValue()}",
+            };
         }
         if ($var instanceof ArrayNode) {
             return $this->exportArray($var, $indent + 1);

+ 6 - 10
src/Error/Debug/TextFormatter.php

@@ -71,16 +71,12 @@ TEXT;
     protected function export(NodeInterface $var, int $indent): string
     {
         if ($var instanceof ScalarNode) {
-            switch ($var->getType()) {
-                case 'bool':
-                    return $var->getValue() ? 'true' : 'false';
-                case 'null':
-                    return 'null';
-                case 'string':
-                    return "'" . (string)$var->getValue() . "'";
-                default:
-                    return "({$var->getType()}) {$var->getValue()}";
-            }
+            return match ($var->getType()) {
+                'bool' => $var->getValue() ? 'true' : 'false',
+                'null' => 'null',
+                'string' => "'" . (string)$var->getValue() . "'",
+                default => "({$var->getType()}) {$var->getValue()}",
+            };
         }
         if ($var instanceof ArrayNode) {
             return $this->exportArray($var, $indent + 1);

+ 8 - 16
src/Error/Debugger.php

@@ -688,22 +688,14 @@ class Debugger
             return new ScalarNode($type, $var);
         }
 
-        switch ($type) {
-            case 'float':
-            case 'string':
-            case 'null':
-                return new ScalarNode($type, $var);
-            case 'bool':
-                return new ScalarNode('bool', $var);
-            case 'int':
-                return new ScalarNode('int', $var);
-            case 'array':
-                return static::exportArray($var, $context->withAddedDepth());
-            case 'unknown':
-                return new SpecialNode('(unknown)');
-            default:
-                return static::exportObject($var, $context->withAddedDepth());
-        }
+        return match ($type) {
+            'float', 'string', 'null' => new ScalarNode($type, $var),
+            'bool' => new ScalarNode('bool', $var),
+            'int' => new ScalarNode('int', $var),
+            'array' => static::exportArray($var, $context->withAddedDepth()),
+            'unknown' => new SpecialNode('(unknown)'),
+            default => static::exportObject($var, $context->withAddedDepth()),
+        };
     }
 
     /**

+ 11 - 17
src/Http/Client/Adapter/Curl.php

@@ -170,23 +170,17 @@ class Curl implements AdapterInterface
      */
     protected function getProtocolVersion(RequestInterface $request): int
     {
-        switch ($request->getProtocolVersion()) {
-            case '1.0':
-                return CURL_HTTP_VERSION_1_0;
-            case '1.1':
-                return CURL_HTTP_VERSION_1_1;
-            case '2':
-            case '2.0':
-                if (defined('CURL_HTTP_VERSION_2TLS')) {
-                    return CURL_HTTP_VERSION_2TLS;
-                }
-                if (defined('CURL_HTTP_VERSION_2_0')) {
-                    return CURL_HTTP_VERSION_2_0;
-                }
-                throw new HttpException('libcurl 7.33 or greater required for HTTP/2 support');
-        }
-
-        return CURL_HTTP_VERSION_NONE;
+        return match ($request->getProtocolVersion()) {
+            '1.0' => CURL_HTTP_VERSION_1_0,
+            '1.1' => CURL_HTTP_VERSION_1_1,
+            '2', '2.0' => defined('CURL_HTTP_VERSION_2TLS')
+                ? CURL_HTTP_VERSION_2TLS
+                : (defined('CURL_HTTP_VERSION_2_0')
+                    ? CURL_HTTP_VERSION_2_0
+                    : throw new HttpException('libcurl 7.33 or greater required for HTTP/2 support')
+                ),
+            default => CURL_HTTP_VERSION_NONE,
+        };
     }
 
     /**

+ 8 - 12
src/I18n/Number.php

@@ -100,18 +100,14 @@ class Number
     {
         $size = (int)$size;
 
-        switch (true) {
-            case $size < 1024:
-                return __dn('cake', '{0,number,integer} Byte', '{0,number,integer} Bytes', $size, $size);
-            case round($size / 1024) < 1024:
-                return __d('cake', '{0,number,#,###.##} KB', $size / 1024);
-            case round($size / 1024 / 1024, 2) < 1024:
-                return __d('cake', '{0,number,#,###.##} MB', $size / 1024 / 1024);
-            case round($size / 1024 / 1024 / 1024, 2) < 1024:
-                return __d('cake', '{0,number,#,###.##} GB', $size / 1024 / 1024 / 1024);
-            default:
-                return __d('cake', '{0,number,#,###.##} TB', $size / 1024 / 1024 / 1024 / 1024);
-        }
+        return match (true) {
+            $size < 1024 => __dn('cake', '{0,number,integer} Byte', '{0,number,integer} Bytes', $size, $size),
+            round($size / 1024) < 1024 => __d('cake', '{0,number,#,###.##} KB', $size / 1024),
+            round($size / 1024 / 1024, 2) < 1024 => __d('cake', '{0,number,#,###.##} MB', $size / 1024 / 1024),
+            round($size / 1024 / 1024 / 1024, 2) < 1024 =>
+                __d('cake', '{0,number,#,###.##} GB', $size / 1024 / 1024 / 1024),
+            default => __d('cake', '{0,number,#,###.##} TB', $size / 1024 / 1024 / 1024 / 1024),
+        };
     }
 
     /**

+ 29 - 46
src/I18n/PluralRules.php

@@ -153,56 +153,39 @@ class PluralRules
             return 0;
         }
 
-        switch (static::$_rulesMap[$locale]) {
-            case 0:
-                return 0;
-            case 1:
-                return $n === 1 ? 0 : 1;
-            case 2:
-                return $n > 1 ? 1 : 0;
-            case 3:
-                return $n % 10 === 1 && $n % 100 !== 11 ? 0 :
-                    (($n % 10 >= 2 && $n % 10 <= 4) && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
-            case 4:
-                return $n === 1 ? 0 :
-                    ($n >= 2 && $n <= 4 ? 1 : 2);
-            case 5:
-                return $n === 1 ? 0 :
-                    ($n === 2 ? 1 : ($n < 7 ? 2 : ($n < 11 ? 3 : 4)));
-            case 6:
-                return $n % 10 === 1 && $n % 100 !== 11 ? 0 :
-                    ($n % 10 >= 2 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
-            case 7:
-                return $n % 100 === 1 ? 1 :
-                    ($n % 100 === 2 ? 2 : ($n % 100 === 3 || $n % 100 === 4 ? 3 : 0));
-            case 8:
-                return $n % 10 === 1 ? 0 : ($n % 10 === 2 ? 1 : 2);
-            case 9:
-                return $n === 1 ? 0 :
+        return match (static::$_rulesMap[$locale]) {
+            0 => 0,
+            1 => $n === 1 ? 0 : 1,
+            2 => $n > 1 ? 1 : 0,
+            3 => $n % 10 === 1 && $n % 100 !== 11 ? 0 :
+                    (($n % 10 >= 2 && $n % 10 <= 4) && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2),
+            4 => $n === 1 ? 0 :
+                    ($n >= 2 && $n <= 4 ? 1 : 2),
+            5 => $n === 1 ? 0 :
+                    ($n === 2 ? 1 : ($n < 7 ? 2 : ($n < 11 ? 3 : 4))),
+            6 => $n % 10 === 1 && $n % 100 !== 11 ? 0 :
+                    ($n % 10 >= 2 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2),
+            7 => $n % 100 === 1 ? 1 :
+                    ($n % 100 === 2 ? 2 : ($n % 100 === 3 || $n % 100 === 4 ? 3 : 0)),
+            8 => $n % 10 === 1 ? 0 : ($n % 10 === 2 ? 1 : 2),
+            9 => $n === 1 ? 0 :
                     ($n === 0 || ($n % 100 > 0 && $n % 100 <= 10) ? 1 :
-                    ($n % 100 > 10 && $n % 100 < 20 ? 2 : 3));
-            case 10:
-                return $n % 10 === 1 && $n % 100 !== 11 ? 0 : ($n !== 0 ? 1 : 2);
-            case 11:
-                return $n === 1 ? 0 :
-                    ($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
-            case 12:
-                return $n === 1 ? 0 :
-                    ($n === 0 || $n % 100 > 0 && $n % 100 < 20 ? 1 : 2);
-            case 13:
-                return $n === 0 ? 0 :
+                    ($n % 100 > 10 && $n % 100 < 20 ? 2 : 3)),
+            10 => $n % 10 === 1 && $n % 100 !== 11 ? 0 : ($n !== 0 ? 1 : 2),
+            11 => $n === 1 ? 0 :
+                    ($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2),
+            12 => $n === 1 ? 0 :
+                    ($n === 0 || $n % 100 > 0 && $n % 100 < 20 ? 1 : 2),
+            13 => $n === 0 ? 0 :
                     ($n === 1 ? 1 :
                     ($n === 2 ? 2 :
                     ($n % 100 >= 3 && $n % 100 <= 10 ? 3 :
-                    ($n % 100 >= 11 ? 4 : 5))));
-            case 14:
-                return $n === 1 ? 0 :
+                    ($n % 100 >= 11 ? 4 : 5)))),
+            14 => $n === 1 ? 0 :
                     ($n === 2 ? 1 :
-                    ($n !== 8 && $n !== 11 ? 2 : 3));
-            case 15:
-                return $n % 10 !== 1 || $n % 100 === 11 ? 1 : 0;
-        }
-
-        throw new CakeException('Unable to find plural rule number.');
+                    ($n !== 8 && $n !== 11 ? 2 : 3)),
+            15 => $n % 10 !== 1 || $n % 100 === 11 ? 1 : 0,
+            default => throw new CakeException('Unable to find plural rule number.'),
+        };
     }
 }

+ 6 - 10
src/Utility/Hash.php

@@ -208,16 +208,12 @@ class Hash
      */
     protected static function _matchToken(mixed $key, string $token): bool
     {
-        switch ($token) {
-            case '{n}':
-                return is_numeric($key);
-            case '{s}':
-                return is_string($key);
-            case '{*}':
-                return true;
-            default:
-                return is_numeric($token) ? ($key == $token) : $key === $token;
-        }
+        return match ($token) {
+            '{n}' => is_numeric($key),
+            '{s}' => is_string($key),
+            '{*}' => true,
+            default => is_numeric($token) ? ($key == $token) : $key === $token,
+        };
     }
 
     /**

+ 14 - 43
src/Validation/Validation.php

@@ -25,6 +25,7 @@ use LogicException;
 use NumberFormatter;
 use Psr\Http\Message\UploadedFileInterface;
 use RuntimeException;
+use UnhandledMatchError;
 
 /**
  * Validation Class. Used for validation of model data
@@ -344,49 +345,19 @@ class Validation
             return false;
         }
 
-        switch ($operator) {
-            case static::COMPARE_GREATER:
-                if ($check1 > $check2) {
-                    return true;
-                }
-                break;
-            case static::COMPARE_LESS:
-                if ($check1 < $check2) {
-                    return true;
-                }
-                break;
-            case static::COMPARE_GREATER_OR_EQUAL:
-                if ($check1 >= $check2) {
-                    return true;
-                }
-                break;
-            case static::COMPARE_LESS_OR_EQUAL:
-                if ($check1 <= $check2) {
-                    return true;
-                }
-                break;
-            case static::COMPARE_EQUAL:
-                if ($check1 == $check2) {
-                    return true;
-                }
-                break;
-            case static::COMPARE_NOT_EQUAL:
-                if ($check1 != $check2) {
-                    return true;
-                }
-                break;
-            case static::COMPARE_SAME:
-                if ($check1 === $check2) {
-                    return true;
-                }
-                break;
-            case static::COMPARE_NOT_SAME:
-                if ($check1 !== $check2) {
-                    return true;
-                }
-                break;
-            default:
-                static::$errors[] = 'You must define a valid $operator parameter for Validation::comparison()';
+        try {
+            return match ($operator) {
+                static::COMPARE_GREATER => $check1 > $check2,
+                static::COMPARE_LESS => $check1 < $check2,
+                static::COMPARE_GREATER_OR_EQUAL => $check1 >= $check2,
+                static::COMPARE_LESS_OR_EQUAL => $check1 <= $check2,
+                static::COMPARE_EQUAL => $check1 == $check2,
+                static::COMPARE_NOT_EQUAL => $check1 != $check2,
+                static::COMPARE_SAME => $check1 === $check2,
+                static::COMPARE_NOT_SAME => $check1 !== $check2,
+            };
+        } catch (UnhandledMatchError) {
+            static::$errors[] = 'You must define a valid $operator parameter for Validation::comparison()';
         }
 
         return false;