Skip to content

Commit

Permalink
Fix up bake value defaults for fixtures with enums (#982)
Browse files Browse the repository at this point in the history
* Fix up bake value defaults for fixtures with enums

* Fix CS

* Prevent runtime error.
  • Loading branch information
dereuromark committed Mar 11, 2024
1 parent 63ae641 commit 2a30ba2
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/Command/FixtureCommand.php
Expand Up @@ -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.
Expand Down Expand Up @@ -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;
Expand Down

0 comments on commit 2a30ba2

Please sign in to comment.