Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Application/Exception/BaseErrorHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ protected function json($exception, mixed $code = null): void
}

if (app_env("APP_ENV") != "production") {
$response["trace"] = $exception->getTrace();
$response["trace"] = $exception->getTraceAsString();
}

response()->status($status);
Expand Down
9 changes: 8 additions & 1 deletion src/Configuration/LoggerConfiguration.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,14 @@ private function loadFrontLogger(Logger $monolog, $error_handler): void

$handler = new CallbackHandler(
function ($exception, $inspector, $run) use ($monolog, $error_handler) {
$monolog->error($exception->getMessage(), $exception->getTrace());
$monolog->error($exception->getMessage(), [
'exception' => $exception::class,
'file' => $exception->getFile() . ':' . $exception->getLine(),
// A string trace: never serialize the frame args, which may
// hold objects whose jsonSerialize() runs a query (and would
// throw here on an already-aborted transaction).
'trace' => $exception->getTraceAsString(),
]);

$result = call_user_func_array([new $error_handler(), 'handle'], [$exception]);

Expand Down
5 changes: 5 additions & 0 deletions src/Database/Connection/Adapters/PostgreSQLAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ protected function makePdo(#[\SensitiveParameter] array $config): PDO
$options = [
PDO::ATTR_DEFAULT_FETCH_MODE => $config['fetch'] ?? $this->fetch,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
// Opt-in per connection. Behind a pooler a server-side prepared
// statement can outlive a schema change and fail with SQLSTATE
// 0A000 "cached plan must not change result type"; with emulated
// prepares nothing is cached on the server and PDO quotes values.
PDO::ATTR_EMULATE_PREPARES => (bool) ($config['emulate_prepares'] ?? false),
];

// Build the PDO connection
Expand Down
4 changes: 3 additions & 1 deletion src/Database/QueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -723,7 +723,9 @@ public function whereIn(string $column, array $range): QueryBuilder
$this->where_data_binding = array_merge($this->where_data_binding, $range);

$map = array_map(fn() => '?', $range);
$in = implode(', ', $map);
// An empty list is `in (null)`: valid SQL that matches no row,
// where `in ()` is a syntax error (SQLSTATE 42601).
$in = $range === [] ? 'null' : implode(', ', $map);
} else {
$in = (string) $range;
}
Expand Down
6 changes: 5 additions & 1 deletion src/Queue/Adapters/QueueAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,11 @@ protected function logError(Throwable $exception): void
error_log($exception->getMessage());

try {
logger()->error($exception->getMessage(), $exception->getTrace());
logger()->error($exception->getMessage(), [
'exception' => $exception::class,
'file' => $exception->getFile() . ':' . $exception->getLine(),
'trace' => $exception->getTraceAsString(),
]);
} catch (Throwable $loggerException) {
// Logger not available, already logged to error_log
}
Expand Down
2 changes: 1 addition & 1 deletion src/Validation/Rules/EmailRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ protected function compileEmail(string $key, string $masque): void
return;
}

if (Str::isMail($this->inputs[$key])) {
if (is_string($this->inputs[$key] ?? null) && Str::isMail($this->inputs[$key])) {
return;
}

Expand Down
29 changes: 28 additions & 1 deletion src/Validation/Rules/NullableRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,39 @@ protected function compileNullable(string $key, string $masque): bool
return false;
}

if (isset($this->inputs[$key]) && !Str::isEmpty($this->inputs[$key])) {
if (!$this->isBlankInput($this->inputs[$key] ?? null)) {
return false;
}

$this->inputs[$key] = null;

return true;
}

/**
* Whether a submitted value counts as "nothing was sent".
*
* Inputs arrive with their native type when the request body is JSON, so
* false, 0 and 0.0 are real values and must be validated by the rules that
* follow; only null, a blank string and an empty array are absent.
*
* @param mixed $value
* @return bool
*/
private function isBlankInput(mixed $value): bool
{
if ($value === null) {
return true;
}

if (is_string($value)) {
return Str::isEmpty($value);
}

if (is_array($value)) {
return $value === [];
}

return false;
}
}
44 changes: 37 additions & 7 deletions src/Validation/Rules/StringRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ protected function compileAlphaNum(string $key, string $masque): void
return;
}

if (Str::isAlphaNum($this->inputs[$key])) {
if (is_string($this->inputs[$key] ?? null) && Str::isAlphaNum($this->inputs[$key])) {
return;
}

Expand Down Expand Up @@ -205,7 +205,9 @@ protected function compileSize(string $key, string $masque): void

$length = (int)end($match);

if (Str::len($this->inputs[$key]) == $length) {
$size = $this->inputSize($key);

if ($size !== null && $size == $length) {
return;
}

Expand Down Expand Up @@ -240,7 +242,7 @@ protected function compileLower(string $key, string $masque): void
return;
}

if (Str::isLower($this->inputs[$key])) {
if (is_string($this->inputs[$key] ?? null) && Str::isLower($this->inputs[$key])) {
return;
}

Expand Down Expand Up @@ -269,7 +271,7 @@ protected function compileUpper(string $key, string $masque): void
return;
}

if (Str::isUpper($this->inputs[$key])) {
if (is_string($this->inputs[$key] ?? null) && Str::isUpper($this->inputs[$key])) {
return;
}

Expand Down Expand Up @@ -298,7 +300,7 @@ protected function compileAlpha(string $key, string $masque): void
return;
}

if (Str::isAlpha($this->inputs[$key])) {
if (is_string($this->inputs[$key] ?? null) && Str::isAlpha($this->inputs[$key])) {
return;
}

Expand Down Expand Up @@ -330,7 +332,9 @@ protected function compileMin(string $key, string $masque): void

$length = (int)end($match);

if (Str::len($this->inputs[$key]) >= $length) {
$size = $this->inputSize($key);

if ($size !== null && $size >= $length) {
return;
}

Expand Down Expand Up @@ -368,7 +372,9 @@ protected function compileMax(string $key, string $masque): void

$length = (int)end($match);

if (Str::len($this->inputs[$key]) <= $length) {
$size = $this->inputSize($key);

if ($size !== null && $size <= $length) {
return;
}

Expand Down Expand Up @@ -423,4 +429,28 @@ protected function compileSame(string $key, string $masque): void
"message" => $this->last_message
];
}

/**
* The quantity that min, max and size compare against their bound.
*
* Mirrors the convention documented by the between rule: a native number
* (as decoded from a JSON body) is compared by value, a string by its
* character length. Numeric strings keep length semantics so form inputs
* such as phone numbers or postal codes behave as before. Anything else
* (bool, array, object) yields null and fails the rule instead of
* throwing a TypeError from the string-typed Str helpers.
*
* @param string $key
* @return int|float|null
*/
private function inputSize(string $key): int|float|null
{
$value = $this->inputs[$key] ?? null;

return match (true) {
is_int($value) || is_float($value) => $value,
is_string($value) => Str::len($value),
default => null,
};
}
}
24 changes: 24 additions & 0 deletions tests/Database/ConnectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,30 @@ public function test_pgsql_pdo_connection()
$this->assertEquals('pgsql', $pdo->getAttribute(PDO::ATTR_DRIVER_NAME));
}

public function test_pgsql_emulate_prepares_is_off_by_default()
{
$pdo = static::$pgsqlAdapter->getConnection();

$this->assertFalse((bool) $pdo->getAttribute(PDO::ATTR_EMULATE_PREPARES));
}

/**
* Behind a connection pooler a server-side prepared statement can outlive a
* schema change and fail with SQLSTATE 0A000 "cached plan must not change
* result type". `emulate_prepares` lets a connection opt out of
* server-side prepares; PDO then quotes the values itself.
*/
public function test_pgsql_emulate_prepares_can_be_enabled_per_connection()
{
$config = static::$config["database"]['connections']['pgsql'];
$config['emulate_prepares'] = true;

$pdo = (new PostgreSQLAdapter($config))->getConnection();

$this->assertTrue((bool) $pdo->getAttribute(PDO::ATTR_EMULATE_PREPARES));
$this->assertEquals('pgsql', $pdo->getAttribute(PDO::ATTR_DRIVER_NAME));
}

public function test_pgsql_adapter_name()
{
$this->assertEquals('pgsql', static::$pgsqlAdapter->getName());
Expand Down
24 changes: 24 additions & 0 deletions tests/Database/Query/QueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,30 @@ public function test_where_rejects_unsafe_column_identifier()
$builder->where('1=1 UNION SELECT password FROM admins -- ', '=', 'x');
}

/**
* whereIn() with an empty list used to build `column in ()`, which is
* invalid SQL (SQLSTATE 42601). An empty list means "match nothing", and
* `in (null)` is valid everywhere and matches no row.
*/
public function test_where_in_with_empty_list_matches_nothing()
{
$pdo = new \PDO('sqlite::memory:');
$pdo->exec('create table users (id integer primary key, name text)');
$pdo->exec("insert into users (id, name) values (1, 'a'), (2, 'b')");

$builder = new QueryBuilder('users', $pdo);
$builder->whereIn('id', []);

$this->assertStringContainsString('id in (null)', $builder->toSql());

$property = (new \ReflectionObject($builder))->getProperty('where_data_binding');
$property->setAccessible(true);
$this->assertSame([], $property->getValue($builder));

$this->assertSame([], (array) (new QueryBuilder('users', $pdo))->whereIn('id', [])->get());
$this->assertCount(1, (array) (new QueryBuilder('users', $pdo))->whereIn('id', [2])->get());
}

/**
* SQL-injection guard: whereBetween must bind both bounds as placeholders
* instead of concatenating them into the statement.
Expand Down
Loading
Loading