diff --git a/src/Repository.php b/src/Repository.php index 84a609d..55b9aa0 100644 --- a/src/Repository.php +++ b/src/Repository.php @@ -218,6 +218,13 @@ final class Repository } /** + * Builds a new model from $values and inserts it. + * + * `hydrate()` deliberately skips #[Guarded] properties, which is right for request payloads but + * wrong here: this method is called from trusted server code (a seeder, a service), and a guarded + * column such as a password hash would otherwise be silently dropped. Guarded values are applied + * after hydration, so `create()` can persist every column it is given. + * * @param array $values * @return T */ @@ -226,6 +233,23 @@ final class Repository /** @var T $model */ $model = new $this->class(); $model->hydrate($values); + + $metadata = $this->metadata(); + + foreach ($values as $key => $value) { + $property = $metadata->resolveProperty((string) $key); + + if ($property === null) { + continue; + } + + $definition = $metadata->propertyMetadata($property); + + if ($definition->guarded && !$definition->ignored && !$definition->primaryKey) { + $model->set($property, $model->castFor($definition, $value)); + } + } + $this->persister()->insert($model); return $model; diff --git a/tests/Unit/CreateWithGuardedTest.php b/tests/Unit/CreateWithGuardedTest.php new file mode 100644 index 0000000..8ed06cd --- /dev/null +++ b/tests/Unit/CreateWithGuardedTest.php @@ -0,0 +1,62 @@ +repository(CuentaDePrueba::class) + ->create([ + 'correo' => 'a@x', + 'passwordHash' => 'ARGON2ID', + ]); + + self::assertSame('ARGON2ID', $model->passwordHash); + self::assertStringContainsString('`password_hash`', $connection->lastSql()); + } + + #[Test] + public function hydrate_still_rejects_a_guarded_column_from_a_payload(): void + { + $model = new CuentaDePrueba()->hydrate([ + 'correo' => 'a@x', + 'passwordHash' => 'FROM-PAYLOAD', + ]); + + self::assertSame('', $model->passwordHash); + self::assertSame('a@x', $model->correo); + } +}