diff --git a/CHANGELOG.md b/CHANGELOG.md index 73d9ba35..d27c66a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## 1.0.1 under development - Enh #260: Typecast refactoring (@Tigrov) +- Enh #262: Refactoring of `Schema::normalizeDefaultValue()` method (@Tigrov) ## 1.0.0 April 12, 2023 diff --git a/src/Schema.php b/src/Schema.php index dae672a5..eb1286f9 100644 --- a/src/Schema.php +++ b/src/Schema.php @@ -25,10 +25,10 @@ use function explode; use function md5; use function preg_match; +use function preg_replace; use function serialize; use function strncasecmp; use function strtolower; -use function trim; /** * Implements the SQLite Server specific schema, supporting SQLite 3.3.0 or higher. @@ -505,20 +505,20 @@ protected function loadColumnSchema(array $info): ColumnSchemaInterface * @param ColumnSchemaInterface $column The column schema object. * * @return mixed The normalized default value. - * - * @psalm-suppress PossiblyNullArgument */ - private function normalizeDefaultValue(?string $defaultValue, ColumnSchemaInterface $column): mixed + private function normalizeDefaultValue(string|null $defaultValue, ColumnSchemaInterface $column): mixed { - if ($column->isPrimaryKey()) { + if ($column->isPrimaryKey() || in_array($defaultValue, [null, '', 'null', 'NULL'], true)) { return null; } - return match ($defaultValue) { - null, 'null', '' => null, - 'CURRENT_TIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIME' => new Expression($defaultValue), - default => $column->phpTypecast(trim($defaultValue, "'\"")), - }; + if (in_array($defaultValue, ['CURRENT_TIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIME'], true)) { + return new Expression($defaultValue); + } + + $value = preg_replace('/^([\'"])(.*)\1$/s', '$2', $defaultValue); + + return $column->phpTypecast($value); } /** diff --git a/tests/Provider/SchemaProvider.php b/tests/Provider/SchemaProvider.php index 17b32149..00c31596 100644 --- a/tests/Provider/SchemaProvider.php +++ b/tests/Provider/SchemaProvider.php @@ -90,7 +90,7 @@ public static function columns(): array 'size' => 100, 'precision' => 100, 'scale' => null, - 'defaultValue' => 'something', + 'defaultValue' => 'something"', ], 'char_col3' => [ 'type' => 'text', diff --git a/tests/Support/Fixture/sqlite.sql b/tests/Support/Fixture/sqlite.sql index 45de6756..04334a60 100644 --- a/tests/Support/Fixture/sqlite.sql +++ b/tests/Support/Fixture/sqlite.sql @@ -122,7 +122,7 @@ CREATE TABLE "type" ( tinyint_col TINYINT(3) DEFAULT '1', smallint_col SMALLINT(1) DEFAULT '1', char_col char(100) NOT NULL, - char_col2 varchar(100) DEFAULT 'something', + char_col2 varchar(100) DEFAULT 'something"', char_col3 text, float_col double(4,3) NOT NULL, float_col2 double DEFAULT '1.23',