Skip to content

Commit

Permalink
coding style
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Aug 9, 2023
1 parent b6ead80 commit d1a3362
Show file tree
Hide file tree
Showing 46 changed files with 597 additions and 501 deletions.
4 changes: 2 additions & 2 deletions examples/query-language-and-conditions.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
$dibi->test('
SELECT *
FROM customers
%if', isset($name), 'WHERE name LIKE ?', $name, '%end'
%if', isset($name), 'WHERE name LIKE ?', $name, '%end',
);
// -> SELECT * FROM customers WHERE name LIKE 'K%'

Expand All @@ -54,7 +54,7 @@
WHERE
%if', isset($name), 'name LIKE ?', $name, '
%if', $cond2, 'AND admin=1 %end
%else 1 LIMIT 10 %end'
%else 1 LIMIT 10 %end',
);
// -> SELECT * FROM customers WHERE LIMIT 10

Expand Down
4 changes: 2 additions & 2 deletions examples/query-language-basic-examples.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
SELECT COUNT(*) as [count]
FROM [comments]
WHERE [ip] LIKE ?', $ipMask, '
AND [date] > ', new Dibi\DateTime($timestamp)
AND [date] > ', new Dibi\DateTime($timestamp),
);
// -> SELECT COUNT(*) as [count] FROM [comments] WHERE [ip] LIKE '192.168.%' AND [date] > 876693600

Expand Down Expand Up @@ -69,7 +69,7 @@
$dibi->test('
SELECT *
FROM people
WHERE id IN (?)', $array
WHERE id IN (?)', $array,
);
// -> SELECT * FROM people WHERE id IN ( 1, 2, 3 )

Expand Down
2 changes: 1 addition & 1 deletion examples/using-datetime.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,6 @@
'id' => 123,
'date' => new DateTime('12.3.2007'),
'stamp' => new DateTime('23.1.2007 10:23'),
]
],
);
// -> INSERT INTO [mytable] ([id], [date], [stamp]) VALUES (123, '2007-03-12', '2007-01-23 10-23-00')
2 changes: 1 addition & 1 deletion examples/using-substitutions.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,6 @@ function substFallBack($expr)
$dibi->test("
UPDATE :account:user
SET name='John Doe', status=:active:
WHERE id=", 7
WHERE id=", 7,
);
// -> UPDATE eshop_user SET name='John Doe', status=7 WHERE id= 7
2 changes: 1 addition & 1 deletion src/Dibi/Bridges/Nette/DibiExtension22.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public function loadConfiguration()
if (class_exists(Tracy\Debugger::class)) {
$connection->addSetup(
[new Nette\DI\Statement('Tracy\Debugger::getBlueScreen'), 'addPanel'],
[[Dibi\Bridges\Tracy\Panel::class, 'renderException']]
[[Dibi\Bridges\Tracy\Panel::class, 'renderException']],
);
}

Expand Down
2 changes: 1 addition & 1 deletion src/Dibi/Bridges/Tracy/Panel.php
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ public function getPanel(): ?string
private function getConnectionName(Dibi\Connection $connection): string
{
$driver = $connection->getConfig('driver');
return (is_object($driver) ? get_class($driver) : $driver)
return (is_object($driver) ? $driver::class : $driver)
. ($connection->getConfig('name') ? '/' . $connection->getConfig('name') : '')
. ($connection->getConfig('host') ? "\u{202f}@\u{202f}" . $connection->getConfig('host') : '');
}
Expand Down
8 changes: 4 additions & 4 deletions src/Dibi/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public function __construct(array $config, ?string $name = null)
Helpers::alias($config, 'host', 'hostname');
Helpers::alias($config, 'result|formatDate', 'resultDate');
Helpers::alias($config, 'result|formatDateTime', 'resultDateTime');
$config['driver'] = $config['driver'] ?? 'mysqli';
$config['driver'] ??= 'mysqli';
$config['name'] = $name;
$this->config = $config;

Expand All @@ -93,7 +93,7 @@ public function __construct(array $config, ?string $name = null)
$this->onEvent[] = [new Loggers\FileLogger($config['profiler']['file'], $filter, $errorsOnly), 'logEvent'];
}

$this->substitutes = new HashMap(function (string $expr) { return ":$expr:"; });
$this->substitutes = new HashMap(fn(string $expr) => ":$expr:");
if (!empty($config['substitutes'])) {
foreach ($config['substitutes'] as $key => $value) {
$this->substitutes->$key = $value;
Expand Down Expand Up @@ -253,7 +253,7 @@ final public function test(...$args): bool
if ($e->getSql()) {
Helpers::dump($e->getSql());
} else {
echo get_class($e) . ': ' . $e->getMessage() . (PHP_SAPI === 'cli' ? "\n" : '<br>');
echo $e::class . ': ' . $e->getMessage() . (PHP_SAPI === 'cli' ? "\n" : '<br>');
}

return false;
Expand Down Expand Up @@ -529,7 +529,7 @@ public function substitute(string $value): string
{
return strpos($value, ':') === false
? $value
: preg_replace_callback('#:([^:\s]*):#', function (array $m) { return $this->substitutes->{$m[1]}; }, $value);
: preg_replace_callback('#:([^:\s]*):#', fn(array $m) => $this->substitutes->{$m[1]}, $value);
}


Expand Down
6 changes: 3 additions & 3 deletions src/Dibi/DataSource.php
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ public function __toString(): string
$this->sorting ? ['ORDER BY %by', $this->sorting] : null,
"\n%ofs %lmt",
$this->offset,
$this->limit
$this->limit,
);
} catch (\Throwable $e) {
trigger_error($e->getMessage(), E_USER_ERROR);
Expand All @@ -261,7 +261,7 @@ public function count(): int
if ($this->count === null) {
$this->count = $this->conds || $this->offset || $this->limit
? Helpers::intVal($this->connection->nativeQuery(
'SELECT COUNT(*) FROM (' . $this->__toString() . ') t'
'SELECT COUNT(*) FROM (' . $this->__toString() . ') t',
)->fetchSingle())
: $this->getTotalCount();
}
Expand All @@ -277,7 +277,7 @@ public function getTotalCount(): int
{
if ($this->totalCount === null) {
$this->totalCount = Helpers::intVal($this->connection->nativeQuery(
'SELECT COUNT(*) FROM ' . $this->sql
'SELECT COUNT(*) FROM ' . $this->sql,
)->fetchSingle());
}

Expand Down
2 changes: 1 addition & 1 deletion src/Dibi/Drivers/FirebirdReflector.php
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ public function getTriggersMeta(?string $table = null): array
END AS TRIGGER_ENABLED
FROM RDB\$TRIGGERS
WHERE RDB\$SYSTEM_FLAG = 0"
. ($table === null ? ';' : " AND RDB\$RELATION_NAME = UPPER('$table');")
. ($table === null ? ';' : " AND RDB\$RELATION_NAME = UPPER('$table');"),
);
$triggers = [];
while ($row = $res->fetch(true)) {
Expand Down
2 changes: 1 addition & 1 deletion src/Dibi/Drivers/MySqliDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ public function __construct(array $config)
$config['database'] ?? '',
$config['port'] ?? 0,
$config['socket'],
$config['flags'] ?? 0
$config['flags'] ?? 0,
);

if ($this->connection->connect_errno) {
Expand Down
2 changes: 1 addition & 1 deletion src/Dibi/Drivers/SqliteDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ public function registerAggregateFunction(
string $name,
callable $rowCallback,
callable $agrCallback,
int $numArgs = -1
int $numArgs = -1,
): void
{
$this->connection->createAggregate($name, $rowCallback, $agrCallback, $numArgs);
Expand Down
2 changes: 1 addition & 1 deletion src/Dibi/Drivers/SqliteResult.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public function getResultColumns(): array
{
$count = $this->resultSet->numColumns();
$columns = [];
static $types = [SQLITE3_INTEGER => 'int', SQLITE3_FLOAT => 'float', SQLITE3_TEXT => 'text', SQLITE3_BLOB => 'blob', SQLITE3_NULL => 'null'];
$types = [SQLITE3_INTEGER => 'int', SQLITE3_FLOAT => 'float', SQLITE3_TEXT => 'text', SQLITE3_BLOB => 'blob', SQLITE3_NULL => 'null'];
for ($i = 0; $i < $count; $i++) {
$columns[] = [
'name' => $this->resultSet->columnName($i),
Expand Down
2 changes: 1 addition & 1 deletion src/Dibi/Drivers/SqlsrvDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public function __construct(array $config)
$options = $config['options'];

// Default values
$options['CharacterSet'] = $options['CharacterSet'] ?? 'UTF-8';
$options['CharacterSet'] ??= 'UTF-8';
$options['PWD'] = (string) $options['PWD'];
$options['UID'] = (string) $options['UID'];
$options['Database'] = (string) $options['Database'];
Expand Down
2 changes: 1 addition & 1 deletion src/Dibi/Event.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public function __construct(Connection $connection, int $type, ?string $sql = nu
$this->time = -microtime(true);

if ($type === self::QUERY && preg_match('#\(?\s*(SELECT|UPDATE|INSERT|DELETE)#iA', $this->sql, $matches)) {
static $types = [
$types = [
'SELECT' => self::SELECT, 'UPDATE' => self::UPDATE,
'INSERT' => self::INSERT, 'DELETE' => self::DELETE,
];
Expand Down
8 changes: 4 additions & 4 deletions src/Dibi/Helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ public static function dump($sql = null, bool $return = false): ?string
$sql = \dibi::$sql;
}

static $keywords1 = 'SELECT|(?:ON\s+DUPLICATE\s+KEY)?UPDATE|INSERT(?:\s+INTO)?|REPLACE(?:\s+INTO)?|DELETE|CALL|UNION|FROM|WHERE|HAVING|GROUP\s+BY|ORDER\s+BY|LIMIT|OFFSET|FETCH\s+NEXT|SET|VALUES|LEFT\s+JOIN|INNER\s+JOIN|TRUNCATE|START\s+TRANSACTION|BEGIN|COMMIT|ROLLBACK(?:\s+TO\s+SAVEPOINT)?|(?:RELEASE\s+)?SAVEPOINT';
static $keywords2 = 'ALL|DISTINCT|DISTINCTROW|IGNORE|AS|USING|ON|AND|OR|IN|IS|NOT|NULL|LIKE|RLIKE|REGEXP|TRUE|FALSE';
$keywords1 = 'SELECT|(?:ON\s+DUPLICATE\s+KEY)?UPDATE|INSERT(?:\s+INTO)?|REPLACE(?:\s+INTO)?|DELETE|CALL|UNION|FROM|WHERE|HAVING|GROUP\s+BY|ORDER\s+BY|LIMIT|OFFSET|FETCH\s+NEXT|SET|VALUES|LEFT\s+JOIN|INNER\s+JOIN|TRUNCATE|START\s+TRANSACTION|BEGIN|COMMIT|ROLLBACK(?:\s+TO\s+SAVEPOINT)?|(?:RELEASE\s+)?SAVEPOINT';
$keywords2 = 'ALL|DISTINCT|DISTINCTROW|IGNORE|AS|USING|ON|AND|OR|IN|IS|NOT|NULL|LIKE|RLIKE|REGEXP|TRUE|FALSE';

// insert new lines
$sql = " $sql ";
Expand Down Expand Up @@ -162,7 +162,7 @@ public static function getSuggestion(array $items, string $value): ?string
/** @internal */
public static function escape(Driver $driver, $value, string $type): string
{
static $types = [
$types = [
Type::TEXT => 'text',
Type::BINARY => 'binary',
Type::BOOL => 'bool',
Expand All @@ -184,7 +184,7 @@ public static function escape(Driver $driver, $value, string $type): string
*/
public static function detectType(string $type): ?string
{
static $patterns = [
$patterns = [
'^_' => Type::TEXT, // PostgreSQL arrays
'RANGE$' => Type::TEXT, // PostgreSQL range types
'BYTEA|BLOB|BIN' => Type::BINARY,
Expand Down
6 changes: 3 additions & 3 deletions src/Dibi/Loggers/FileLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,15 +58,15 @@ public function logEvent(Dibi\Event $event): void
$this->writeToFile(
$event,
"ERROR: $message"
. "\n-- SQL: " . $event->sql
. "\n-- SQL: " . $event->sql,
);
} else {
$this->writeToFile(
$event,
'OK: ' . $event->sql
. ($event->count ? ";\n-- rows: " . $event->count : '')
. "\n-- takes: " . sprintf('%0.3f ms', $event->time * 1000)
. "\n-- source: " . implode(':', $event->source)
. "\n-- source: " . implode(':', $event->source),
);
}
}
Expand All @@ -76,7 +76,7 @@ private function writeToFile(Dibi\Event $event, string $message): void
{
$driver = $event->connection->getConfig('driver');
$message .=
"\n-- driver: " . (is_object($driver) ? get_class($driver) : $driver) . '/' . $event->connection->getConfig('name')
"\n-- driver: " . (is_object($driver) ? $driver::class : $driver) . '/' . $event->connection->getConfig('name')
. "\n-- " . date('Y-m-d H:i:s')
. "\n\n";
file_put_contents($this->file, $message, FILE_APPEND | LOCK_EX);
Expand Down
2 changes: 1 addition & 1 deletion src/Dibi/Result.php
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ final public function fetchSingle()
*/
final public function fetchAll(?int $offset = null, ?int $limit = null): array
{
$limit = $limit ?? -1;
$limit ??= -1;
$this->seek($offset ?: 0);
$row = $this->fetch();
if (!$row) {
Expand Down
14 changes: 7 additions & 7 deletions src/Dibi/Strict.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public function __call(string $name, array $args)
{
$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);
$items = array_map(fn($item) => $item->getName(), $items);
$hint = ($t = Helpers::getSuggestion($items, $name))
? ", did you mean $t()?"
: '.';
Expand All @@ -46,8 +46,8 @@ public function __call(string $name, array $args)
public static function __callStatic(string $name, array $args)
{
$rc = new ReflectionClass(static::class);
$items = array_filter($rc->getMethods(\ReflectionMethod::IS_STATIC), function ($m) { return $m->isPublic(); });
$items = array_map(function ($item) { return $item->getName(); }, $items);
$items = array_filter($rc->getMethods(\ReflectionMethod::IS_STATIC), fn($m) => $m->isPublic());
$items = array_map(fn($item) => $item->getName(), $items);
$hint = ($t = Helpers::getSuggestion($items, $name))
? ", did you mean $t()?"
: '.';
Expand All @@ -69,8 +69,8 @@ public function &__get(string $name)
}

$rc = new ReflectionClass($this);
$items = array_filter($rc->getProperties(ReflectionProperty::IS_PUBLIC), function ($p) { return !$p->isStatic(); });
$items = array_map(function ($item) { return $item->getName(); }, $items);
$items = array_filter($rc->getProperties(ReflectionProperty::IS_PUBLIC), fn($p) => !$p->isStatic());
$items = array_map(fn($item) => $item->getName(), $items);
$hint = ($t = Helpers::getSuggestion($items, $name))
? ", did you mean $$t?"
: '.';
Expand All @@ -85,8 +85,8 @@ public function &__get(string $name)
public function __set(string $name, $value)
{
$rc = new ReflectionClass($this);
$items = array_filter($rc->getProperties(ReflectionProperty::IS_PUBLIC), function ($p) { return !$p->isStatic(); });
$items = array_map(function ($item) { return $item->getName(); }, $items);
$items = array_filter($rc->getProperties(ReflectionProperty::IS_PUBLIC), fn($p) => !$p->isStatic());
$items = array_map(fn($item) => $item->getName(), $items);
$hint = ($t = Helpers::getSuggestion($items, $name))
? ", did you mean $$t?"
: '.';
Expand Down
60 changes: 29 additions & 31 deletions src/Dibi/Translator.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,22 +96,21 @@ public function translate(array $args): string
// note: this can change $this->args & $this->cursor & ...
. preg_replace_callback(
<<<'XX'
/
(?=[`['":%?]) ## speed-up
(?:
`(.+?)`| ## 1) `identifier`
\[(.+?)\]| ## 2) [identifier]
(')((?:''|[^'])*)'| ## 3,4) string
(")((?:""|[^"])*)"| ## 5,6) "string"
('|")| ## 7) lone quote
:(\S*?:)([a-zA-Z0-9._]?)| ## 8,9) :substitution:
%([a-zA-Z~][a-zA-Z0-9~]{0,5})| ## 10) modifier
(\?) ## 11) placeholder
)/xs
XX
,
/
(?=[`['":%?]) ## speed-up
(?:
`(.+?)`| ## 1) `identifier`
\[(.+?)\]| ## 2) [identifier]
(')((?:''|[^'])*)'| ## 3,4) string
(")((?:""|[^"])*)"| ## 5,6) "string"
('|")| ## 7) lone quote
:(\S*?:)([a-zA-Z0-9._]?)| ## 8,9) :substitution:
%([a-zA-Z~][a-zA-Z0-9~]{0,5})| ## 10) modifier
(\?) ## 11) placeholder
)/xs
XX,
[$this, 'cb'],
substr($arg, $toSkip)
substr($arg, $toSkip),
);
if (preg_last_error()) {
throw new PcreException;
Expand Down Expand Up @@ -280,7 +279,7 @@ public function formatValue($value, ?string $modifier): string
$proto = array_keys($v);
}
} else {
return $this->errors[] = '**Unexpected type ' . (is_object($v) ? get_class($v) : gettype($v)) . '**';
return $this->errors[] = '**Unexpected type ' . (is_object($v) ? $v::class : gettype($v)) . '**';
}

$pair = explode('%', $k, 2); // split into identifier & modifier
Expand Down Expand Up @@ -349,7 +348,7 @@ public function formatValue($value, ?string $modifier): string
) {
// continue
} else {
$type = is_object($value) ? get_class($value) : gettype($value);
$type = is_object($value) ? $value::class : gettype($value);
return $this->errors[] = "**Invalid combination of type $type and modifier %$modifier**";
}
}
Expand Down Expand Up @@ -437,20 +436,19 @@ public function formatValue($value, ?string $modifier): string
$value = substr($value, 0, $toSkip)
. preg_replace_callback(
<<<'XX'
/
(?=[`['":])
(?:
`(.+?)`|
\[(.+?)\]|
(')((?:''|[^'])*)'|
(")((?:""|[^"])*)"|
('|")|
:(\S*?:)([a-zA-Z0-9._]?)
)/sx
XX
,
/
(?=[`['":])
(?:
`(.+?)`|
\[(.+?)]|
(')((?:''|[^'])*)'|
(")((?:""|[^"])*)"|
(['"])|
:(\S*?:)([a-zA-Z0-9._]?)
)/sx
XX,
[$this, 'cb'],
substr($value, $toSkip)
substr($value, $toSkip),
);
if (preg_last_error()) {
throw new PcreException;
Expand Down Expand Up @@ -516,7 +514,7 @@ public function formatValue($value, ?string $modifier): string
return $this->connection->translate(...$value->getValues());

} else {
$type = is_object($value) ? get_class($value) : gettype($value);
$type = is_object($value) ? $value::class : gettype($value);
return $this->errors[] = "**Unexpected $type**";
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Dibi/dibi.php
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ public static function dump($sql = null, bool $return = false): ?string
*/
public static function stripMicroseconds(DateTimeInterface $dt): DateTimeInterface
{
$class = get_class($dt);
$class = $dt::class;
return new $class($dt->format('Y-m-d H:i:s'), $dt->getTimezone());
}
}
Loading

0 comments on commit d1a3362

Please sign in to comment.