From 2a30ba221859176dbe583783da7299bde95c8956 Mon Sep 17 00:00:00 2001 From: Mark Scherer Date: Mon, 11 Mar 2024 18:36:39 +0100 Subject: [PATCH] Fix up bake value defaults for fixtures with enums (#982) * Fix up bake value defaults for fixtures with enums * Fix CS * Prevent runtime error. --- src/Command/FixtureCommand.php | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/Command/FixtureCommand.php b/src/Command/FixtureCommand.php index bd778a67..bf9a1d15 100644 --- a/src/Command/FixtureCommand.php +++ b/src/Command/FixtureCommand.php @@ -26,10 +26,13 @@ use Cake\Core\Configure; use Cake\Core\Exception\CakeException; use Cake\Database\Schema\TableSchemaInterface; +use Cake\Database\Type\EnumType; +use Cake\Database\TypeFactory; use Cake\Datasource\ConnectionManager; use Cake\Utility\Inflector; use Cake\Utility\Text; use DateTimeInterface; +use ReflectionEnum; /** * Task class for creating and updating fixtures files. @@ -419,6 +422,33 @@ protected function _generateRecords(TableSchemaInterface $table, int $recordCoun $insert = Text::uuid(); break; } + if (str_starts_with($fieldInfo['type'], 'enum-')) { + $insert = null; + if ($fieldInfo['default'] || $fieldInfo['null'] === false) { + $dbType = TypeFactory::build($fieldInfo['type']); + if ($dbType instanceof EnumType) { + $class = $dbType->getEnumClassName(); + $reflectionEnum = new ReflectionEnum($class); + $backingType = (string)$reflectionEnum->getBackingType(); + + if ($fieldInfo['default'] !== null) { + $insert = $fieldInfo['default']; + if ($backingType === 'int') { + $insert = (int)$insert; + } + } else { + $cases = $reflectionEnum->getCases(); + if ($cases) { + $firstCase = array_shift($cases); + /** @var \BackedEnum $firstValue */ + $firstValue = $firstCase->getValue(); + $insert = $firstValue->value; + } + } + } + } + } + $record[$field] = $insert; } $records[] = $record;