mirror of
https://github.com/archtechx/tenancy.git
synced 2026-05-07 05:34:03 +00:00
Extract parameter validation into a trait
Also, use parameterAllowlist() instead of the static property (so that we can e.g. override it later in SQLiteDatabaseManager, since overriding the static property doesn't work).
This commit is contained in:
parent
182f3a2eb2
commit
d5087d19c5
2 changed files with 41 additions and 22 deletions
39
src/Database/Concerns/ValidatesSqlParameters.php
Normal file
39
src/Database/Concerns/ValidatesSqlParameters.php
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Database\Concerns;
|
||||
|
||||
use InvalidArgumentException;
|
||||
|
||||
// todo@validation this trait's name might be a bit misleading
|
||||
// it suggests validating parameters for SQL statements, but it is also used in SQLiteDatabaseManager to validate the database file name
|
||||
trait ValidatesSqlParameters
|
||||
{
|
||||
/**
|
||||
* Characters allowed in the parameters.
|
||||
*/
|
||||
protected static function parameterAllowlist(): string
|
||||
{
|
||||
return 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-';
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that parameters (database names, usernames, etc.)
|
||||
* contain only allowed characters before used in SQL statements.
|
||||
*
|
||||
* @throws InvalidArgumentException
|
||||
*/
|
||||
protected function validateParameter(string|array $parameters): string|array
|
||||
{
|
||||
foreach ((array) $parameters as $parameter) {
|
||||
foreach (str_split($parameter) as $char) {
|
||||
if (! str_contains(static::parameterAllowlist(), $char)) {
|
||||
throw new InvalidArgumentException("Invalid character '{$char}' in SQL parameter: {$parameter}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $parameters;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue