1
0
mirror of https://github.com/dg/dibi.git synced 2025-08-27 07:54:21 +02:00

coding style

This commit is contained in:
David Grudl
2020-10-28 16:38:16 +01:00
parent b27db4a9aa
commit 34a1665915
28 changed files with 216 additions and 154 deletions

View File

@@ -45,7 +45,7 @@ class Panel implements Tracy\IBarPanel
public function register(Dibi\Connection $connection): void
{
Tracy\Debugger::getBar()->addPanel($this);
Tracy\Debugger::getBlueScreen()->addPanel([__CLASS__, 'renderException']);
Tracy\Debugger::getBlueScreen()->addPanel([self::class, 'renderException']);
$connection->onEvent[] = [$this, 'logEvent'];
}
@@ -121,7 +121,9 @@ class Panel implements Tracy\IBarPanel
if ($this->explain && $event->type === Event::SELECT) {
$backup = [$connection->onEvent, \dibi::$numOfQueries, \dibi::$totalTime];
$connection->onEvent = null;
$cmd = is_string($this->explain) ? $this->explain : ($connection->getConfig('driver') === 'oracle' ? 'EXPLAIN PLAN FOR' : 'EXPLAIN');
$cmd = is_string($this->explain)
? $this->explain
: ($connection->getConfig('driver') === 'oracle' ? 'EXPLAIN PLAN FOR' : 'EXPLAIN');
try {
$explain = @Helpers::dump($connection->nativeQuery("$cmd $event->sql"), true);
} catch (Dibi\Exception $e) {
@@ -141,7 +143,7 @@ class Panel implements Tracy\IBarPanel
$s .= "<div id='tracy-debug-DibiProfiler-row-$counter' class='tracy-collapsed'>{$explain}</div>";
}
if ($event->source) {
$s .= Tracy\Helpers::editorLink($event->source[0], $event->source[1]);//->class('tracy-DibiProfiler-source');
$s .= Tracy\Helpers::editorLink($event->source[0], $event->source[1]); //->class('tracy-DibiProfiler-source');
}
$s .= "</td><td>{$event->count}</td>";

View File

@@ -562,7 +562,7 @@ class Connection implements IConnection
*/
public function __wakeup()
{
throw new NotSupportedException('You cannot serialize or unserialize ' . get_class($this) . ' instances.');
throw new NotSupportedException('You cannot serialize or unserialize ' . static::class . ' instances.');
}
@@ -571,7 +571,7 @@ class Connection implements IConnection
*/
public function __sleep()
{
throw new NotSupportedException('You cannot serialize or unserialize ' . get_class($this) . ' instances.');
throw new NotSupportedException('You cannot serialize or unserialize ' . static::class . ' instances.');
}

View File

@@ -53,11 +53,9 @@ class DataSource implements IDataSource
*/
public function __construct(string $sql, Connection $connection)
{
if (strpbrk($sql, " \t\r\n") === false) {
$this->sql = $connection->getDriver()->escapeIdentifier($sql); // table name
} else {
$this->sql = '(' . $sql . ') t'; // SQL command
}
$this->sql = strpbrk($sql, " \t\r\n") === false
? $connection->getDriver()->escapeIdentifier($sql) // table name
: '(' . $sql . ') t'; // SQL command
$this->connection = $connection;
}
@@ -84,12 +82,9 @@ class DataSource implements IDataSource
*/
public function where($cond): self
{
if (is_array($cond)) {
// TODO: not consistent with select and orderBy
$this->conds[] = $cond;
} else {
$this->conds[] = func_get_args();
}
$this->conds[] = is_array($cond)
? $cond // TODO: not consistent with select and orderBy
: func_get_args();
$this->result = $this->count = null;
return $this;
}
@@ -232,12 +227,18 @@ class DataSource implements IDataSource
public function __toString(): string
{
try {
return $this->connection->translate('
SELECT %n', (empty($this->cols) ? '*' : $this->cols), '
FROM %SQL', $this->sql, '
%ex', $this->conds ? ['WHERE %and', $this->conds] : null, '
%ex', $this->sorting ? ['ORDER BY %by', $this->sorting] : null, '
%ofs %lmt', $this->offset, $this->limit
return $this->connection->translate(
"\nSELECT %n",
(empty($this->cols) ? '*' : $this->cols),
"\nFROM %SQL",
$this->sql,
"\n%ex",
$this->conds ? ['WHERE %and', $this->conds] : null,
"\n%ex",
$this->sorting ? ['ORDER BY %by', $this->sorting] : null,
"\n%ofs %lmt",
$this->offset,
$this->limit
);
} catch (\Throwable $e) {
trigger_error($e->getMessage(), E_USER_ERROR);

View File

@@ -62,11 +62,9 @@ class FirebirdDriver implements Dibi\Driver
'buffers' => 0,
];
if (empty($config['persistent'])) {
$this->connection = @ibase_connect($config['database'], $config['username'], $config['password'], $config['charset'], $config['buffers']); // intentionally @
} else {
$this->connection = @ibase_pconnect($config['database'], $config['username'], $config['password'], $config['charset'], $config['buffers']); // intentionally @
}
$this->connection = empty($config['persistent'])
? @ibase_connect($config['database'], $config['username'], $config['password'], $config['charset'], $config['buffers']) // intentionally @
: @ibase_pconnect($config['database'], $config['username'], $config['password'], $config['charset'], $config['buffers']); // intentionally @
if (!is_resource($this->connection)) {
throw new Dibi\DriverException(ibase_errmsg(), ibase_errcode());
@@ -90,7 +88,9 @@ class FirebirdDriver implements Dibi\Driver
*/
public function query(string $sql): ?Dibi\ResultDriver
{
$resource = $this->inTransaction ? $this->transaction : $this->connection;
$resource = $this->inTransaction
? $this->transaction
: $this->connection;
$res = ibase_query($resource, $sql);
if ($res === false) {

View File

@@ -38,8 +38,8 @@ class FirebirdReflector implements Dibi\Reflector
SELECT TRIM(RDB\$RELATION_NAME),
CASE RDB\$VIEW_BLR WHEN NULL THEN 'TRUE' ELSE 'FALSE' END
FROM RDB\$RELATIONS
WHERE RDB\$SYSTEM_FLAG = 0;"
);
WHERE RDB\$SYSTEM_FLAG = 0;
");
$tables = [];
while ($row = $res->fetch(false)) {
$tables[] = [
@@ -84,9 +84,8 @@ class FirebirdReflector implements Dibi\Reflector
FROM RDB\$RELATION_FIELDS r
LEFT JOIN RDB\$FIELDS f ON r.RDB\$FIELD_SOURCE = f.RDB\$FIELD_NAME
WHERE r.RDB\$RELATION_NAME = '$table'
ORDER BY r.RDB\$FIELD_POSITION;"
);
ORDER BY r.RDB\$FIELD_POSITION;
");
$columns = [];
while ($row = $res->fetch(true)) {
$key = $row['FIELD_NAME'];
@@ -121,8 +120,8 @@ class FirebirdReflector implements Dibi\Reflector
LEFT JOIN RDB\$INDICES i ON i.RDB\$INDEX_NAME = s.RDB\$INDEX_NAME
LEFT JOIN RDB\$RELATION_CONSTRAINTS r ON r.RDB\$INDEX_NAME = s.RDB\$INDEX_NAME
WHERE UPPER(i.RDB\$RELATION_NAME) = '$table'
ORDER BY s.RDB\$FIELD_POSITION"
);
ORDER BY s.RDB\$FIELD_POSITION
");
$indexes = [];
while ($row = $res->fetch(true)) {
$key = $row['INDEX_NAME'];
@@ -149,8 +148,8 @@ class FirebirdReflector implements Dibi\Reflector
LEFT JOIN RDB\$RELATION_CONSTRAINTS r ON r.RDB\$INDEX_NAME = s.RDB\$INDEX_NAME
WHERE UPPER(i.RDB\$RELATION_NAME) = '$table'
AND r.RDB\$CONSTRAINT_TYPE = 'FOREIGN KEY'
ORDER BY s.RDB\$FIELD_POSITION"
);
ORDER BY s.RDB\$FIELD_POSITION
");
$keys = [];
while ($row = $res->fetch(true)) {
$key = $row['INDEX_NAME'];
@@ -174,8 +173,8 @@ class FirebirdReflector implements Dibi\Reflector
FROM RDB\$INDICES
WHERE RDB\$RELATION_NAME = UPPER('$table')
AND RDB\$UNIQUE_FLAG IS NULL
AND RDB\$FOREIGN_KEY IS NULL;"
);
AND RDB\$FOREIGN_KEY IS NULL;
");
$indices = [];
while ($row = $res->fetch(false)) {
$indices[] = $row[0];
@@ -196,8 +195,8 @@ class FirebirdReflector implements Dibi\Reflector
AND (
RDB\$UNIQUE_FLAG IS NOT NULL
OR RDB\$FOREIGN_KEY IS NOT NULL
);"
);
);
");
$constraints = [];
while ($row = $res->fetch(false)) {
$constraints[] = $row[0];
@@ -212,7 +211,8 @@ class FirebirdReflector implements Dibi\Reflector
*/
public function getTriggersMeta(string $table = null): array
{
$res = $this->driver->query("
$res = $this->driver->query(
"
SELECT TRIM(RDB\$TRIGGER_NAME) AS TRIGGER_NAME,
TRIM(RDB\$RELATION_NAME) AS TABLE_NAME,
CASE RDB\$TRIGGER_TYPE
@@ -261,7 +261,9 @@ class FirebirdReflector implements Dibi\Reflector
$q = 'SELECT TRIM(RDB$TRIGGER_NAME)
FROM RDB$TRIGGERS
WHERE RDB$SYSTEM_FLAG = 0';
$q .= $table === null ? ';' : " AND RDB\$RELATION_NAME = UPPER('$table')";
$q .= $table === null
? ';'
: " AND RDB\$RELATION_NAME = UPPER('$table')";
$res = $this->driver->query($q);
$triggers = [];
@@ -307,8 +309,8 @@ class FirebirdReflector implements Dibi\Reflector
p.RDB\$PARAMETER_NUMBER AS PARAMETER_NUMBER
FROM RDB\$PROCEDURE_PARAMETERS p
LEFT JOIN RDB\$FIELDS f ON f.RDB\$FIELD_NAME = p.RDB\$FIELD_SOURCE
ORDER BY p.RDB\$PARAMETER_TYPE, p.RDB\$PARAMETER_NUMBER;"
);
ORDER BY p.RDB\$PARAMETER_TYPE, p.RDB\$PARAMETER_NUMBER;
");
$procedures = [];
while ($row = $res->fetch(true)) {
$key = $row['PROCEDURE_NAME'];
@@ -330,8 +332,8 @@ class FirebirdReflector implements Dibi\Reflector
{
$res = $this->driver->query('
SELECT TRIM(RDB$PROCEDURE_NAME)
FROM RDB$PROCEDURES;'
);
FROM RDB$PROCEDURES;
');
$procedures = [];
while ($row = $res->fetch(false)) {
$procedures[] = $row[0];
@@ -348,8 +350,8 @@ class FirebirdReflector implements Dibi\Reflector
$res = $this->driver->query('
SELECT TRIM(RDB$GENERATOR_NAME)
FROM RDB$GENERATORS
WHERE RDB$SYSTEM_FLAG = 0;'
);
WHERE RDB$SYSTEM_FLAG = 0;
');
$generators = [];
while ($row = $res->fetch(false)) {
$generators[] = $row[0];
@@ -366,8 +368,8 @@ class FirebirdReflector implements Dibi\Reflector
$res = $this->driver->query('
SELECT TRIM(RDB$FUNCTION_NAME)
FROM RDB$FUNCTIONS
WHERE RDB$SYSTEM_FLAG = 0;'
);
WHERE RDB$SYSTEM_FLAG = 0;
');
$functions = [];
while ($row = $res->fetch(false)) {
$functions[] = $row[0];

View File

@@ -62,7 +62,9 @@ class FirebirdResult implements Dibi\ResultDriver
*/
public function fetch(bool $assoc): ?array
{
$result = $assoc ? @ibase_fetch_assoc($this->resultSet, IBASE_TEXT) : @ibase_fetch_row($this->resultSet, IBASE_TEXT); // intentionally @
$result = $assoc
? @ibase_fetch_assoc($this->resultSet, IBASE_TEXT)
: @ibase_fetch_row($this->resultSet, IBASE_TEXT); // intentionally @
if (ibase_errcode()) {
if (ibase_errcode() == FirebirdDriver::ERROR_EXCEPTION_THROWN) {

View File

@@ -200,7 +200,9 @@ class MySqliDriver implements Dibi\Driver
*/
public function getAffectedRows(): ?int
{
return $this->connection->affected_rows === -1 ? null : $this->connection->affected_rows;
return $this->connection->affected_rows === -1
? null
: $this->connection->affected_rows;
}

View File

@@ -54,11 +54,9 @@ class OdbcDriver implements Dibi\Driver
'dsn' => ini_get('odbc.default_db'),
];
if (empty($config['persistent'])) {
$this->connection = @odbc_connect($config['dsn'], $config['username'] ?? '', $config['password'] ?? ''); // intentionally @
} else {
$this->connection = @odbc_pconnect($config['dsn'], $config['username'] ?? '', $config['password'] ?? ''); // intentionally @
}
$this->connection = empty($config['persistent'])
? @odbc_connect($config['dsn'], $config['username'] ?? '', $config['password'] ?? '') // intentionally @
: @odbc_pconnect($config['dsn'], $config['username'] ?? '', $config['password'] ?? ''); // intentionally @
}
if (!is_resource($this->connection)) {
@@ -94,7 +92,9 @@ class OdbcDriver implements Dibi\Driver
} elseif (is_resource($res)) {
$this->affectedRows = Dibi\Helpers::false2Null(odbc_num_rows($res));
return odbc_num_fields($res) ? $this->createResultDriver($res) : null;
return odbc_num_fields($res)
? $this->createResultDriver($res)
: null;
}
return null;
}

View File

@@ -96,7 +96,9 @@ class OracleDriver implements Dibi\Driver
} elseif (is_resource($res)) {
$this->affectedRows = Dibi\Helpers::false2Null(oci_num_rows($res));
return oci_num_fields($res) ? $this->createResultDriver($res) : null;
return oci_num_fields($res)
? $this->createResultDriver($res)
: null;
}
} else {
$err = oci_error($this->connection);

View File

@@ -234,21 +234,17 @@ class PdoDriver implements Dibi\Driver
*/
public function escapeText(string $value): string
{
if ($this->driverName === 'odbc') {
return "'" . str_replace("'", "''", $value) . "'";
} else {
return $this->connection->quote($value, PDO::PARAM_STR);
}
return $this->driverName === 'odbc'
? "'" . str_replace("'", "''", $value) . "'"
: $this->connection->quote($value, PDO::PARAM_STR);
}
public function escapeBinary(string $value): string
{
if ($this->driverName === 'odbc') {
return "'" . str_replace("'", "''", $value) . "'";
} else {
return $this->connection->quote($value, PDO::PARAM_LOB);
}
return $this->driverName === 'odbc'
? "'" . str_replace("'", "''", $value) . "'"
: $this->connection->quote($value, PDO::PARAM_LOB);
}

View File

@@ -85,7 +85,7 @@ class PdoResult implements Dibi\ResultDriver
if ($row === false) {
throw new Dibi\NotSupportedException('Driver does not support meta data.');
}
$row = $row + [
$row += [
'table' => null,
'native_type' => 'VAR_STRING',
];

View File

@@ -68,11 +68,9 @@ class PostgreDriver implements Dibi\Driver
set_error_handler(function (int $severity, string $message) use (&$error) {
$error = $message;
});
if (empty($config['persistent'])) {
$this->connection = pg_connect($string, $connectType);
} else {
$this->connection = pg_pconnect($string, $connectType);
}
$this->connection = empty($config['persistent'])
? pg_connect($string, $connectType)
: pg_pconnect($string, $connectType);
restore_error_handler();
}
@@ -171,12 +169,9 @@ class PostgreDriver implements Dibi\Driver
*/
public function getInsertId(?string $sequence): ?int
{
if ($sequence === null) {
// PostgreSQL 8.1 is needed
$res = $this->query('SELECT LASTVAL()');
} else {
$res = $this->query("SELECT CURRVAL('$sequence')");
}
$res = $sequence === null
? $this->query('SELECT LASTVAL()') // PostgreSQL 8.1 is needed
: $this->query("SELECT CURRVAL('$sequence')");
if (!$res) {
return null;

View File

@@ -251,7 +251,10 @@ class PostgreReflector implements Dibi\Reflector
$references[$row['name']] = array_combine($l, $f);
}
if (isset($references[$row['name']][$row['lnum']]) && $references[$row['name']][$row['lnum']] === $row['fnum']) {
if (
isset($references[$row['name']][$row['lnum']])
&& $references[$row['name']][$row['lnum']] === $row['fnum']
) {
$fKeys[$row['name']]['local'][] = $row['local'];
$fKeys[$row['name']]['foreign'][] = $row['foreign'];
}

View File

@@ -97,7 +97,9 @@ class PostgreResult implements Dibi\ResultDriver
'table' => pg_field_table($this->resultSet, $i),
'nativetype' => pg_field_type($this->resultSet, $i),
];
$row['fullname'] = $row['table'] ? $row['table'] . '.' . $row['name'] : $row['name'];
$row['fullname'] = $row['table']
? $row['table'] . '.' . $row['name']
: $row['name'];
$columns[] = $row;
}
return $columns;

View File

@@ -286,8 +286,12 @@ class SqliteDriver implements Dibi\Driver
/**
* Registers an aggregating user defined function for use in SQL statements.
*/
public function registerAggregateFunction(string $name, callable $rowCallback, callable $agrCallback, int $numArgs = -1): void
{
public function registerAggregateFunction(
string $name,
callable $rowCallback,
callable $agrCallback,
int $numArgs = -1
): void {
$this->connection->createAggregate($name, $rowCallback, $agrCallback, $numArgs);
}
}

View File

@@ -98,7 +98,9 @@ class SqlsrvDriver implements Dibi\Driver
} elseif (is_resource($res)) {
$this->affectedRows = Helpers::false2Null(sqlsrv_rows_affected($res));
return sqlsrv_num_fields($res) ? $this->createResultDriver($res) : null;
return sqlsrv_num_fields($res)
? $this->createResultDriver($res)
: null;
}
return null;
}

View File

@@ -119,7 +119,7 @@ class Fluent implements IDataSource
$this->connection = $connection;
if (self::$normalizer === null) {
self::$normalizer = new HashMap([__CLASS__, '_formatClause']);
self::$normalizer = new HashMap([self::class, '_formatClause']);
}
}
@@ -311,11 +311,9 @@ class Fluent implements IDataSource
*/
public function fetch()
{
if ($this->command === 'SELECT' && !$this->clauses['LIMIT']) {
return $this->query($this->_export(null, ['%lmt', 1]))->fetch();
} else {
return $this->query($this->_export())->fetch();
}
return $this->command === 'SELECT' && !$this->clauses['LIMIT']
? $this->query($this->_export(null, ['%lmt', 1]))->fetch()
: $this->query($this->_export())->fetch();
}
@@ -325,11 +323,9 @@ class Fluent implements IDataSource
*/
public function fetchSingle()
{
if ($this->command === 'SELECT' && !$this->clauses['LIMIT']) {
return $this->query($this->_export(null, ['%lmt', 1]))->fetchSingle();
} else {
return $this->query($this->_export())->fetchSingle();
}
return $this->command === 'SELECT' && !$this->clauses['LIMIT']
? $this->query($this->_export(null, ['%lmt', 1]))->fetchSingle()
: $this->query($this->_export())->fetchSingle();
}

View File

@@ -205,7 +205,7 @@ class Helpers
public static function getTypeCache(): HashMap
{
if (self::$types === null) {
self::$types = new HashMap([__CLASS__, 'detectType']);
self::$types = new HashMap([self::class, 'detectType']);
}
return self::$types;
}

View File

@@ -72,7 +72,9 @@ class Column
public function getTableName(): ?string
{
return isset($this->info['table']) && $this->info['table'] != null ? $this->info['table'] : null; // intentionally ==
return isset($this->info['table']) && $this->info['table'] != null // intentionally ==
? $this->info['table']
: null;
}

View File

@@ -82,7 +82,9 @@ class Result
{
if ($this->columns === null) {
$this->columns = [];
$reflector = $this->driver instanceof Dibi\Reflector ? $this->driver : null;
$reflector = $this->driver instanceof Dibi\Reflector
? $this->driver
: null;
foreach ($this->driver->getResultColumns() as $info) {
$this->columns[] = $this->names[strtolower($info['name'])] = new Column($reflector, $info);
}

View File

@@ -83,7 +83,9 @@ class Result implements IDataSource
*/
final public function seek(int $row): bool
{
return ($row !== 0 || $this->fetched) ? $this->getResultDriver()->seek($row) : true;
return ($row !== 0 || $this->fetched)
? $this->getResultDriver()->seek($row)
: true;
}
@@ -199,7 +201,7 @@ class Result implements IDataSource
*/
final public function fetchAll(int $offset = null, int $limit = null): array
{
$limit = $limit === null ? -1 : $limit;
$limit = $limit ?? -1;
$this->seek($offset ?: 0);
$row = $this->fetch();
if (!$row) {
@@ -357,11 +359,9 @@ class Result implements IDataSource
}
if ($x === null) { // build leaf
if ($leaf === '=') {
$x = $row->toArray();
} else {
$x = $row;
}
$x = $leaf === '='
? $row->toArray()
: $row;
}
} while ($row = $this->fetch());
@@ -485,7 +485,9 @@ class Result implements IDataSource
} elseif ($type === Type::DATETIME || $type === Type::DATE || $type === Type::TIME) {
if ($value && substr((string) $value, 0, 3) !== '000') { // '', null, false, '0000-00-00', ...
$value = new DateTime($value);
$row[$key] = empty($this->formats[$type]) ? $value : $value->format($this->formats[$type]);
$row[$key] = empty($this->formats[$type])
? $value
: $value->format($this->formats[$type]);
} else {
$row[$key] = null;
}
@@ -496,7 +498,9 @@ class Result implements IDataSource
$row[$key]->invert = (int) (bool) $m[1];
} elseif ($type === Type::BINARY) {
$row[$key] = is_string($value) ? $this->getResultDriver()->unescapeBinary($value) : $value;
$row[$key] = is_string($value)
? $this->getResultDriver()->unescapeBinary($value)
: $value;
} elseif ($type === Type::JSON) {
if ($this->formats[$type] === 'string') {

View File

@@ -29,10 +29,12 @@ trait Strict
*/
public function __call(string $name, array $args)
{
$class = method_exists($this, $name) ? 'parent' : get_class($this);
$class = method_exists($this, $name) ? 'parent' : static::class;
$items = (new ReflectionClass($this))->getMethods(ReflectionMethod::IS_PUBLIC);
$items = array_map(function ($item) { return $item->getName(); }, $items);
$hint = ($t = Helpers::getSuggestion($items, $name)) ? ", did you mean $t()?" : '.';
$hint = ($t = Helpers::getSuggestion($items, $name))
? ", did you mean $t()?"
: '.';
throw new \LogicException("Call to undefined method $class::$name()$hint");
}
@@ -43,10 +45,12 @@ trait Strict
*/
public static function __callStatic(string $name, array $args)
{
$rc = new ReflectionClass(get_called_class());
$rc = new ReflectionClass(static::class);
$items = array_intersect($rc->getMethods(ReflectionMethod::IS_PUBLIC), $rc->getMethods(ReflectionMethod::IS_STATIC));
$items = array_map(function ($item) { return $item->getName(); }, $items);
$hint = ($t = Helpers::getSuggestion($items, $name)) ? ", did you mean $t()?" : '.';
$hint = ($t = Helpers::getSuggestion($items, $name))
? ", did you mean $t()?"
: '.';
throw new \LogicException("Call to undefined static method {$rc->getName()}::$name()$hint");
}
@@ -66,7 +70,9 @@ trait Strict
$rc = new ReflectionClass($this);
$items = array_diff($rc->getProperties(ReflectionProperty::IS_PUBLIC), $rc->getProperties(ReflectionProperty::IS_STATIC));
$items = array_map(function ($item) { return $item->getName(); }, $items);
$hint = ($t = Helpers::getSuggestion($items, $name)) ? ", did you mean $$t?" : '.';
$hint = ($t = Helpers::getSuggestion($items, $name))
? ", did you mean $$t?"
: '.';
throw new \LogicException("Attempt to read undeclared property {$rc->getName()}::$$name$hint");
}
@@ -80,7 +86,9 @@ trait Strict
$rc = new ReflectionClass($this);
$items = array_diff($rc->getProperties(ReflectionProperty::IS_PUBLIC), $rc->getProperties(ReflectionProperty::IS_STATIC));
$items = array_map(function ($item) { return $item->getName(); }, $items);
$hint = ($t = Helpers::getSuggestion($items, $name)) ? ", did you mean $$t?" : '.';
$hint = ($t = Helpers::getSuggestion($items, $name))
? ", did you mean $$t?"
: '.';
throw new \LogicException("Attempt to write to undeclared property {$rc->getName()}::$$name$hint");
}
@@ -97,7 +105,7 @@ trait Strict
*/
public function __unset(string $name)
{
$class = get_class($this);
$class = static::class;
throw new \LogicException("Attempt to unset undeclared property $class::$$name.");
}
}

View File

@@ -93,7 +93,8 @@ final class Translator
} else {
$sql[] = substr($arg, 0, $toSkip)
// note: this can change $this->args & $this->cursor & ...
. preg_replace_callback(<<<'XX'
. preg_replace_callback(
<<<'XX'
/
(?=[`['":%?]) ## speed-up
(?:
@@ -323,7 +324,13 @@ XX
} elseif ($value instanceof Expression && $modifier === 'ex') {
return $this->connection->translate(...$value->getValues());
} elseif ($value instanceof \DateTimeInterface && ($modifier === 'd' || $modifier === 't' || $modifier === 'dt')) {
} elseif (
$value instanceof \DateTimeInterface
&& ($modifier === 'd'
|| $modifier === 't'
|| $modifier === 'dt'
)
) {
// continue
} else {
$type = is_object($value) ? get_class($value) : gettype($value);
@@ -333,13 +340,19 @@ XX
switch ($modifier) {
case 's': // string
return $value === null ? 'NULL' : $this->driver->escapeText((string) $value);
return $value === null
? 'NULL'
: $this->driver->escapeText((string) $value);
case 'bin':// binary
return $value === null ? 'NULL' : $this->driver->escapeBinary($value);
return $value === null
? 'NULL'
: $this->driver->escapeBinary($value);
case 'b': // boolean
return $value === null ? 'NULL' : $this->driver->escapeBool((bool) $value);
return $value === null
? 'NULL'
: $this->driver->escapeBool((bool) $value);
case 'sN': // string or null
case 'sn':
@@ -387,7 +400,9 @@ XX
} elseif (!$value instanceof \DateTimeInterface) {
$value = new DateTime($value);
}
return $modifier === 'd' ? $this->driver->escapeDate($value) : $this->driver->escapeDateTime($value);
return $modifier === 'd'
? $this->driver->escapeDate($value)
: $this->driver->escapeDateTime($value);
case 'by':
case 'n': // composed identifier name
@@ -403,7 +418,8 @@ XX
$toSkip = strcspn($value, '`[\'":');
if (strlen($value) !== $toSkip) {
$value = substr($value, 0, $toSkip)
. preg_replace_callback(<<<'XX'
. preg_replace_callback(
<<<'XX'
/
(?=[`['":])
(?:
@@ -611,7 +627,9 @@ XX
if ($matches[8]) { // SQL identifier substitution
$m = substr($matches[8], 0, -1);
$m = $this->connection->getSubstitutes()->$m;
return $matches[9] == '' ? $this->formatValue($m, null) : $m . $matches[9]; // value or identifier
return $matches[9] == ''
? $this->formatValue($m, null)
: $m . $matches[9]; // value or identifier
}
throw new \Exception('this should be never executed');

View File

@@ -30,6 +30,6 @@ class Type
final public function __construct()
{
throw new \LogicException('Cannot instantiate static class ' . __CLASS__);
throw new \LogicException('Cannot instantiate static class ' . self::class);
}
}

View File

@@ -75,7 +75,7 @@ class dibi
*/
final public function __construct()
{
throw new LogicException('Cannot instantiate static class ' . get_class($this));
throw new LogicException('Cannot instantiate static class ' . static::class);
}

View File

@@ -23,7 +23,9 @@ Assert::equal(1, $conn->getInsertId());
$conn->query(
'CREATE TRIGGER %n ON %n AFTER INSERT AS INSERT INTO %n DEFAULT VALUES',
'UpdAAB', 'aab', 'aaa'
'UpdAAB',
'aab',
'aaa'
);
$conn->query('INSERT INTO %n DEFAULT VALUES', 'aab');

View File

@@ -19,12 +19,17 @@ Assert::same(
SELECT *
FROM [customers]
/* WHERE ... LIKE ... */'),
$conn->translate('
$conn->translate(
'
SELECT *
FROM [customers]
%if', isset($name), 'WHERE [name] LIKE %s', 'xxx', '%end'
));
%if',
isset($name),
'WHERE [name] LIKE %s',
'xxx',
'%end'
)
);
// if & else & end (last end is optional)
@@ -32,11 +37,14 @@ Assert::same(
reformat('
SELECT *
FROM [customers] /* ... */'),
$conn->translate('
$conn->translate(
'
SELECT *
FROM %if', true, '[customers] %else [products]'
));
FROM %if',
true,
'[customers] %else [products]'
)
);
// if & else & (optional) end
@@ -48,14 +56,14 @@ WHERE [id] > 0
/* AND ...=...
*/ AND [bar]=1
'),
$conn->translate('
SELECT *
FROM [people]
WHERE [id] > 0
%if', false, 'AND [foo]=%i', 1, '
%else %if', true, 'AND [bar]=%i', 1, '
'));
')
);
// nested condition
@@ -76,24 +84,35 @@ WHERE
/* AND ...=1 */
/* 1 LIMIT 10 */",
]),
$conn->translate('
$conn->translate(
'
SELECT *
FROM [customers]
WHERE
%if', true, '[name] LIKE %s', 'xxx', '
%if', false, 'AND [admin]=1 %end
%if',
true,
'[name] LIKE %s',
'xxx',
'
%if',
false,
'AND [admin]=1 %end
%else 1 LIMIT 10 %end'
));
)
);
// limit & offset
Assert::same(
'SELECT * FROM foo /* (limit 3) (offset 5) */',
$conn->translate(
'SELECT * FROM foo',
'%if', false,
'%lmt', 3,
'%ofs', 5,
'%end'
));
'SELECT * FROM foo',
'%if',
false,
'%lmt',
3,
'%ofs',
5,
'%end'
)
);

View File

@@ -261,7 +261,7 @@ if ($config['system'] === 'postgre') {
'sqlite' => "SELECT * FROM products WHERE (title LIKE 'C%' ESCAPE '\\' AND title LIKE '%r' ESCAPE '\\') OR title LIKE '%a\n\\%\\_\\\\''\"%' ESCAPE '\\'",
'odbc' => "SELECT * FROM products WHERE (title LIKE 'C%' AND title LIKE '%r') OR title LIKE '%a\n[%][_]\\''\"%'",
'sqlsrv' => "SELECT * FROM products WHERE (title LIKE 'C%' AND title LIKE '%r') OR title LIKE '%a\n[%][_]\\''\"%'",
"SELECT * FROM products WHERE (title LIKE 'C%' AND title LIKE '%r') OR title LIKE '%a\\n\\%\\_\\\\\\\\\'\"%'",
"SELECT * FROM products WHERE (title LIKE 'C%' AND title LIKE '%r') OR title LIKE '%a\\n\\%\\_\\\\\\\\\\'\"%'",
]),
$conn->translate($args[0], $args[1], $args[2], $args[3])
);
@@ -279,7 +279,7 @@ Assert::match(
CONCAT(last_name, ', ', first_name) AS full_name
GROUP BY `user`
HAVING MAX(salary) > %i 123
INTO OUTFILE '/tmp/result\'.txt'
INTO OUTFILE '/tmp/result\\'.txt'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\\\"'
LINES TERMINATED BY '\\\\n'
",
@@ -344,7 +344,7 @@ WHERE (`test`.`a` LIKE '1995-03-01'
OR `b8` IN (RAND() `col1` > `col2` )
OR `b9` IN (RAND(), [col1] > [col2] )
OR `b10` IN ( )
AND `c` = 'embedded \' string'
AND `c` = 'embedded \\' string'
OR `d`=10
OR `e`=NULL
OR `true`= 1
@@ -437,7 +437,6 @@ WHERE ([test].[a] LIKE '1995-03-01'
OR [str_not_null]='hello'
LIMIT 10",
]),
$conn->translate('SELECT *
FROM [db.table]
WHERE ([test.a] LIKE %d', '1995-03-01', '
@@ -671,7 +670,6 @@ Assert::same(
'sqlsrv' => "UPDATE [colors] SET [color]=N'blue', [price]=-12.4, [spec]=-9E-005, [spec2]=1000, [spec3]=10000, [spec4]=10000 WHERE [price]=123.5",
"UPDATE [colors] SET [color]='blue', [price]=-12.4, [spec]=-9E-005, [spec2]=1000, [spec3]=10000, [spec4]=10000 WHERE [price]=123.5",
]),
$conn->translate('UPDATE [colors] SET', [
'color' => 'blue',
'price' => -12.4,