From 13bc0e902db1c6027972ce7878732bd941799256 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Thu, 26 Jan 2017 00:43:19 +0100 Subject: [PATCH] added PHP 7.1 scalar and return type hints --- src/Bridges/DatabaseDI/DatabaseExtension.php | 2 +- src/Bridges/DatabaseTracy/ConnectionPanel.php | 6 +- src/Database/Connection.php | 36 +--- src/Database/Context.php | 39 +--- .../Conventions/DiscoveredConventions.php | 6 +- .../Conventions/StaticConventions.php | 10 +- src/Database/DriverException.php | 4 +- src/Database/Drivers/MsSqlDriver.php | 32 ++-- src/Database/Drivers/MySqlDriver.php | 35 ++-- src/Database/Drivers/OciDriver.php | 32 ++-- src/Database/Drivers/OdbcDriver.php | 32 ++-- src/Database/Drivers/PgSqlDriver.php | 36 ++-- src/Database/Drivers/SqliteDriver.php | 32 ++-- src/Database/Drivers/SqlsrvDriver.php | 32 ++-- src/Database/Helpers.php | 25 +-- src/Database/IConventions.php | 7 +- src/Database/IRowContainer.php | 11 +- src/Database/IStructure.php | 27 +-- src/Database/ISupplementalDriver.php | 53 ++---- src/Database/ResultSet.php | 48 ++--- src/Database/Row.php | 3 +- src/Database/SqlLiteral.php | 12 +- src/Database/SqlPreprocessor.php | 5 +- src/Database/Structure.php | 18 +- src/Database/Table/ActiveRow.php | 43 ++--- src/Database/Table/GroupedSelection.php | 37 ++-- src/Database/Table/IRow.php | 21 +-- src/Database/Table/Selection.php | 159 +++++----------- src/Database/Table/SqlBuilder.php | 178 ++++-------------- tests/Database/Table/Selection.page().phpt | 8 - .../Database/Table/SqlBuilder.addAlias().phpt | 4 +- .../SqlBuilder.parseJoinConditions().phpt | 8 +- .../Table/SqlBuilder.parseJoins().phpt | 4 +- .../Table/bugs/Selection.emptyResultSet.phpt | 2 +- 34 files changed, 327 insertions(+), 680 deletions(-) diff --git a/src/Bridges/DatabaseDI/DatabaseExtension.php b/src/Bridges/DatabaseDI/DatabaseExtension.php index bd4f06430..692252066 100644 --- a/src/Bridges/DatabaseDI/DatabaseExtension.php +++ b/src/Bridges/DatabaseDI/DatabaseExtension.php @@ -33,7 +33,7 @@ class DatabaseExtension extends Nette\DI\CompilerExtension private $debugMode; - public function __construct($debugMode = FALSE) + public function __construct(bool $debugMode = FALSE) { $this->debugMode = $debugMode; } diff --git a/src/Bridges/DatabaseTracy/ConnectionPanel.php b/src/Bridges/DatabaseTracy/ConnectionPanel.php index 63048a21e..0c470d473 100644 --- a/src/Bridges/DatabaseTracy/ConnectionPanel.php +++ b/src/Bridges/DatabaseTracy/ConnectionPanel.php @@ -99,7 +99,7 @@ public static function renderException($e) } - public function getTab() + public function getTab(): string { $name = $this->name; $count = $this->count; @@ -110,11 +110,11 @@ public function getTab() } - public function getPanel() + public function getPanel(): ?string { $this->disabled = TRUE; if (!$this->count) { - return; + return NULL; } $name = $this->name; diff --git a/src/Database/Connection.php b/src/Database/Connection.php index 148678639..4dc927114 100644 --- a/src/Database/Connection.php +++ b/src/Database/Connection.php @@ -118,9 +118,8 @@ public function getSupplementalDriver() /** * @param string sequence object - * @return string */ - public function getInsertId($name = NULL) + public function getInsertId(string $name = NULL): string { try { $res = $this->getPdo()->lastInsertId($name); @@ -134,9 +133,8 @@ public function getInsertId($name = NULL) /** * @param string string to be quoted * @param int data type hint - * @return string */ - public function quote($string, $type = PDO::PARAM_STR) + public function quote(string $string, int $type = PDO::PARAM_STR): string { try { return $this->getPdo()->quote($string, $type); @@ -169,10 +167,8 @@ public function rollBack() /** * Generates and executes SQL query. - * @param string - * @return ResultSet */ - public function query($sql, ...$params) + public function query(string $sql, ...$params): ResultSet { [$sql, $params] = $this->preprocess($sql, ...$params); try { @@ -186,11 +182,7 @@ public function query($sql, ...$params) } - /** - * @param string - * @return ResultSet - */ - public function queryArgs($sql, array $params) + public function queryArgs(string $sql, array $params): ResultSet { return $this->query($sql, ...$params); } @@ -213,10 +205,8 @@ public function preprocess($sql, ...$params) /** * Shortcut for query()->fetch() - * @param string - * @return Row|NULL */ - public function fetch($sql, ...$params) + public function fetch(string $sql, ...$params): ?Row { return $this->query($sql, ...$params)->fetch(); } @@ -224,10 +214,9 @@ public function fetch($sql, ...$params) /** * Shortcut for query()->fetchField() - * @param string * @return mixed */ - public function fetchField($sql, ...$params) + public function fetchField(string $sql, ...$params) { return $this->query($sql, ...$params)->fetchField(); } @@ -235,10 +224,8 @@ public function fetchField($sql, ...$params) /** * Shortcut for query()->fetchPairs() - * @param string - * @return array */ - public function fetchPairs($sql, ...$params) + public function fetchPairs(string $sql, ...$params): array { return $this->query($sql, ...$params)->fetchPairs(); } @@ -246,19 +233,14 @@ public function fetchPairs($sql, ...$params) /** * Shortcut for query()->fetchAll() - * @param string - * @return array */ - public function fetchAll($sql, ...$params) + public function fetchAll(string $sql, ...$params): array { return $this->query($sql, ...$params)->fetchAll(); } - /** - * @return SqlLiteral - */ - public static function literal($value, ...$params) + public static function literal($value, ...$params): SqlLiteral { return new SqlLiteral($value, $params); } diff --git a/src/Database/Context.php b/src/Database/Context.php index 76c4ccee9..03b07fbcc 100644 --- a/src/Database/Context.php +++ b/src/Database/Context.php @@ -65,9 +65,8 @@ public function rollBack() /** * @param string sequence object - * @return string */ - public function getInsertId($name = NULL) + public function getInsertId(string $name = NULL): string { return $this->connection->getInsertId($name); } @@ -75,30 +74,20 @@ public function getInsertId($name = NULL) /** * Generates and executes SQL query. - * @param string - * @return ResultSet */ - public function query($sql, ...$params) + public function query(string $sql, ...$params): ResultSet { return $this->connection->query($sql, ...$params); } - /** - * @param string - * @return ResultSet - */ - public function queryArgs($sql, array $params) + public function queryArgs(string $sql, array $params): ResultSet { return $this->connection->query($sql, ...$params); } - /** - * @param string - * @return Table\Selection - */ - public function table($table) + public function table(string $table): Table\Selection { return new Table\Selection($this, $this->conventions, $table, $this->cacheStorage); } @@ -130,10 +119,8 @@ public function getConventions() /** * Shortcut for query()->fetch() - * @param string - * @return Row|NULL */ - public function fetch($sql, ...$params) + public function fetch(string $sql, ...$params): ?Row { return $this->connection->query($sql, ...$params)->fetch(); } @@ -141,10 +128,9 @@ public function fetch($sql, ...$params) /** * Shortcut for query()->fetchField() - * @param string * @return mixed */ - public function fetchField($sql, ...$params) + public function fetchField(string $sql, ...$params) { return $this->connection->query($sql, ...$params)->fetchField(); } @@ -152,10 +138,8 @@ public function fetchField($sql, ...$params) /** * Shortcut for query()->fetchPairs() - * @param string - * @return array */ - public function fetchPairs($sql, ...$params) + public function fetchPairs(string $sql, ...$params): array { return $this->connection->query($sql, ...$params)->fetchPairs(); } @@ -163,19 +147,14 @@ public function fetchPairs($sql, ...$params) /** * Shortcut for query()->fetchAll() - * @param string - * @return array */ - public function fetchAll($sql, ...$params) + public function fetchAll(string $sql, ...$params): array { return $this->connection->query($sql, ...$params)->fetchAll(); } - /** - * @return SqlLiteral - */ - public static function literal($value, ...$params) + public static function literal($value, ...$params): SqlLiteral { return new SqlLiteral($value, $params); } diff --git a/src/Database/Conventions/DiscoveredConventions.php b/src/Database/Conventions/DiscoveredConventions.php index b2910c0b4..d091051f0 100644 --- a/src/Database/Conventions/DiscoveredConventions.php +++ b/src/Database/Conventions/DiscoveredConventions.php @@ -28,13 +28,13 @@ public function __construct(IStructure $structure) } - public function getPrimary($table) + public function getPrimary(string $table) { return $this->structure->getPrimaryKey($table); } - public function getHasManyReference($nsTable, $key) + public function getHasManyReference(string $nsTable, string $key): ?array { $candidates = $columnCandidates = []; $targets = $this->structure->getHasManyReference($nsTable); @@ -83,7 +83,7 @@ public function getHasManyReference($nsTable, $key) } - public function getBelongsToReference($table, $key) + public function getBelongsToReference(string $table, string $key): ?array { $tableColumns = $this->structure->getBelongsToReference($table); diff --git a/src/Database/Conventions/StaticConventions.php b/src/Database/Conventions/StaticConventions.php index de430bc8e..1a188ae8a 100644 --- a/src/Database/Conventions/StaticConventions.php +++ b/src/Database/Conventions/StaticConventions.php @@ -36,7 +36,7 @@ class StaticConventions implements IConventions * @param string %1$s stands for key used after ->, %2$s for table name * @param string %1$s stands for key used after ->, %2$s for table name */ - public function __construct($primary = 'id', $foreign = '%s_id', $table = '%s') + public function __construct(string $primary = 'id', string $foreign = '%s_id', string $table = '%s') { $this->primary = $primary; $this->foreign = $foreign; @@ -44,13 +44,13 @@ public function __construct($primary = 'id', $foreign = '%s_id', $table = '%s') } - public function getPrimary($table) + public function getPrimary(string $table) { return sprintf($this->primary, $this->getColumnFromTable($table)); } - public function getHasManyReference($table, $key) + public function getHasManyReference(string $table, string $key): ?array { $table = $this->getColumnFromTable($table); return [ @@ -60,7 +60,7 @@ public function getHasManyReference($table, $key) } - public function getBelongsToReference($table, $key) + public function getBelongsToReference(string $table, string $key): ?array { $table = $this->getColumnFromTable($table); return [ @@ -70,7 +70,7 @@ public function getBelongsToReference($table, $key) } - protected function getColumnFromTable($name) + protected function getColumnFromTable(string $name) { if ($this->table !== '%s' && preg_match('(^' . str_replace('%s', '(.*)', preg_quote($this->table)) . '\z)', $name, $match)) { return $match[1]; diff --git a/src/Database/DriverException.php b/src/Database/DriverException.php index aa2df1920..0f42f8596 100644 --- a/src/Database/DriverException.php +++ b/src/Database/DriverException.php @@ -49,7 +49,7 @@ public function getDriverCode() /** * @return string|NULL SQLSTATE error code */ - public function getSqlState() + public function getSqlState(): ?string { return $this->errorInfo[0] ?? NULL; } @@ -58,7 +58,7 @@ public function getSqlState() /** * @return string|NULL SQL command */ - public function getQueryString() + public function getQueryString(): ?string { return $this->queryString; } diff --git a/src/Database/Drivers/MsSqlDriver.php b/src/Database/Drivers/MsSqlDriver.php index 3a917c287..a30a92f4c 100644 --- a/src/Database/Drivers/MsSqlDriver.php +++ b/src/Database/Drivers/MsSqlDriver.php @@ -24,7 +24,7 @@ public function initialize(Nette\Database\Connection $connection, array $options } - public function convertException(\PDOException $e) + public function convertException(\PDOException $e): Nette\Database\DriverException { return Nette\Database\DriverException::from($e); } @@ -36,7 +36,7 @@ public function convertException(\PDOException $e) /** * Delimites identifier for use in a SQL statement. */ - public function delimite($name) + public function delimite(string $name): string { // @see https://msdn.microsoft.com/en-us/library/ms176027.aspx return '[' . str_replace(['[', ']'], ['[[', ']]'], $name) . ']'; @@ -46,7 +46,7 @@ public function delimite($name) /** * Formats boolean for use in a SQL statement. */ - public function formatBool($value) + public function formatBool(bool $value): string { return $value ? '1' : '0'; } @@ -55,7 +55,7 @@ public function formatBool($value) /** * Formats date-time for use in a SQL statement. */ - public function formatDateTime(/*\DateTimeInterface*/ $value) + public function formatDateTime(\DateTimeInterface $value): string { return $value->format("'Y-m-d H:i:s'"); } @@ -64,7 +64,7 @@ public function formatDateTime(/*\DateTimeInterface*/ $value) /** * Formats date-time interval for use in a SQL statement. */ - public function formatDateInterval(\DateInterval $value) + public function formatDateInterval(\DateInterval $value): string { throw new Nette\NotSupportedException; } @@ -73,7 +73,7 @@ public function formatDateInterval(\DateInterval $value) /** * Encodes string for use in a LIKE statement. */ - public function formatLike($value, $pos) + public function formatLike(string $value, int $pos): string { $value = strtr($value, ["'" => "''", '%' => '[%]', '_' => '[_]', '[' => '[[]']); return ($pos <= 0 ? "'%" : "'") . $value . ($pos >= 0 ? "%'" : "'"); @@ -83,7 +83,7 @@ public function formatLike($value, $pos) /** * Injects LIMIT/OFFSET to the SQL query. */ - public function applyLimit(&$sql, $limit, $offset) + public function applyLimit(string &$sql, ?int $limit, ?int $offset) { if ($offset) { throw new Nette\NotSupportedException('Offset is not supported by this database.'); @@ -103,7 +103,7 @@ public function applyLimit(&$sql, $limit, $offset) /** * Normalizes result row. */ - public function normalizeRow($row) + public function normalizeRow(array $row): array { return $row; } @@ -115,7 +115,7 @@ public function normalizeRow($row) /** * Returns list of tables. */ - public function getTables() + public function getTables(): array { throw new Nette\NotImplementedException; } @@ -124,7 +124,7 @@ public function getTables() /** * Returns metadata for all columns in a table. */ - public function getColumns($table) + public function getColumns(string $table): array { throw new Nette\NotImplementedException; } @@ -133,7 +133,7 @@ public function getColumns($table) /** * Returns metadata for all indexes in a table. */ - public function getIndexes($table) + public function getIndexes(string $table): array { throw new Nette\NotImplementedException; } @@ -142,7 +142,7 @@ public function getIndexes($table) /** * Returns metadata for all foreign keys in a table. */ - public function getForeignKeys($table) + public function getForeignKeys(string $table): array { throw new Nette\NotImplementedException; } @@ -151,17 +151,13 @@ public function getForeignKeys($table) /** * Returns associative array of detected types (IReflection::FIELD_*) in result set. */ - public function getColumnTypes(\PDOStatement $statement) + public function getColumnTypes(\PDOStatement $statement): array { return Nette\Database\Helpers::detectTypes($statement); } - /** - * @param string - * @return bool - */ - public function isSupported($item) + public function isSupported(string $item): bool { return $item === self::SUPPORT_SUBSELECT; } diff --git a/src/Database/Drivers/MySqlDriver.php b/src/Database/Drivers/MySqlDriver.php index 174ccc019..7a5da2a98 100644 --- a/src/Database/Drivers/MySqlDriver.php +++ b/src/Database/Drivers/MySqlDriver.php @@ -46,10 +46,7 @@ public function initialize(Nette\Database\Connection $connection, array $options } - /** - * @return Nette\Database\DriverException - */ - public function convertException(\PDOException $e) + public function convertException(\PDOException $e): Nette\Database\DriverException { $code = $e->errorInfo[1] ?? NULL; if (in_array($code, [1216, 1217, 1451, 1452, 1701], TRUE)) { @@ -76,7 +73,7 @@ public function convertException(\PDOException $e) /** * Delimites identifier for use in a SQL statement. */ - public function delimite($name) + public function delimite(string $name): string { // @see http://dev.mysql.com/doc/refman/5.0/en/identifiers.html return '`' . str_replace('`', '``', $name) . '`'; @@ -86,7 +83,7 @@ public function delimite($name) /** * Formats boolean for use in a SQL statement. */ - public function formatBool($value) + public function formatBool(bool $value): string { return $value ? '1' : '0'; } @@ -95,7 +92,7 @@ public function formatBool($value) /** * Formats date-time for use in a SQL statement. */ - public function formatDateTime(/*\DateTimeInterface*/ $value) + public function formatDateTime(\DateTimeInterface $value): string { return $value->format("'Y-m-d H:i:s'"); } @@ -104,7 +101,7 @@ public function formatDateTime(/*\DateTimeInterface*/ $value) /** * Formats date-time interval for use in a SQL statement. */ - public function formatDateInterval(\DateInterval $value) + public function formatDateInterval(\DateInterval $value): string { return $value->format("'%r%h:%I:%S'"); } @@ -113,7 +110,7 @@ public function formatDateInterval(\DateInterval $value) /** * Encodes string for use in a LIKE statement. */ - public function formatLike($value, $pos) + public function formatLike(string $value, int $pos): string { $value = str_replace('\\', '\\\\', $value); $value = addcslashes(substr($this->connection->quote($value), 1, -1), '%_'); @@ -124,7 +121,7 @@ public function formatLike($value, $pos) /** * Injects LIMIT/OFFSET to the SQL query. */ - public function applyLimit(&$sql, $limit, $offset) + public function applyLimit(string &$sql, ?int $limit, ?int $offset) { if ($limit < 0 || $offset < 0) { throw new Nette\InvalidArgumentException('Negative offset or limit.'); @@ -140,7 +137,7 @@ public function applyLimit(&$sql, $limit, $offset) /** * Normalizes result row. */ - public function normalizeRow($row) + public function normalizeRow(array $row): array { return $row; } @@ -152,7 +149,7 @@ public function normalizeRow($row) /** * Returns list of tables. */ - public function getTables() + public function getTables(): array { $tables = []; foreach ($this->connection->query('SHOW FULL TABLES') as $row) { @@ -168,7 +165,7 @@ public function getTables() /** * Returns metadata for all columns in a table. */ - public function getColumns($table) + public function getColumns(string $table): array { $columns = []; foreach ($this->connection->query('SHOW FULL COLUMNS FROM ' . $this->delimite($table)) as $row) { @@ -193,7 +190,7 @@ public function getColumns($table) /** * Returns metadata for all indexes in a table. */ - public function getIndexes($table) + public function getIndexes(string $table): array { $indexes = []; foreach ($this->connection->query('SHOW INDEX FROM ' . $this->delimite($table)) as $row) { @@ -209,7 +206,7 @@ public function getIndexes($table) /** * Returns metadata for all foreign keys in a table. */ - public function getForeignKeys($table) + public function getForeignKeys(string $table): array { $keys = []; $query = 'SELECT CONSTRAINT_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM information_schema.KEY_COLUMN_USAGE ' @@ -229,7 +226,7 @@ public function getForeignKeys($table) /** * Returns associative array of detected types (IReflection::FIELD_*) in result set. */ - public function getColumnTypes(\PDOStatement $statement) + public function getColumnTypes(\PDOStatement $statement): array { $types = []; $count = $statement->columnCount(); @@ -246,11 +243,7 @@ public function getColumnTypes(\PDOStatement $statement) } - /** - * @param string - * @return bool - */ - public function isSupported($item) + public function isSupported(string $item): bool { // MULTI_COLUMN_AS_OR_COND due to mysql bugs: // - http://bugs.mysql.com/bug.php?id=31188 diff --git a/src/Database/Drivers/OciDriver.php b/src/Database/Drivers/OciDriver.php index 3630a2a4b..25a4ed4d5 100644 --- a/src/Database/Drivers/OciDriver.php +++ b/src/Database/Drivers/OciDriver.php @@ -33,7 +33,7 @@ public function initialize(Nette\Database\Connection $connection, array $options } - public function convertException(\PDOException $e) + public function convertException(\PDOException $e): Nette\Database\DriverException { $code = $e->errorInfo[1] ?? NULL; if (in_array($code, [1, 2299, 38911], TRUE)) { @@ -57,7 +57,7 @@ public function convertException(\PDOException $e) /** * Delimites identifier for use in a SQL statement. */ - public function delimite($name) + public function delimite(string $name): string { // @see http://download.oracle.com/docs/cd/B10500_01/server.920/a96540/sql_elements9a.htm return '"' . str_replace('"', '""', $name) . '"'; @@ -67,7 +67,7 @@ public function delimite($name) /** * Formats boolean for use in a SQL statement. */ - public function formatBool($value) + public function formatBool(bool $value): string { return $value ? '1' : '0'; } @@ -76,7 +76,7 @@ public function formatBool($value) /** * Formats date-time for use in a SQL statement. */ - public function formatDateTime(/*\DateTimeInterface*/ $value) + public function formatDateTime(\DateTimeInterface $value): string { return $value->format($this->fmtDateTime); } @@ -85,7 +85,7 @@ public function formatDateTime(/*\DateTimeInterface*/ $value) /** * Formats date-time interval for use in a SQL statement. */ - public function formatDateInterval(\DateInterval $value) + public function formatDateInterval(\DateInterval $value): string { throw new Nette\NotSupportedException; } @@ -94,7 +94,7 @@ public function formatDateInterval(\DateInterval $value) /** * Encodes string for use in a LIKE statement. */ - public function formatLike($value, $pos) + public function formatLike(string $value, int $pos): string { throw new Nette\NotImplementedException; } @@ -103,7 +103,7 @@ public function formatLike($value, $pos) /** * Injects LIMIT/OFFSET to the SQL query. */ - public function applyLimit(&$sql, $limit, $offset) + public function applyLimit(string &$sql, ?int $limit, ?int $offset) { if ($limit < 0 || $offset < 0) { throw new Nette\InvalidArgumentException('Negative offset or limit.'); @@ -123,7 +123,7 @@ public function applyLimit(&$sql, $limit, $offset) /** * Normalizes result row. */ - public function normalizeRow($row) + public function normalizeRow(array $row): array { return $row; } @@ -135,7 +135,7 @@ public function normalizeRow($row) /** * Returns list of tables. */ - public function getTables() + public function getTables(): array { $tables = []; foreach ($this->connection->query('SELECT * FROM cat') as $row) { @@ -153,7 +153,7 @@ public function getTables() /** * Returns metadata for all columns in a table. */ - public function getColumns($table) + public function getColumns(string $table): array { throw new Nette\NotImplementedException; } @@ -162,7 +162,7 @@ public function getColumns($table) /** * Returns metadata for all indexes in a table. */ - public function getIndexes($table) + public function getIndexes(string $table): array { throw new Nette\NotImplementedException; } @@ -171,7 +171,7 @@ public function getIndexes($table) /** * Returns metadata for all foreign keys in a table. */ - public function getForeignKeys($table) + public function getForeignKeys(string $table): array { throw new Nette\NotImplementedException; } @@ -180,17 +180,13 @@ public function getForeignKeys($table) /** * Returns associative array of detected types (IReflection::FIELD_*) in result set. */ - public function getColumnTypes(\PDOStatement $statement) + public function getColumnTypes(\PDOStatement $statement): array { return Nette\Database\Helpers::detectTypes($statement); } - /** - * @param string - * @return bool - */ - public function isSupported($item) + public function isSupported(string $item): bool { return $item === self::SUPPORT_SEQUENCE || $item === self::SUPPORT_SUBSELECT; } diff --git a/src/Database/Drivers/OdbcDriver.php b/src/Database/Drivers/OdbcDriver.php index b6ea602d5..8287ffe27 100644 --- a/src/Database/Drivers/OdbcDriver.php +++ b/src/Database/Drivers/OdbcDriver.php @@ -24,7 +24,7 @@ public function initialize(Nette\Database\Connection $connection, array $options } - public function convertException(\PDOException $e) + public function convertException(\PDOException $e): Nette\Database\DriverException { return Nette\Database\DriverException::from($e); } @@ -36,7 +36,7 @@ public function convertException(\PDOException $e) /** * Delimites identifier for use in a SQL statement. */ - public function delimite($name) + public function delimite(string $name): string { return '[' . str_replace(['[', ']'], ['[[', ']]'], $name) . ']'; } @@ -45,7 +45,7 @@ public function delimite($name) /** * Formats boolean for use in a SQL statement. */ - public function formatBool($value) + public function formatBool(bool $value): string { return $value ? '1' : '0'; } @@ -54,7 +54,7 @@ public function formatBool($value) /** * Formats date-time for use in a SQL statement. */ - public function formatDateTime(/*\DateTimeInterface*/ $value) + public function formatDateTime(\DateTimeInterface $value): string { return $value->format('#m/d/Y H:i:s#'); } @@ -63,7 +63,7 @@ public function formatDateTime(/*\DateTimeInterface*/ $value) /** * Formats date-time interval for use in a SQL statement. */ - public function formatDateInterval(\DateInterval $value) + public function formatDateInterval(\DateInterval $value): string { throw new Nette\NotSupportedException; } @@ -72,7 +72,7 @@ public function formatDateInterval(\DateInterval $value) /** * Encodes string for use in a LIKE statement. */ - public function formatLike($value, $pos) + public function formatLike(string $value, int $pos): string { $value = strtr($value, ["'" => "''", '%' => '[%]', '_' => '[_]', '[' => '[[]']); return ($pos <= 0 ? "'%" : "'") . $value . ($pos >= 0 ? "%'" : "'"); @@ -82,7 +82,7 @@ public function formatLike($value, $pos) /** * Injects LIMIT/OFFSET to the SQL query. */ - public function applyLimit(&$sql, $limit, $offset) + public function applyLimit(string &$sql, ?int $limit, ?int $offset) { if ($offset) { throw new Nette\NotSupportedException('Offset is not supported by this database.'); @@ -102,7 +102,7 @@ public function applyLimit(&$sql, $limit, $offset) /** * Normalizes result row. */ - public function normalizeRow($row) + public function normalizeRow(array $row): array { return $row; } @@ -114,7 +114,7 @@ public function normalizeRow($row) /** * Returns list of tables. */ - public function getTables() + public function getTables(): array { throw new Nette\NotImplementedException; } @@ -123,7 +123,7 @@ public function getTables() /** * Returns metadata for all columns in a table. */ - public function getColumns($table) + public function getColumns(string $table): array { throw new Nette\NotImplementedException; } @@ -132,7 +132,7 @@ public function getColumns($table) /** * Returns metadata for all indexes in a table. */ - public function getIndexes($table) + public function getIndexes(string $table): array { throw new Nette\NotImplementedException; } @@ -141,7 +141,7 @@ public function getIndexes($table) /** * Returns metadata for all foreign keys in a table. */ - public function getForeignKeys($table) + public function getForeignKeys(string $table): array { throw new Nette\NotImplementedException; } @@ -150,17 +150,13 @@ public function getForeignKeys($table) /** * Returns associative array of detected types (IReflection::FIELD_*) in result set. */ - public function getColumnTypes(\PDOStatement $statement) + public function getColumnTypes(\PDOStatement $statement): array { return Nette\Database\Helpers::detectTypes($statement); } - /** - * @param string - * @return bool - */ - public function isSupported($item) + public function isSupported(string $item): bool { return $item === self::SUPPORT_SUBSELECT; } diff --git a/src/Database/Drivers/PgSqlDriver.php b/src/Database/Drivers/PgSqlDriver.php index a0351f412..d615a1f3d 100644 --- a/src/Database/Drivers/PgSqlDriver.php +++ b/src/Database/Drivers/PgSqlDriver.php @@ -29,7 +29,7 @@ public function initialize(Nette\Database\Connection $connection, array $options } - public function convertException(\PDOException $e) + public function convertException(\PDOException $e): Nette\Database\DriverException { $code = $e->errorInfo[0] ?? NULL; if ($code === '0A000' && strpos($e->getMessage(), 'truncate') !== FALSE) { @@ -59,7 +59,7 @@ public function convertException(\PDOException $e) /** * Delimites identifier for use in a SQL statement. */ - public function delimite($name) + public function delimite(string $name): string { // @see http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS return '"' . str_replace('"', '""', $name) . '"'; @@ -69,7 +69,7 @@ public function delimite($name) /** * Formats boolean for use in a SQL statement. */ - public function formatBool($value) + public function formatBool(bool $value): string { return $value ? 'TRUE' : 'FALSE'; } @@ -78,7 +78,7 @@ public function formatBool($value) /** * Formats date-time for use in a SQL statement. */ - public function formatDateTime(/*\DateTimeInterface*/ $value) + public function formatDateTime(\DateTimeInterface $value): string { return $value->format("'Y-m-d H:i:s'"); } @@ -87,7 +87,7 @@ public function formatDateTime(/*\DateTimeInterface*/ $value) /** * Formats date-time interval for use in a SQL statement. */ - public function formatDateInterval(\DateInterval $value) + public function formatDateInterval(\DateInterval $value): string { throw new Nette\NotSupportedException; } @@ -96,7 +96,7 @@ public function formatDateInterval(\DateInterval $value) /** * Encodes string for use in a LIKE statement. */ - public function formatLike($value, $pos) + public function formatLike(string $value, int $pos): string { $bs = substr($this->connection->quote('\\'), 1, -1); // standard_conforming_strings = on/off $value = substr($this->connection->quote($value), 1, -1); @@ -108,7 +108,7 @@ public function formatLike($value, $pos) /** * Injects LIMIT/OFFSET to the SQL query. */ - public function applyLimit(&$sql, $limit, $offset) + public function applyLimit(string &$sql, ?int $limit, ?int $offset) { if ($limit < 0 || $offset < 0) { throw new Nette\InvalidArgumentException('Negative offset or limit.'); @@ -125,7 +125,7 @@ public function applyLimit(&$sql, $limit, $offset) /** * Normalizes result row. */ - public function normalizeRow($row) + public function normalizeRow(array $row): array { return $row; } @@ -137,7 +137,7 @@ public function normalizeRow($row) /** * Returns list of tables. */ - public function getTables() + public function getTables(): array { $tables = []; foreach ($this->connection->query(" @@ -164,7 +164,7 @@ public function getTables() /** * Returns metadata for all columns in a table. */ - public function getColumns($table) + public function getColumns(string $table): array { $columns = []; foreach ($this->connection->query(" @@ -207,7 +207,7 @@ public function getColumns($table) /** * Returns metadata for all indexes in a table. */ - public function getIndexes($table) + public function getIndexes(string $table): array { $indexes = []; foreach ($this->connection->query(" @@ -238,7 +238,7 @@ public function getIndexes($table) /** * Returns metadata for all foreign keys in a table. */ - public function getForeignKeys($table) + public function getForeignKeys(string $table): array { /* Does't work with multicolumn foreign keys */ return $this->connection->query(" @@ -265,17 +265,13 @@ public function getForeignKeys($table) /** * Returns associative array of detected types (IReflection::FIELD_*) in result set. */ - public function getColumnTypes(\PDOStatement $statement) + public function getColumnTypes(\PDOStatement $statement): array { return Nette\Database\Helpers::detectTypes($statement); } - /** - * @param string - * @return bool - */ - public function isSupported($item) + public function isSupported(string $item): bool { return $item === self::SUPPORT_SEQUENCE || $item === self::SUPPORT_SUBSELECT || $item === self::SUPPORT_SCHEMA; } @@ -283,10 +279,8 @@ public function isSupported($item) /** * Converts: schema.name => "schema"."name" - * @param string - * @return string */ - private function delimiteFQN($name) + private function delimiteFQN(string $name): string { return implode('.', array_map([$this, 'delimite'], explode('.', $name))); } diff --git a/src/Database/Drivers/SqliteDriver.php b/src/Database/Drivers/SqliteDriver.php index 73c8e6025..d2d4ef28f 100644 --- a/src/Database/Drivers/SqliteDriver.php +++ b/src/Database/Drivers/SqliteDriver.php @@ -33,7 +33,7 @@ public function initialize(Nette\Database\Connection $connection, array $options } - public function convertException(\PDOException $e) + public function convertException(\PDOException $e): Nette\Database\DriverException { $code = $e->errorInfo[1] ?? NULL; $msg = $e->getMessage(); @@ -68,7 +68,7 @@ public function convertException(\PDOException $e) /** * Delimites identifier for use in a SQL statement. */ - public function delimite($name) + public function delimite(string $name): string { return '[' . strtr($name, '[]', ' ') . ']'; } @@ -77,7 +77,7 @@ public function delimite($name) /** * Formats boolean for use in a SQL statement. */ - public function formatBool($value) + public function formatBool(bool $value): string { return $value ? '1' : '0'; } @@ -86,7 +86,7 @@ public function formatBool($value) /** * Formats date-time for use in a SQL statement. */ - public function formatDateTime(/*\DateTimeInterface*/ $value) + public function formatDateTime(\DateTimeInterface $value): string { return $value->format($this->fmtDateTime); } @@ -95,7 +95,7 @@ public function formatDateTime(/*\DateTimeInterface*/ $value) /** * Formats date-time interval for use in a SQL statement. */ - public function formatDateInterval(\DateInterval $value) + public function formatDateInterval(\DateInterval $value): string { throw new Nette\NotSupportedException; } @@ -104,7 +104,7 @@ public function formatDateInterval(\DateInterval $value) /** * Encodes string for use in a LIKE statement. */ - public function formatLike($value, $pos) + public function formatLike(string $value, int $pos): string { $value = addcslashes(substr($this->connection->quote($value), 1, -1), '%_\\'); return ($pos <= 0 ? "'%" : "'") . $value . ($pos >= 0 ? "%'" : "'") . " ESCAPE '\\'"; @@ -114,7 +114,7 @@ public function formatLike($value, $pos) /** * Injects LIMIT/OFFSET to the SQL query. */ - public function applyLimit(&$sql, $limit, $offset) + public function applyLimit(string &$sql, ?int $limit, ?int $offset) { if ($limit < 0 || $offset < 0) { throw new Nette\InvalidArgumentException('Negative offset or limit.'); @@ -129,7 +129,7 @@ public function applyLimit(&$sql, $limit, $offset) /** * Normalizes result row. */ - public function normalizeRow($row) + public function normalizeRow(array $row): array { foreach ($row as $key => $value) { unset($row[$key]); @@ -148,7 +148,7 @@ public function normalizeRow($row) /** * Returns list of tables. */ - public function getTables() + public function getTables(): array { $tables = []; foreach ($this->connection->query(" @@ -170,7 +170,7 @@ public function getTables() /** * Returns metadata for all columns in a table. */ - public function getColumns($table) + public function getColumns(string $table): array { $meta = $this->connection->query(" SELECT sql FROM sqlite_master WHERE type = 'table' AND name = {$this->connection->quote($table)} @@ -203,7 +203,7 @@ public function getColumns($table) /** * Returns metadata for all indexes in a table. */ - public function getIndexes($table) + public function getIndexes(string $table): array { $indexes = []; foreach ($this->connection->query("PRAGMA index_list({$this->delimite($table)})") as $row) { @@ -250,7 +250,7 @@ public function getIndexes($table) /** * Returns metadata for all foreign keys in a table. */ - public function getForeignKeys($table) + public function getForeignKeys(string $table): array { $keys = []; foreach ($this->connection->query("PRAGMA foreign_key_list({$this->delimite($table)})") as $row) { @@ -272,7 +272,7 @@ public function getForeignKeys($table) /** * Returns associative array of detected types (IReflection::FIELD_*) in result set. */ - public function getColumnTypes(\PDOStatement $statement) + public function getColumnTypes(\PDOStatement $statement): array { $types = []; $count = $statement->columnCount(); @@ -292,11 +292,7 @@ public function getColumnTypes(\PDOStatement $statement) } - /** - * @param string - * @return bool - */ - public function isSupported($item) + public function isSupported(string $item): bool { return $item === self::SUPPORT_MULTI_INSERT_AS_SELECT || $item === self::SUPPORT_SUBSELECT || $item === self::SUPPORT_MULTI_COLUMN_AS_OR_COND; } diff --git a/src/Database/Drivers/SqlsrvDriver.php b/src/Database/Drivers/SqlsrvDriver.php index 05d4a2ae1..3839a841e 100644 --- a/src/Database/Drivers/SqlsrvDriver.php +++ b/src/Database/Drivers/SqlsrvDriver.php @@ -33,7 +33,7 @@ public function initialize(Nette\Database\Connection $connection, array $options } - public function convertException(\PDOException $e) + public function convertException(\PDOException $e): Nette\Database\DriverException { return Nette\Database\DriverException::from($e); } @@ -45,7 +45,7 @@ public function convertException(\PDOException $e) /** * Delimites identifier for use in a SQL statement. */ - public function delimite($name) + public function delimite(string $name): string { /** @see https://msdn.microsoft.com/en-us/library/ms176027.aspx */ return '[' . str_replace(']', ']]', $name) . ']'; @@ -55,7 +55,7 @@ public function delimite($name) /** * Formats boolean for use in a SQL statement. */ - public function formatBool($value) + public function formatBool(bool $value): string { return $value ? '1' : '0'; } @@ -64,7 +64,7 @@ public function formatBool($value) /** * Formats date-time for use in a SQL statement. */ - public function formatDateTime(/*\DateTimeInterface*/ $value) + public function formatDateTime(\DateTimeInterface $value): string { /** @see https://msdn.microsoft.com/en-us/library/ms187819.aspx */ return $value->format("'Y-m-d\\TH:i:s'"); @@ -74,7 +74,7 @@ public function formatDateTime(/*\DateTimeInterface*/ $value) /** * Formats date-time interval for use in a SQL statement. */ - public function formatDateInterval(\DateInterval $value) + public function formatDateInterval(\DateInterval $value): string { throw new Nette\NotSupportedException; } @@ -83,7 +83,7 @@ public function formatDateInterval(\DateInterval $value) /** * Encodes string for use in a LIKE statement. */ - public function formatLike($value, $pos) + public function formatLike(string $value, int $pos): string { /** @see https://msdn.microsoft.com/en-us/library/ms179859.aspx */ $value = strtr($value, ["'" => "''", '%' => '[%]', '_' => '[_]', '[' => '[[]']); @@ -94,7 +94,7 @@ public function formatLike($value, $pos) /** * Injects LIMIT/OFFSET to the SQL query. */ - public function applyLimit(&$sql, $limit, $offset) + public function applyLimit(string &$sql, ?int $limit, ?int $offset) { if ($limit < 0 || $offset < 0) { throw new Nette\InvalidArgumentException('Negative offset or limit.'); @@ -121,7 +121,7 @@ public function applyLimit(&$sql, $limit, $offset) /** * Normalizes result row. */ - public function normalizeRow($row) + public function normalizeRow(array $row): array { return $row; } @@ -133,7 +133,7 @@ public function normalizeRow($row) /** * Returns list of tables. */ - public function getTables() + public function getTables(): array { $tables = []; foreach ($this->connection->query(" @@ -161,7 +161,7 @@ public function getTables() /** * Returns metadata for all columns in a table. */ - public function getColumns($table) + public function getColumns(string $table): array { $columns = []; foreach ($this->connection->query(" @@ -205,7 +205,7 @@ public function getColumns($table) /** * Returns metadata for all indexes in a table. */ - public function getIndexes($table) + public function getIndexes(string $table): array { $indexes = []; foreach ($this->connection->query(" @@ -241,7 +241,7 @@ public function getIndexes($table) /** * Returns metadata for all foreign keys in a table. */ - public function getForeignKeys($table) + public function getForeignKeys(string $table): array { // Does't work with multicolumn foreign keys $keys = []; @@ -271,7 +271,7 @@ public function getForeignKeys($table) /** * Returns associative array of detected types (IReflection::FIELD_*) in result set. */ - public function getColumnTypes(\PDOStatement $statement) + public function getColumnTypes(\PDOStatement $statement): array { $types = []; $count = $statement->columnCount(); @@ -287,11 +287,7 @@ public function getColumnTypes(\PDOStatement $statement) } - /** - * @param string - * @return bool - */ - public function isSupported($item) + public function isSupported(string $item): bool { return $item === self::SUPPORT_SUBSELECT; } diff --git a/src/Database/Helpers.php b/src/Database/Helpers.php index ab1beca4b..f5b28a2db 100644 --- a/src/Database/Helpers.php +++ b/src/Database/Helpers.php @@ -38,9 +38,8 @@ class Helpers /** * Displays complete result set as HTML table for debug purposes. - * @return void */ - public static function dumpResult(ResultSet $result) + public static function dumpResult(ResultSet $result): void { echo "\n\n\n"; if (!$result->getColumnCount()) { @@ -74,10 +73,8 @@ public static function dumpResult(ResultSet $result) /** * Returns syntax highlighted SQL command. - * @param string - * @return string */ - public static function dumpSql($sql, array $params = NULL, Connection $connection = NULL) + public static function dumpSql(string $sql, array $params = NULL, Connection $connection = NULL): string { 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|SET|VALUES|LEFT\s+JOIN|INNER\s+JOIN|TRUNCATE'; static $keywords2 = 'ALL|DISTINCT|DISTINCTROW|IGNORE|AS|USING|ON|AND|OR|IN|IS|NOT|NULL|[RI]?LIKE|REGEXP|TRUE|FALSE'; @@ -144,9 +141,8 @@ public static function dumpSql($sql, array $params = NULL, Connection $connectio /** * Common column type detection. - * @return array */ - public static function detectTypes(\PDOStatement $statement) + public static function detectTypes(\PDOStatement $statement): array { $types = []; $count = $statement->columnCount(); // driver must be meta-aware, see PHP bugs #53782, #54695 @@ -162,11 +158,9 @@ public static function detectTypes(\PDOStatement $statement) /** * Heuristic column type detection. - * @param string - * @return string * @internal */ - public static function detectType($type) + public static function detectType(string $type): string { static $cache; if (!isset($cache[$type])) { @@ -185,7 +179,7 @@ public static function detectType($type) * Import SQL dump from file - extremely fast. * @return int count of commands */ - public static function loadFromFile(Connection $connection, $file) + public static function loadFromFile(Connection $connection, $file): int { @set_time_limit(0); // @ function may be disabled @@ -222,7 +216,7 @@ public static function loadFromFile(Connection $connection, $file) } - public static function createDebugPanel($connection, $explain = TRUE, $name = NULL) + public static function createDebugPanel($connection, bool $explain = TRUE, $name = NULL) { $panel = new Nette\Bridges\DatabaseTracy\ConnectionPanel($connection); $panel->explain = $explain; @@ -234,9 +228,8 @@ public static function createDebugPanel($connection, $explain = TRUE, $name = NU /** * Reformat source to key -> value pairs. - * @return array */ - public static function toPairs(array $rows, $key = NULL, $value = NULL) + public static function toPairs(array $rows, $key = NULL, $value = NULL): array { if (!$rows) { return []; @@ -271,10 +264,8 @@ public static function toPairs(array $rows, $key = NULL, $value = NULL) /** * Finds duplicate columns in select statement - * @param \PDOStatement - * @return string */ - public static function findDuplicates(\PDOStatement $statement) + public static function findDuplicates(\PDOStatement $statement): string { $cols = []; for ($i = 0; $i < $statement->columnCount(); $i++) { diff --git a/src/Database/IConventions.php b/src/Database/IConventions.php index a4a77c00b..3c13f9807 100644 --- a/src/Database/IConventions.php +++ b/src/Database/IConventions.php @@ -17,10 +17,9 @@ interface IConventions /** * Returns primary key for table. - * @param string * @return string|array|NULL */ - function getPrimary($table); + function getPrimary(string $table); /** * Returns referenced table & referenced column. @@ -32,7 +31,7 @@ function getPrimary($table); * @return array|NULL array(referenced table, referenced column) * @throws AmbiguousReferenceKeyException */ - function getHasManyReference($table, $key); + function getHasManyReference(string $table, string $key): ?array; /** * Returns referenced table & referencing column. @@ -44,6 +43,6 @@ function getHasManyReference($table, $key); * @param string referencing key * @return array|NULL array(referenced table, referencing column) */ - function getBelongsToReference($table, $key); + function getBelongsToReference(string $table, string $key): ?array; } diff --git a/src/Database/IRowContainer.php b/src/Database/IRowContainer.php index 9eb0b483f..48a07aaee 100644 --- a/src/Database/IRowContainer.php +++ b/src/Database/IRowContainer.php @@ -18,9 +18,8 @@ interface IRowContainer extends \Traversable /** * Fetches single row object. - * @return IRow|NULL if there is no row */ - function fetch(); + function fetch(): ?IRow; /** * Fetches single field. @@ -33,21 +32,19 @@ function fetchField($column = 0); * Fetches all rows as associative array. * @param string|int column name used for an array key or NULL for numeric index * @param string|int column name used for an array value or NULL for the whole row - * @return array */ - function fetchPairs($key = NULL, $value = NULL); + function fetchPairs($key = NULL, $value = NULL): array; /** * Fetches all rows. * @return IRow[] */ - function fetchAll(); + function fetchAll(): array; /** * Fetches all rows and returns associative tree. * @param string associative descriptor - * @return array */ - function fetchAssoc($path); + function fetchAssoc(string $path): array; } diff --git a/src/Database/IStructure.php b/src/Database/IStructure.php index fc34eeede..4a1e89a5d 100644 --- a/src/Database/IStructure.php +++ b/src/Database/IStructure.php @@ -29,48 +29,36 @@ interface IStructure /** * Returns tables list. - * @return array */ - function getTables(); + function getTables(): array; /** * Returns table columns list. - * @param string - * @return array */ - function getColumns($table); + function getColumns(string $table): array; /** * Returns table primary key. - * @param string * @return string|array|NULL */ - function getPrimaryKey($table); + function getPrimaryKey(string $table); /** * Returns table primary key sequence. - * @param string - * @return string|NULL */ - function getPrimaryKeySequence($table); + function getPrimaryKeySequence(string $table): ?string; /** * Returns hasMany reference. * If a targetTable is not provided, returns references for all tables. - * @param string - * @param string|NULL - * @return array|NULL */ - function getHasManyReference($table, $targetTable = NULL); + function getHasManyReference(string $table, string $targetTable = NULL): ?array; /** * Returns belongsTo reference. * If a column is not provided, returns references for all columns. - * @param string - * @param string|NULL - * @return array|NULL */ - function getBelongsToReference($table, $column = NULL); + function getBelongsToReference(string $table, string $column = NULL): ?array; /** * Rebuilds database structure cache. @@ -80,8 +68,7 @@ function rebuild(); /** * Returns true if database cached structure has been rebuilt. - * @return bool */ - function isRebuilt(); + function isRebuilt(): bool; } diff --git a/src/Database/ISupplementalDriver.php b/src/Database/ISupplementalDriver.php index 12b8a43c5..18c863202 100644 --- a/src/Database/ISupplementalDriver.php +++ b/src/Database/ISupplementalDriver.php @@ -24,64 +24,46 @@ interface ISupplementalDriver /** * Initializes connection. - * @return void */ function initialize(Connection $connection, array $options); - /** - * @return DriverException - */ - function convertException(\PDOException $e); + function convertException(\PDOException $e): DriverException; /** * Delimites identifier for use in a SQL statement. - * @param string - * @return string */ - function delimite($name); + function delimite(string $name): string; /** * Formats boolean for use in a SQL statement. - * @param bool - * @return string */ - function formatBool($value); + function formatBool(bool $value): string; /** * Formats date-time for use in a SQL statement. - * @return string */ - function formatDateTime(/*\DateTimeInterface*/ $value); + function formatDateTime(\DateTimeInterface $value): string; /** * Formats date-time interval for use in a SQL statement. - * @return string */ - function formatDateInterval(\DateInterval $value); + function formatDateInterval(\DateInterval $value): string; /** * Encodes string for use in a LIKE statement. - * @param string - * @param int - * @return string */ - function formatLike($value, $pos); + function formatLike(string $value, int $pos): string; /** * Injects LIMIT/OFFSET to the SQL query. * @param string SQL query that will be modified. - * @param int|NULL - * @param int|NULL - * @return void */ - function applyLimit(&$sql, $limit, $offset); + function applyLimit(string &$sql, ?int $limit, ?int $offset); /** * Normalizes result row. - * @param array - * @return array */ - function normalizeRow($row); + function normalizeRow(array $row): array; /********************* reflection ****************d*g**/ @@ -91,41 +73,34 @@ function normalizeRow($row); * Returns list of tables. * @return array of [name [, (bool) view]] */ - function getTables(); + function getTables(): array; /** * Returns metadata for all columns in a table. - * @param string * @return array of [name, nativetype, primary [, table, fullname, (int) size, (bool) nullable, (mixed) default, (bool) autoincrement, (array) vendor]] */ - function getColumns($table); + function getColumns(string $table): array; /** * Returns metadata for all indexes in a table. - * @param string * @return array of [name, (array of names) columns [, (bool) unique, (bool) primary]] */ - function getIndexes($table); + function getIndexes(string $table): array; /** * Returns metadata for all foreign keys in a table. - * @param string - * @return array */ - function getForeignKeys($table); + function getForeignKeys(string $table): array; /** * Returns associative array of detected types (IStructure::FIELD_*) in result set. - * @param \PDOStatement - * @return array */ - function getColumnTypes(\PDOStatement $statement); + function getColumnTypes(\PDOStatement $statement): array; /** * Cheks if driver supports specific property * @param string self::SUPPORT_* property - * @return bool */ - function isSupported($item); + function isSupported(string $item): bool; } diff --git a/src/Database/ResultSet.php b/src/Database/ResultSet.php index 607460d6d..975885dba 100644 --- a/src/Database/ResultSet.php +++ b/src/Database/ResultSet.php @@ -82,10 +82,7 @@ public function __construct(Connection $connection, $queryString, array $params) } - /** - * @return Connection - */ - public function getConnection() + public function getConnection(): Connection { return $this->connection; } @@ -93,54 +90,38 @@ public function getConnection() /** * @internal - * @return \PDOStatement */ - public function getPdoStatement() + public function getPdoStatement(): \PDOStatement { return $this->pdoStatement; } - /** - * @return string - */ - public function getQueryString() + public function getQueryString(): string { return $this->queryString; } - /** - * @return array - */ - public function getParameters() + public function getParameters(): array { return $this->params; } - /** - * @return int - */ - public function getColumnCount() + public function getColumnCount(): ?int { return $this->pdoStatement ? $this->pdoStatement->columnCount() : NULL; } - /** - * @return int - */ - public function getRowCount() + public function getRowCount(): ?int { return $this->pdoStatement ? $this->pdoStatement->rowCount() : NULL; } - /** - * @return float - */ - public function getTime() + public function getTime(): float { return $this->time; } @@ -148,10 +129,8 @@ public function getTime() /** * Normalizes result row. - * @param array - * @return array */ - public function normalizeRow($row) + public function normalizeRow(array $row): array { if ($this->types === NULL) { $this->types = (array) $this->supplementalDriver->getColumnTypes($this->pdoStatement); @@ -196,9 +175,8 @@ public function normalizeRow($row) /** * Displays complete result set as HTML table for debug purposes. - * @return void */ - public function dump() + public function dump(): void { Helpers::dumpResult($this); } @@ -249,7 +227,7 @@ public function valid() /** * @inheritDoc */ - public function fetch() + public function fetch(): ?IRow { $data = $this->pdoStatement ? $this->pdoStatement->fetch() : NULL; if (!$data) { @@ -286,7 +264,7 @@ public function fetchField($column = 0) /** * @inheritDoc */ - public function fetchPairs($key = NULL, $value = NULL) + public function fetchPairs($key = NULL, $value = NULL): array { return Helpers::toPairs($this->fetchAll(), $key, $value); } @@ -295,7 +273,7 @@ public function fetchPairs($key = NULL, $value = NULL) /** * @inheritDoc */ - public function fetchAll() + public function fetchAll(): array { if ($this->results === NULL) { $this->results = iterator_to_array($this); @@ -307,7 +285,7 @@ public function fetchAll() /** * @inheritDoc */ - public function fetchAssoc($path) + public function fetchAssoc(string $path): array { return Nette\Utils\Arrays::associate($this->fetchAll(), $path); } diff --git a/src/Database/Row.php b/src/Database/Row.php index 90ea649bf..6e477061c 100644 --- a/src/Database/Row.php +++ b/src/Database/Row.php @@ -46,9 +46,8 @@ public function offsetGet($key) /** * Checks if $key exists. * @param mixed key or index - * @return bool */ - public function offsetExists($key) + public function offsetExists($key): bool { if (is_int($key)) { return (bool) current(array_slice((array) $this, $key, 1)); diff --git a/src/Database/SqlLiteral.php b/src/Database/SqlLiteral.php index 9fa4f090b..48a29a2d1 100644 --- a/src/Database/SqlLiteral.php +++ b/src/Database/SqlLiteral.php @@ -26,26 +26,20 @@ class SqlLiteral private $parameters; - public function __construct($value, array $parameters = []) + public function __construct(string $value, array $parameters = []) { $this->value = (string) $value; $this->parameters = $parameters; } - /** - * @return array - */ - public function getParameters() + public function getParameters(): array { return $this->parameters; } - /** - * @return string - */ - public function __toString() + public function __toString(): string { return $this->value; } diff --git a/src/Database/SqlPreprocessor.php b/src/Database/SqlPreprocessor.php index f3d7c0038..aa60beef4 100644 --- a/src/Database/SqlPreprocessor.php +++ b/src/Database/SqlPreprocessor.php @@ -46,10 +46,9 @@ public function __construct(Connection $connection) /** - * @param array * @return array of [sql, params] */ - public function process($params) + public function process(array $params): array { $this->params = $params; $this->counter = 0; @@ -258,7 +257,7 @@ private function formatValue($value, $mode = NULL) } - private function delimite($name) + private function delimite(string $name): string { return implode('.', array_map([$this->driver, 'delimite'], explode('.', $name))); } diff --git a/src/Database/Structure.php b/src/Database/Structure.php index e627267cd..e71c33843 100644 --- a/src/Database/Structure.php +++ b/src/Database/Structure.php @@ -39,14 +39,14 @@ public function __construct(Connection $connection, Nette\Caching\IStorage $cach } - public function getTables() + public function getTables(): array { $this->needStructure(); return $this->structure['tables']; } - public function getColumns($table) + public function getColumns(string $table): array { $this->needStructure(); $table = $this->resolveFQTableName($table); @@ -55,7 +55,7 @@ public function getColumns($table) } - public function getPrimaryKey($table) + public function getPrimaryKey(string $table) { $this->needStructure(); $table = $this->resolveFQTableName($table); @@ -68,7 +68,7 @@ public function getPrimaryKey($table) } - public function getPrimaryKeySequence($table) + public function getPrimaryKeySequence(string $table): ?string { $this->needStructure(); $table = $this->resolveFQTableName($table); @@ -92,7 +92,7 @@ public function getPrimaryKeySequence($table) } - public function getHasManyReference($table, $targetTable = NULL) + public function getHasManyReference(string $table, string $targetTable = NULL): ?array { $this->needStructure(); $table = $this->resolveFQTableName($table); @@ -116,7 +116,7 @@ public function getHasManyReference($table, $targetTable = NULL) } - public function getBelongsToReference($table, $column = NULL) + public function getBelongsToReference(string $table, string $column = NULL): ?array { $this->needStructure(); $table = $this->resolveFQTableName($table); @@ -144,7 +144,7 @@ public function rebuild() } - public function isRebuilt() + public function isRebuilt(): bool { return $this->isRebuilt; } @@ -219,7 +219,7 @@ protected function analyzePrimaryKey(array $columns) } - protected function analyzeForeignKeys(&$structure, $table) + protected function analyzeForeignKeys(&$structure, string $table) { $lowerTable = strtolower($table); foreach ($this->connection->getSupplementalDriver()->getForeignKeys($table) as $row) { @@ -235,7 +235,7 @@ protected function analyzeForeignKeys(&$structure, $table) } - protected function resolveFQTableName($table) + protected function resolveFQTableName(string $table) { $name = strtolower($table); if (isset($this->structure['columns'][$name])) { diff --git a/src/Database/Table/ActiveRow.php b/src/Database/Table/ActiveRow.php index 04e747b09..ac8f3c39d 100644 --- a/src/Database/Table/ActiveRow.php +++ b/src/Database/Table/ActiveRow.php @@ -47,7 +47,7 @@ public function setTable(Selection $table) /** * @internal */ - public function getTable() + public function getTable(): Selection { return $this->table; } @@ -66,10 +66,7 @@ public function __toString() } - /** - * @return array - */ - public function toArray() + public function toArray(): array { $this->accessColumn(NULL); return $this->data; @@ -78,10 +75,9 @@ public function toArray() /** * Returns primary key value. - * @param bool * @return mixed possible int, string, array, object (Nette\Utils\DateTime) */ - public function getPrimary($throw = TRUE) + public function getPrimary(bool $throw = TRUE) { $primary = $this->table->getPrimary($throw); if ($primary === NULL) { @@ -115,10 +111,8 @@ public function getPrimary($throw = TRUE) /** * Returns row signature (composition of primary keys) - * @param bool - * @return string */ - public function getSignature($throw = TRUE) + public function getSignature(bool $throw = TRUE): string { return implode('|', (array) $this->getPrimary($throw)); } @@ -126,11 +120,9 @@ public function getSignature($throw = TRUE) /** * Returns referenced row. - * @param string - * @param string * @return IRow|NULL if the row does not exist */ - public function ref($key, $throughColumn = NULL) + public function ref(string $key, string $throughColumn = NULL): ?IRow { $row = $this->table->getReferencedTable($this, $key, $throughColumn); if ($row === FALSE) { @@ -143,11 +135,8 @@ public function ref($key, $throughColumn = NULL) /** * Returns referencing rows. - * @param string - * @param string - * @return GroupedSelection */ - public function related($key, $throughColumn = NULL) + public function related(string $key, string $throughColumn = NULL): GroupedSelection { $groupedSelection = $this->table->getReferencingTable($key, $throughColumn, $this[$this->table->getPrimary()]); if (!$groupedSelection) { @@ -160,10 +149,8 @@ public function related($key, $throughColumn = NULL) /** * Updates row. - * @param iterable (column => value) - * @return bool */ - public function update($data) + public function update(iterable $data): bool { if ($data instanceof \Traversable) { $data = iterator_to_array($data); @@ -198,7 +185,7 @@ public function update($data) * Deletes row. * @return int number of affected rows */ - public function delete() + public function delete(): int { $res = $this->table->createSelectionInstance() ->wherePrimary($this->getPrimary()) @@ -229,9 +216,8 @@ public function getIterator() * Stores value in column. * @param string * @param mixed - * @return void */ - public function offsetSet($column, $value) + public function offsetSet($column, $value): void { $this->__set($column, $value); } @@ -251,9 +237,8 @@ public function offsetGet($column) /** * Tests if column exists. * @param string - * @return bool */ - public function offsetExists($column) + public function offsetExists($column): bool { return $this->__isset($column); } @@ -262,9 +247,8 @@ public function offsetExists($column) /** * Removes column from data. * @param string - * @return void */ - public function offsetUnset($column) + public function offsetUnset($column): void { $this->__unset($column); } @@ -277,11 +261,10 @@ public function __set($column, $value) /** - * @param string * @return ActiveRow|mixed * @throws Nette\MemberAccessException */ - public function &__get($key) + public function &__get(string $key) { if ($this->accessColumn($key)) { return $this->data[$key]; @@ -318,7 +301,7 @@ public function __unset($key) /** * @internal */ - public function accessColumn($key, $selectColumn = TRUE) + public function accessColumn($key, bool $selectColumn = TRUE) { if ($this->table->accessColumn($key, $selectColumn) && !$this->dataRefreshed) { if (!isset($this->table[$this->getSignature()])) { diff --git a/src/Database/Table/GroupedSelection.php b/src/Database/Table/GroupedSelection.php index e6eee30dc..fa12b077e 100644 --- a/src/Database/Table/GroupedSelection.php +++ b/src/Database/Table/GroupedSelection.php @@ -35,14 +35,10 @@ class GroupedSelection extends Selection /** * Creates filtered and grouped table representation. - * @param Context - * @param IConventions - * @param string database table name - * @param string joining column - * @param Selection - * @param Nette\Caching\IStorage|NULL + * @param string $tableName database table name + * @param string $column joining column */ - public function __construct(Context $context, IConventions $conventions, $tableName, $column, Selection $refTable, Nette\Caching\IStorage $cacheStorage = NULL) + public function __construct(Context $context, IConventions $conventions, string $tableName, string $column, Selection $refTable, Nette\Caching\IStorage $cacheStorage = NULL) { $this->refTable = $refTable; $this->column = $column; @@ -56,7 +52,7 @@ public function __construct(Context $context, IConventions $conventions, $tableN * @param int primary key of grouped rows * @return static */ - public function setActive($active) + public function setActive(int $active) { $this->active = $active; return $this; @@ -79,7 +75,7 @@ public function select($columns, ...$params) /** * @return static */ - public function order($columns, ...$params) + public function order(string $columns, ...$params) { if (!$this->sqlBuilder->getOrder()) { // improve index utilization @@ -93,7 +89,7 @@ public function order($columns, ...$params) /********************* aggregations ****************d*g**/ - public function aggregation($function) + public function aggregation(string $function): int { $aggregation = &$this->getRefTable($refPath)->aggregation[$refPath . $function . $this->sqlBuilder->getSelectQueryHash($this->getPreviousAccessedColumns())]; @@ -116,13 +112,11 @@ public function aggregation($function) return $val; } } + return 0; } - /** - * @return int - */ - public function count($column = NULL) + public function count(string $column = NULL): int { $return = parent::count($column); return $return ?? 0; @@ -132,7 +126,7 @@ public function count($column = NULL) /********************* internal ****************d*g**/ - protected function execute() + protected function execute(): void { if ($this->rows !== NULL) { $this->observeCache = $this; @@ -184,10 +178,7 @@ protected function execute() } - /** - * @return Selection - */ - protected function getRefTable(&$refPath) + protected function getRefTable(&$refPath): Selection { $refObj = $this->refTable; $refPath = $this->name . '.'; @@ -200,7 +191,7 @@ protected function getRefTable(&$refPath) } - protected function loadRefCache() + protected function loadRefCache(): void { $hash = $this->getSpecificCacheKey(); $referencing = &$this->refCache['referencing'][$this->getGeneralCacheKey()]; @@ -216,7 +207,7 @@ protected function loadRefCache() } - protected function emptyResultSet($saveCache = TRUE, $deleteRererencedCache = TRUE) + protected function emptyResultSet(bool $saveCache = TRUE, bool $deleteRererencedCache = TRUE): void { parent::emptyResultSet($saveCache, FALSE); } @@ -243,7 +234,7 @@ public function insert($data) } - public function update($data) + public function update(iterable $data): int { $builder = $this->sqlBuilder; @@ -256,7 +247,7 @@ public function update($data) } - public function delete() + public function delete(): int { $builder = $this->sqlBuilder; diff --git a/src/Database/Table/IRow.php b/src/Database/Table/IRow.php index e031f741e..9ebdd5110 100644 --- a/src/Database/Table/IRow.php +++ b/src/Database/Table/IRow.php @@ -20,39 +20,28 @@ interface IRow extends Database\IRow function setTable(Selection $name); - /** - * @return Selection - */ - function getTable(); + function getTable(): Selection; /** * Returns primary key value. - * @param bool * @return mixed */ - function getPrimary($throw = TRUE); + function getPrimary(bool $throw = TRUE); /** * Returns row signature (composition of primary keys) - * @param bool - * @return string */ - function getSignature($throw = TRUE); + function getSignature(bool $throw = TRUE): string; /** * Returns referencing rows. - * @param string - * @param string - * @return GroupedSelection */ - function related($key, $throughColumn = NULL); + function related(string $key, string $throughColumn = NULL): GroupedSelection; /** * Returns referenced row. - * @param string - * @param string * @return IRow|NULL if the row does not exist */ - function ref($key, $throughColumn = NULL); + function ref(string $key, string $throughColumn = NULL): ?IRow; } diff --git a/src/Database/Table/Selection.php b/src/Database/Table/Selection.php index 98851d955..67255226f 100644 --- a/src/Database/Table/Selection.php +++ b/src/Database/Table/Selection.php @@ -82,12 +82,9 @@ class Selection implements \Iterator, IRowContainer, \ArrayAccess, \Countable /** * Creates filtered table representation. - * @param Context - * @param IConventions - * @param string table name - * @param Nette\Caching\IStorage|NULL + * @param string $tableName table name */ - public function __construct(Context $context, IConventions $conventions, $tableName, Nette\Caching\IStorage $cacheStorage = NULL) + public function __construct(Context $context, IConventions $conventions, string $tableName, Nette\Caching\IStorage $cacheStorage = NULL) { $this->context = $context; $this->conventions = $conventions; @@ -112,20 +109,16 @@ public function __clone() } - /** - * @return string - */ - public function getName() + public function getName(): string { return $this->name; } /** - * @param bool * @return string|array|NULL */ - public function getPrimary($throw = TRUE) + public function getPrimary(bool $throw = TRUE) { if ($this->primary === NULL && $throw) { throw new \LogicException("Table '{$this->name}' does not have a primary key."); @@ -134,10 +127,7 @@ public function getPrimary($throw = TRUE) } - /** - * @return string|NULL - */ - public function getPrimarySequence() + public function getPrimarySequence(): ?string { if ($this->primarySequence === FALSE) { $this->primarySequence = $this->context->getStructure()->getPrimaryKeySequence($this->name); @@ -148,20 +138,16 @@ public function getPrimarySequence() /** - * @param string * @return static */ - public function setPrimarySequence($sequence) + public function setPrimarySequence(string $sequence) { $this->primarySequence = $sequence; return $this; } - /** - * @return string - */ - public function getSql() + public function getSql(): string { return $this->sqlBuilder->buildSelectQuery($this->getPreviousAccessedColumns()); } @@ -187,9 +173,8 @@ public function getPreviousAccessedColumns() /** * @internal - * @return SqlBuilder */ - public function getSqlBuilder() + public function getSqlBuilder(): SqlBuilder { return $this->sqlBuilder; } @@ -203,7 +188,7 @@ public function getSqlBuilder() * @param mixed primary key * @return IRow|NULL if there is no such row */ - public function get($key) + public function get($key): ?IRow { $clone = clone $this; return $clone->wherePrimary($key)->fetch(); @@ -213,7 +198,7 @@ public function get($key) /** * @inheritDoc */ - public function fetch() + public function fetch(): ?Nette\Database\IRow { $this->execute(); $return = current($this->data); @@ -245,7 +230,7 @@ public function fetchField($column = NULL) /** * @inheritDoc */ - public function fetchPairs($key = NULL, $value = NULL) + public function fetchPairs($key = NULL, $value = NULL): array { return Nette\Database\Helpers::toPairs($this->fetchAll(), $key, $value); } @@ -254,7 +239,7 @@ public function fetchPairs($key = NULL, $value = NULL) /** * @inheritDoc */ - public function fetchAll() + public function fetchAll(): array { return iterator_to_array($this); } @@ -263,7 +248,7 @@ public function fetchAll() /** * @inheritDoc */ - public function fetchAssoc($path) + public function fetchAssoc(string $path): array { $rows = array_map('iterator_to_array', $this->fetchAll()); return Nette\Utils\Arrays::associate($rows, $path); @@ -331,7 +316,7 @@ public function where($condition, ...$params) * @param mixed * @return static */ - public function joinWhere($tableChain, $condition, ...$params) + public function joinWhere(string $tableChain, string $condition, ...$params) { $this->condition($condition, $params, $tableChain); return $this; @@ -341,9 +326,8 @@ public function joinWhere($tableChain, $condition, ...$params) /** * Adds condition, more calls appends with AND. * @param string|string[] condition possibly containing ? - * @return void */ - protected function condition($condition, array $params, $tableChain = NULL) + protected function condition($condition, array $params, $tableChain = NULL): void { $this->emptyResultSet(); if (is_array($condition) && $params === []) { // where(array('column1' => 1, 'column2 > ?' => 2)) @@ -401,7 +385,7 @@ public function whereOr(array $parameters) * @param string for example 'column1, column2 DESC' * @return static */ - public function order($columns, ...$params) + public function order(string $columns, ...$params) { $this->emptyResultSet(); $this->sqlBuilder->addOrder($columns, ...$params); @@ -411,11 +395,9 @@ public function order($columns, ...$params) /** * Sets limit clause, more calls rewrite old values. - * @param int - * @param int * @return static */ - public function limit($limit, $offset = NULL) + public function limit(int $limit, int $offset = NULL) { $this->emptyResultSet(); $this->sqlBuilder->setLimit($limit, $offset); @@ -425,11 +407,9 @@ public function limit($limit, $offset = NULL) /** * Sets offset using page number, more calls rewrite old values. - * @param int - * @param int * @return static */ - public function page($page, $itemsPerPage, &$numOfPages = NULL) + public function page(int $page, int $itemsPerPage, &$numOfPages = NULL) { if (func_num_args() > 2) { $numOfPages = (int) ceil($this->count('*') / $itemsPerPage); @@ -443,10 +423,9 @@ public function page($page, $itemsPerPage, &$numOfPages = NULL) /** * Sets group clause, more calls rewrite old value. - * @param string * @return static */ - public function group($columns, ...$params) + public function group(string $columns, ...$params) { $this->emptyResultSet(); $this->sqlBuilder->setGroup($columns, ...$params); @@ -456,10 +435,9 @@ public function group($columns, ...$params) /** * Sets having clause, more calls rewrite old value. - * @param string * @return static */ - public function having($having, ...$params) + public function having(string $having, ...$params) { $this->emptyResultSet(); $this->sqlBuilder->setHaving($having, ...$params); @@ -469,11 +447,9 @@ public function having($having, ...$params) /** * Aliases table. Example ':book:book_tag.tag', 'tg' - * @param string - * @param string * @return static */ - public function alias($tableChain, $alias) + public function alias(string $tableChain, string $alias) { $this->sqlBuilder->addAlias($tableChain, $alias); return $this; @@ -486,9 +462,8 @@ public function alias($tableChain, $alias) /** * Executes aggregation function. * @param string select call in "FUNCTION(column)" format - * @return int */ - public function aggregation($function) + public function aggregation(string $function): int { $selection = $this->createSelectionInstance(); $selection->getSqlBuilder()->importConditions($this->getSqlBuilder()); @@ -502,9 +477,8 @@ public function aggregation($function) /** * Counts number of rows. * @param string if it is not provided returns count of result rows, otherwise runs new sql counting query - * @return int */ - public function count($column = NULL) + public function count(string $column = NULL): int { if (!$column) { $this->execute(); @@ -516,10 +490,8 @@ public function count($column = NULL) /** * Returns minimum value from a column. - * @param string - * @return int */ - public function min($column) + public function min(string $column): int { return $this->aggregation("MIN($column)"); } @@ -527,10 +499,8 @@ public function min($column) /** * Returns maximum value from a column. - * @param string - * @return int */ - public function max($column) + public function max(string $column): int { return $this->aggregation("MAX($column)"); } @@ -538,10 +508,8 @@ public function max($column) /** * Returns sum of values in a column. - * @param string - * @return int */ - public function sum($column) + public function sum(string $column): int { return $this->aggregation("SUM($column)"); } @@ -593,43 +561,31 @@ protected function execute() } - /** - * @return ActiveRow - */ - protected function createRow(array $row) + protected function createRow(array $row): ActiveRow { return new ActiveRow($row, $this); } - /** - * @return self - */ - public function createSelectionInstance($table = NULL) + public function createSelectionInstance($table = NULL): self { return new self($this->context, $this->conventions, $table ?: $this->name, $this->cache ? $this->cache->getStorage() : NULL); } - /** - * @return GroupedSelection - */ - protected function createGroupedSelectionInstance($table, $column) + protected function createGroupedSelectionInstance($table, $column): GroupedSelection { return new GroupedSelection($this->context, $this->conventions, $table, $column, $this, $this->cache ? $this->cache->getStorage() : NULL); } - /** - * @return Nette\Database\ResultSet - */ - protected function query($query) + protected function query($query): Nette\Database\ResultSet { return $this->context->queryArgs($query, $this->sqlBuilder->getParameters()); } - protected function emptyResultSet($clearCache = TRUE, $deleteRererencedCache = TRUE) + protected function emptyResultSet(bool $clearCache = TRUE, bool $deleteRererencedCache = TRUE): void { if ($this->rows !== NULL && $clearCache) { $this->saveCacheState(); @@ -650,7 +606,7 @@ protected function emptyResultSet($clearCache = TRUE, $deleteRererencedCache = T } - protected function saveCacheState() + protected function saveCacheState(): void { if ($this->observeCache === $this && $this->cache && !$this->sqlBuilder->getSelect() && $this->accessedColumns !== $this->previousAccessedColumns) { $previousAccessed = $this->cache->load($this->getGeneralCacheKey()); @@ -681,7 +637,7 @@ protected function getRefTable(&$refPath) /** * Loads refCache references */ - protected function loadRefCache() + protected function loadRefCache(): void { } @@ -689,9 +645,8 @@ protected function loadRefCache() /** * Returns general cache key independent on query parameters or sql limit * Used e.g. for previously accessed columns caching - * @return string */ - protected function getGeneralCacheKey() + protected function getGeneralCacheKey(): string { if ($this->generalCacheKey) { return $this->generalCacheKey; @@ -711,9 +666,8 @@ protected function getGeneralCacheKey() /** * Returns object specific cache key dependent on query parameters * Used e.g. for reference memory caching - * @return string */ - protected function getSpecificCacheKey() + protected function getSpecificCacheKey(): string { if ($this->specificCacheKey) { return $this->specificCacheKey; @@ -726,10 +680,9 @@ protected function getSpecificCacheKey() /** * @internal * @param string|NULL column name or NULL to reload all columns - * @param bool * @return bool if selection requeried for more columns. */ - public function accessColumn($key, $selectColumn = TRUE) + public function accessColumn(?string $key, bool $selectColumn = TRUE): bool { if (!$this->cache) { return FALSE; @@ -783,9 +736,8 @@ public function accessColumn($key, $selectColumn = TRUE) /** * @internal - * @param string */ - public function removeAccessColumn($key) + public function removeAccessColumn(string $key): void { if ($this->cache && is_array($this->accessedColumns)) { $this->accessedColumns[$key] = FALSE; @@ -795,9 +747,8 @@ public function removeAccessColumn($key) /** * Returns if selection requeried for more columns. - * @return bool */ - public function getDataRefreshed() + public function getDataRefreshed(): bool { return $this->dataRefreshed; } @@ -877,10 +828,9 @@ public function insert($data) /** * Updates all rows in result set. * Joins in UPDATE are supported only in MySQL - * @param iterable ($column => $value) * @return int number of affected rows */ - public function update($data) + public function update(iterable $data): int { if ($data instanceof \Traversable) { $data = iterator_to_array($data); @@ -904,7 +854,7 @@ public function update($data) * Deletes all rows in result set. * @return int number of affected rows */ - public function delete() + public function delete(): int { return $this->query($this->sqlBuilder->buildDeleteQuery())->getRowCount(); } @@ -915,12 +865,9 @@ public function delete() /** * Returns referenced row. - * @param ActiveRow - * @param string|NULL - * @param string|NULL * @return ActiveRow|NULL|FALSE NULL if the row does not exist, FALSE if the relationship does not exist */ - public function getReferencedTable(ActiveRow $row, $table, $column = NULL) + public function getReferencedTable(ActiveRow $row, ?string $table, string $column = NULL) { if (!$column) { $belongsTo = $this->conventions->getBelongsToReference($this->name, $table); @@ -964,12 +911,9 @@ public function getReferencedTable(ActiveRow $row, $table, $column = NULL) /** * Returns referencing rows. - * @param string - * @param string - * @param int primary key - * @return GroupedSelection|NULL + * @param int $active primary key */ - public function getReferencingTable($table, $column, $active = NULL) + public function getReferencingTable(string $table, string $column = NULL, int $active = NULL): ?GroupedSelection { if (strpos($table, '.') !== FALSE) { [$table, $column] = explode('.', $table); @@ -996,7 +940,7 @@ public function getReferencingTable($table, $column, $active = NULL) /********************* interface Iterator ****************d*g**/ - public function rewind() + public function rewind(): void { $this->execute(); $this->keys = array_keys($this->data); @@ -1024,7 +968,7 @@ public function key() } - public function next() + public function next(): void { do { next($this->keys); @@ -1032,7 +976,7 @@ public function next() } - public function valid() + public function valid(): bool { return current($this->keys) !== FALSE; } @@ -1045,9 +989,8 @@ public function valid() * Mimic row. * @param string row ID * @param IRow - * @return void */ - public function offsetSet($key, $value) + public function offsetSet($key, $value): void { $this->execute(); $this->rows[$key] = $value; @@ -1059,7 +1002,7 @@ public function offsetSet($key, $value) * @param string row ID * @return IRow|NULL if there is no such row */ - public function offsetGet($key) + public function offsetGet($key): ?IRow { $this->execute(); return $this->rows[$key]; @@ -1069,9 +1012,8 @@ public function offsetGet($key) /** * Tests if row exists. * @param string row ID - * @return bool */ - public function offsetExists($key) + public function offsetExists($key): bool { $this->execute(); return isset($this->rows[$key]); @@ -1081,9 +1023,8 @@ public function offsetExists($key) /** * Removes row from result set. * @param string row ID - * @return void */ - public function offsetUnset($key) + public function offsetUnset($key): void { $this->execute(); unset($this->rows[$key], $this->data[$key]); diff --git a/src/Database/Table/SqlBuilder.php b/src/Database/Table/SqlBuilder.php index 8376d0292..a09bf0652 100644 --- a/src/Database/Table/SqlBuilder.php +++ b/src/Database/Table/SqlBuilder.php @@ -93,7 +93,7 @@ class SqlBuilder private $expandingJoins = []; - public function __construct($tableName, Context $context) + public function __construct(string $tableName, Context $context) { $this->tableName = $tableName; $this->driver = $context->getConnection()->getSupplementalDriver(); @@ -105,28 +105,19 @@ public function __construct($tableName, Context $context) } - /** - * @return string - */ - public function getTableName() + public function getTableName(): string { return $this->tableName; } - /** - * @param string - */ - public function buildInsertQuery() + public function buildInsertQuery(): string { return "INSERT INTO {$this->delimitedTable}"; } - /** - * @param string - */ - public function buildUpdateQuery() + public function buildUpdateQuery(): string { $query = "UPDATE {$this->delimitedTable} SET ?set" . $this->tryDelimite($this->buildConditions()); if ($this->limit !== NULL || $this->offset) { @@ -137,10 +128,7 @@ public function buildUpdateQuery() } - /** - * @param string - */ - public function buildDeleteQuery() + public function buildDeleteQuery(): string { $query = "DELETE FROM {$this->delimitedTable}" . $this->tryDelimite($this->buildConditions()); if ($this->limit !== NULL || $this->offset) { @@ -153,9 +141,8 @@ public function buildDeleteQuery() /** * Returns select query hash for caching. - * @return string */ - public function getSelectQueryHash(array $columns = NULL) + public function getSelectQueryHash(array $columns = NULL): string { $parts = [ 'delimitedTable' => $this->delimitedTable, @@ -187,9 +174,8 @@ public function getSelectQueryHash(array $columns = NULL) /** * Returns SQL query. * @param string[] list of columns - * @return string */ - public function buildSelectQuery(array $columns = NULL) + public function buildSelectQuery(array $columns = NULL): string { if (!$this->order && ($this->limit !== NULL || $this->offset)) { $this->order = array_map( @@ -237,10 +223,7 @@ function ($col) { return "$this->tableName.$col"; }, } - /** - * @return array - */ - public function getParameters() + public function getParameters(): array { if (!isset($this->parameters['joinConditionSorted'])) { $this->buildSelectQuery(); @@ -256,7 +239,7 @@ public function getParameters() } - public function importConditions(SqlBuilder $builder) + public function importConditions(SqlBuilder $builder): void { $this->where = $builder->where; $this->joinCondition = $builder->joinCondition; @@ -271,7 +254,7 @@ public function importConditions(SqlBuilder $builder) /********************* SQL selectors ****************d*g**/ - public function addSelect($columns, ...$params) + public function addSelect($columns, ...$params): void { if (is_array($columns)) { throw new Nette\InvalidArgumentException('Select column must be a string.'); @@ -281,28 +264,19 @@ public function addSelect($columns, ...$params) } - /** - * @return array - */ - public function getSelect() + public function getSelect(): array { return $this->select; } - /** - * @return bool - */ - public function addWhere($condition, ...$params) + public function addWhere($condition, ...$params): bool { return $this->addCondition($condition, $params, $this->where, $this->parameters['where']); } - /** - * @return array - */ - public function addJoinCondition($tableChain, $condition, ...$params) + public function addJoinCondition($tableChain, $condition, ...$params): bool { $this->parameters['joinConditionSorted'] = NULL; if (!isset($this->joinCondition[$tableChain])) { @@ -312,10 +286,7 @@ public function addJoinCondition($tableChain, $condition, ...$params) } - /** - * @return bool - */ - protected function addCondition($condition, array $params, array &$conditions, array &$conditionsParameters) + protected function addCondition($condition, array $params, array &$conditions, array &$conditionsParameters): bool { if (is_array($condition) && !empty($params[0]) && is_array($params[0])) { return $this->addConditionComposition($condition, $params[0], $conditions, $conditionsParameters); @@ -431,10 +402,7 @@ protected function addCondition($condition, array $params, array &$conditions, a } - /** - * @return array - */ - public function getConditions() + public function getConditions(): array { return array_values($this->conditions); } @@ -442,11 +410,8 @@ public function getConditions() /** * Adds alias. - * @param string - * @param string - * @return void */ - public function addAlias($chain, $alias) + public function addAlias(string $chain, string $alias): void { if (isset($chain[0]) && $chain[0] !== '.' && $chain[0] !== ':') { $chain = '.' . $chain; // unified chain format @@ -456,12 +421,7 @@ public function addAlias($chain, $alias) } - /** - * @param string - * @param string - * @return void - */ - protected function checkUniqueTableName($tableName, $chain) + protected function checkUniqueTableName(string $tableName, string $chain): void { if (isset($this->aliases[$tableName]) && ('.' . $tableName === $chain)) { $chain = $this->aliases[$tableName]; @@ -476,86 +436,66 @@ protected function checkUniqueTableName($tableName, $chain) } - public function addOrder($columns, ...$params) + public function addOrder($columns, ...$params): void { $this->order[] = $columns; $this->parameters['order'] = array_merge($this->parameters['order'], $params); } - public function setOrder(array $columns, array $parameters) + public function setOrder(array $columns, array $parameters): void { $this->order = $columns; $this->parameters['order'] = $parameters; } - /** - * @return array - */ - public function getOrder() + public function getOrder(): array { return $this->order; } - /** - * @param int|NULL - * @param int|NULL - * @return void - */ - public function setLimit($limit, $offset) + public function setLimit(?int $limit, ?int $offset): void { $this->limit = $limit; $this->offset = $offset; } - /** - * @return int|NULL - */ - public function getLimit() + public function getLimit(): ?int { return $this->limit; } - /** - * @return int|NULL - */ - public function getOffset() + public function getOffset(): ?int { return $this->offset; } - public function setGroup($columns, ...$params) + public function setGroup($columns, ...$params): void { $this->group = $columns; $this->parameters['group'] = $params; } - /** - * @return string - */ - public function getGroup() + public function getGroup(): string { return $this->group; } - public function setHaving($having, ...$params) + public function setHaving($having, ...$params): void { $this->having = $having; $this->parameters['having'] = $params; } - /** - * @return string - */ - public function getHaving() + public function getHaving(): string { return $this->having; } @@ -564,19 +504,13 @@ public function getHaving() /********************* SQL building ****************d*g**/ - /** - * @return string - */ - protected function buildSelect(array $columns) + protected function buildSelect(array $columns): string { return 'SELECT ' . implode(', ', $columns); } - /** - * @return array - */ - protected function parseJoinConditions(&$joins, $joinConditions) + protected function parseJoinConditions(&$joins, $joinConditions): array { $tableJoins = $leftJoinDependency = $finalJoinConditions = []; foreach ($joinConditions as $tableChain => &$joinCondition) { @@ -609,7 +543,7 @@ protected function parseJoinConditions(&$joins, $joinConditions) } - protected function getSortedJoins($table, &$leftJoinDependency, &$tableJoins, &$finalJoins) + protected function getSortedJoins(string $table, &$leftJoinDependency, &$tableJoins, &$finalJoins): void { if (isset($this->expandingJoins[$table])) { $path = implode("' => '", array_map(function($value) { return $this->reservedTableNames[$value]; }, array_merge(array_keys($this->expandingJoins), [$table]))); @@ -644,7 +578,7 @@ protected function getSortedJoins($table, &$leftJoinDependency, &$tableJoins, &$ } - protected function parseJoins(&$joins, &$query) + protected function parseJoins(&$joins, &$query): void { $query = preg_replace_callback($this->getColumnChainsRegxp(), function ($match) use (&$joins) { return $this->parseJoinsCb($joins, $match); @@ -652,10 +586,7 @@ protected function parseJoins(&$joins, &$query) } - /** - * @return string - */ - private function getColumnChainsRegxp() + private function getColumnChainsRegxp(): string { return '~ (?(DEFINE) @@ -668,10 +599,7 @@ private function getColumnChainsRegxp() } - /** - * @return string - */ - public function parseJoinsCb(&$joins, $match) + public function parseJoinsCb(&$joins, $match): string { $chain = $match['chain']; if (!empty($chain[0]) && ($chain[0] !== '.' && $chain[0] !== ':')) { @@ -777,10 +705,7 @@ public function parseJoinsCb(&$joins, $match) } - /** - * @return string - */ - protected function buildQueryJoins(array $joins, array $leftJoinConditions = []) + protected function buildQueryJoins(array $joins, array $leftJoinConditions = []): string { $return = ''; foreach ($joins as [$joinTable, $joinAlias, $table, $tableColumn, $joinColumn]) { @@ -793,10 +718,7 @@ protected function buildQueryJoins(array $joins, array $leftJoinConditions = []) } - /** - * @return array - */ - protected function buildJoinConditions() + protected function buildJoinConditions(): array { $conditions = []; foreach ($this->joinCondition as $tableChain => $joinConditions) { @@ -806,19 +728,13 @@ protected function buildJoinConditions() } - /** - * @return string - */ - protected function buildConditions() + protected function buildConditions(): string { return $this->where ? ' WHERE (' . implode(') AND (', $this->where) . ')' : ''; } - /** - * @return string - */ - protected function buildQueryEnd() + protected function buildQueryEnd(): string { $return = ''; if ($this->group) { @@ -834,10 +750,7 @@ protected function buildQueryEnd() } - /** - * @return string - */ - protected function tryDelimite($s) + protected function tryDelimite(string $s): string { return preg_replace_callback('#(?<=[^\w`"\[?]|^)[a-z_][a-z0-9_]*(?=[^\w`"(\]]|\z)#i', function ($m) { return strtoupper($m[0]) === $m[0] ? $m[0] : $this->driver->delimite($m[0]); @@ -845,10 +758,7 @@ protected function tryDelimite($s) } - /** - * @return bool - */ - protected function addConditionComposition(array $columns, array $parameters, array &$conditions, array &$conditionsParameters) + protected function addConditionComposition(array $columns, array $parameters, array &$conditions, array &$conditionsParameters): bool { if ($this->driver->isSupported(ISupplementalDriver::SUPPORT_MULTI_COLUMN_AS_OR_COND)) { $conditionFragment = '(' . implode(' = ? AND ', $columns) . ' = ?) OR '; @@ -860,10 +770,7 @@ protected function addConditionComposition(array $columns, array $parameters, ar } - /** - * @return string - */ - private function getConditionHash($condition, array $parameters) + private function getConditionHash($condition, array $parameters): string { foreach ($parameters as $key => &$parameter) { if ($parameter instanceof Selection) { @@ -880,10 +787,7 @@ private function getConditionHash($condition, array $parameters) } - /** - * @return array - */ - private function getCachedTableList() + private function getCachedTableList(): array { if (!$this->cacheTableList) { $this->cacheTableList = array_flip(array_map(function ($pair) { diff --git a/tests/Database/Table/Selection.page().phpt b/tests/Database/Table/Selection.page().phpt index dcdf78126..998f9f793 100644 --- a/tests/Database/Table/Selection.page().phpt +++ b/tests/Database/Table/Selection.page().phpt @@ -59,11 +59,3 @@ test(function () use ($context) { //less items than $itemsPerPage $tags = $context->table('tag')->page(1, 100); Assert::equal(4, count($tags)); //all four items from db }); - -// SQL Server throw PDOException 'The number of rows provided for a FETCH clause must be greater then zero.' -if ($driverName !== 'sqlsrv') { - Assert::error(function () use ($context) { //invalid params - $tags = $context->table('tag')->page('foo', 'bar'); - Assert::equal(0, count($tags)); //no items - }, PHP_VERSION_ID >= 70100 ? [[E_WARNING, 'A non-numeric value encountered']] : []); -} diff --git a/tests/Database/Table/SqlBuilder.addAlias().phpt b/tests/Database/Table/SqlBuilder.addAlias().phpt index 7643e4d55..10af83f67 100644 --- a/tests/Database/Table/SqlBuilder.addAlias().phpt +++ b/tests/Database/Table/SqlBuilder.addAlias().phpt @@ -17,11 +17,11 @@ Nette\Database\Helpers::loadFromFile($connection, __DIR__ . "/../files/{$driverN class SqlBuilderMock extends SqlBuilder { - public function parseJoins(&$joins, &$query, $inner = FALSE) + public function parseJoins(&$joins, &$query, $inner = FALSE): void { parent::parseJoins($joins, $query); } - public function buildQueryJoins(array $joins, array $leftJoinConditions = []) + public function buildQueryJoins(array $joins, array $leftJoinConditions = []): string { return parent::buildQueryJoins($joins, $leftJoinConditions); } diff --git a/tests/Database/Table/SqlBuilder.parseJoinConditions().phpt b/tests/Database/Table/SqlBuilder.parseJoinConditions().phpt index 84b659be7..7baa0a61c 100644 --- a/tests/Database/Table/SqlBuilder.parseJoinConditions().phpt +++ b/tests/Database/Table/SqlBuilder.parseJoinConditions().phpt @@ -17,19 +17,19 @@ Nette\Database\Helpers::loadFromFile($connection, __DIR__ . "/../files/{$driverN class SqlBuilderMock extends SqlBuilder { - public function parseJoinConditions(&$joins, $joinConditions) + public function parseJoinConditions(&$joins, $joinConditions): array { return parent::parseJoinConditions($joins, $joinConditions); } - public function buildJoinConditions() + public function buildJoinConditions(): array { return parent::buildJoinConditions(); } - public function parseJoins(&$joins, &$query) + public function parseJoins(&$joins, &$query): void { parent::parseJoins($joins, $query); } - public function buildQueryJoins(array $joins, array $leftJoinConditions = []) + public function buildQueryJoins(array $joins, array $leftJoinConditions = []): string { return parent::buildQueryJoins($joins, $leftJoinConditions); } diff --git a/tests/Database/Table/SqlBuilder.parseJoins().phpt b/tests/Database/Table/SqlBuilder.parseJoins().phpt index 7b7a4f647..4184e1ecb 100644 --- a/tests/Database/Table/SqlBuilder.parseJoins().phpt +++ b/tests/Database/Table/SqlBuilder.parseJoins().phpt @@ -19,11 +19,11 @@ Nette\Database\Helpers::loadFromFile($connection, __DIR__ . "/../files/{$driverN class SqlBuilderMock extends SqlBuilder { - public function parseJoins(&$joins, &$query, $inner = FALSE) + public function parseJoins(&$joins, &$query, $inner = FALSE): void { parent::parseJoins($joins, $query); } - public function buildQueryJoins(array $joins, array $leftJoinConditions = []) + public function buildQueryJoins(array $joins, array $leftJoinConditions = []): string { return parent::buildQueryJoins($joins, $leftJoinConditions); } diff --git a/tests/Database/Table/bugs/Selection.emptyResultSet.phpt b/tests/Database/Table/bugs/Selection.emptyResultSet.phpt index d2ae97128..ca30b6d8f 100644 --- a/tests/Database/Table/bugs/Selection.emptyResultSet.phpt +++ b/tests/Database/Table/bugs/Selection.emptyResultSet.phpt @@ -20,7 +20,7 @@ test(function () use ($context) { $context->table('book')->get(2)->author->update(['name' => 'New name']); $context->table('book')->get(2)->update(['title' => 'New book title']); - $selection->limit(NULL); //should invalidate cache of data and references + $selection->limit(1); //should invalidate cache of data and references $book = $selection->get(2); Assert::same('New book title', $book->title); //data cache invalidated
" . htmlSpecialChars($result->getQueryString(), ENT_IGNORE, 'UTF-8') . "