From 318b5b9da2377d5707c572e837af4c3dec13a160 Mon Sep 17 00:00:00 2001 From: Dario Garcia Date: Sun, 15 Nov 2026 14:37:54 -0300 Subject: [PATCH] fix(criteria): compare backed enums by their scalar value Using an enum as a criteria value reached PDO as an object and failed with "Object of class X could not be converted to string". Filtering by a state column - the most natural thing to do with an enum-mapped property - was impossible. CriteriaCompiler now unwraps \BackedEnum both for a plain value and inside an an IN list. Covered by CriteriaCompilerEnumTest. --- src/Query/CriteriaCompiler.php | 11 +++- tests/Fixture/EstadoPedido.php | 11 ++++ tests/Unit/Query/CriteriaCompilerEnumTest.php | 53 +++++++++++++++++++ 3 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 tests/Fixture/EstadoPedido.php create mode 100644 tests/Unit/Query/CriteriaCompilerEnumTest.php diff --git a/src/Query/CriteriaCompiler.php b/src/Query/CriteriaCompiler.php index 71273c0..cc470d4 100644 --- a/src/Query/CriteriaCompiler.php +++ b/src/Query/CriteriaCompiler.php @@ -74,12 +74,21 @@ final class CriteriaCompiler return [$quotedColumn . ' IS NULL', []]; } + // A backed enum is compared by its scalar value: PDO cannot bind the enum instance itself. + if ($value instanceof \BackedEnum) { + return [$quotedColumn . ' = ?', [$value->value]]; + } + if (is_array($value)) { if ($value === []) { return ['1 = 0', []]; } - return $this->dialect->renderCondition($quotedColumn, Cond::in(array_values($value))); + $values = array_map(static fn(mixed $entry): mixed => $entry instanceof \BackedEnum + ? $entry->value + : $entry, array_values($value)); + + return $this->dialect->renderCondition($quotedColumn, Cond::in($values)); } return [$quotedColumn . ' = ?', [$value]]; diff --git a/tests/Fixture/EstadoPedido.php b/tests/Fixture/EstadoPedido.php new file mode 100644 index 0000000..65972ff --- /dev/null +++ b/tests/Fixture/EstadoPedido.php @@ -0,0 +1,11 @@ +compiler = new CriteriaCompiler(new MySqlDialect()); + } + + #[Test] + public function it_compiles_an_enum_criterion_to_its_scalar_value(): void + { + $metadata = new MetadataFactory()->forClass(ArticuloConEstado::class); + + [$sql, $params] = $this->compiler->compile($metadata, [ + 'estado' => EstadoPedido::Confirmado, + ]); + + self::assertSame('`estado` = ?', $sql); + self::assertSame(['confirmado'], $params); + } + + #[Test] + public function it_compiles_a_list_of_enums_to_their_scalar_values(): void + { + $metadata = new MetadataFactory()->forClass(ArticuloConEstado::class); + + [, $params] = $this->compiler->compile($metadata, [ + 'estado' => [EstadoPedido::Pendiente, EstadoPedido::Confirmado], + ]); + + self::assertSame(['pendiente', 'confirmado'], $params); + } +}