Skip to content

Commit

Permalink
phpstan enable strict rules
Browse files Browse the repository at this point in the history
  • Loading branch information
hrach committed Jul 22, 2020
1 parent 982428e commit 5ae8bae
Show file tree
Hide file tree
Showing 23 changed files with 100 additions and 89 deletions.
3 changes: 2 additions & 1 deletion composer.json
Expand Up @@ -22,9 +22,10 @@
"nette/utils": "~3.0",
"nette/finder": "~2.5",
"nette/neon": "~3.0",
"phpstan/extension-installer": "1.0.4",
"phpstan/phpstan": "0.12.33",
"phpstan/phpstan-deprecation-rules": "0.12.5",
"phpstan/extension-installer": "~1.0",
"phpstan/phpstan-strict-rules": "0.12.4",
"symfony/config": "~4.4 || ~5.0",
"symfony/dependency-injection": "~4.4 || ~5.0",
"symfony/http-kernel": "~4.4 || ~5.0",
Expand Down
8 changes: 4 additions & 4 deletions src/Bridges/NetteCaching/CachedPlatform.php
Expand Up @@ -34,7 +34,7 @@ public function getName(): string
/** @inheritDoc */
public function getTables(?string $schema = null): array
{
return $this->cache->load(self::CACHE_VERSION . '.tables.' . $schema, function () use ($schema) {
return $this->cache->load(self::CACHE_VERSION . '.tables.' . $schema, function () use ($schema): array {
return $this->platform->getTables($schema);
});
}
Expand All @@ -43,7 +43,7 @@ public function getTables(?string $schema = null): array
/** @inheritDoc */
public function getColumns(string $table): array
{
return $this->cache->load(self::CACHE_VERSION . '.columns.' . $table, function () use ($table) {
return $this->cache->load(self::CACHE_VERSION . '.columns.' . $table, function () use ($table): array {
return $this->platform->getColumns($table);
});
}
Expand All @@ -52,15 +52,15 @@ public function getColumns(string $table): array
/** @inheritDoc */
public function getForeignKeys(string $table): array
{
return $this->cache->load(self::CACHE_VERSION . '.foreign_keys.' . $table, function () use ($table) {
return $this->cache->load(self::CACHE_VERSION . '.foreign_keys.' . $table, function () use ($table): array {
return $this->platform->getForeignKeys($table);
});
}


public function getPrimarySequenceName(string $table): ?string
{
return $this->cache->load(self::CACHE_VERSION . '.sequence.' . $table, function () use ($table) {
return $this->cache->load(self::CACHE_VERSION . '.sequence.' . $table, function () use ($table): array {
return [$this->platform->getPrimarySequenceName($table)];
})[0];
}
Expand Down
2 changes: 1 addition & 1 deletion src/Bridges/NetteDI/DbalExtension.php
Expand Up @@ -35,7 +35,7 @@ protected function setupConnection(array $config): void
->setAutowired(isset($config['autowired']) ? $config['autowired'] : true);

if (isset($config['debugger'])) {
$debugger = $config['debugger'];
$debugger = (bool) $config['debugger'];
} else {
$debugger = class_exists('Tracy\Debugger', false) && Debugger::$productionMode === Debugger::DEVELOPMENT;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Bridges/NetteTracy/BluescreenQueryPanel.php
Expand Up @@ -14,7 +14,7 @@ class BluescreenQueryPanel
*/
public static function renderBluescreenPanel(?\Throwable $exception): ?array
{
if (!$exception instanceof QueryException || !($query = $exception->getSqlQuery())) {
if (!$exception instanceof QueryException || ($query = $exception->getSqlQuery()) === null) {
return null;
}

Expand Down
8 changes: 4 additions & 4 deletions src/Bridges/NetteTracy/ConnectionPanel.php
Expand Up @@ -75,7 +75,7 @@ public function onQuery(string $sqlQuery, float $timeTaken, ?Result $result): vo
$this->connection,
$sqlQuery,
$timeTaken,
$result ? $result->count() : null,
$result !== null ? $result->count() : null,
];
}

Expand All @@ -85,7 +85,7 @@ public function onQueryException(string $sqlQuery, float $timeTaken, ?DriverExce
}


public function getTab(): ?string
public function getTab(): string
{
$count = $this->count;
$totalTime = $this->totalTime;
Expand All @@ -96,11 +96,11 @@ public function getTab(): ?string
}


public function getPanel(): ?string
public function getPanel(): string
{
$count = $this->count;
$queries = $this->queries;
$queries = array_map(function ($row) {
$queries = array_map(function ($row): array {
try {
$row[4] = null;
if ($this->doExplain) {
Expand Down
Expand Up @@ -144,7 +144,7 @@ public function onQuery(string $sqlQuery, float $timeTaken, ?Result $result): vo
$this->queries[] = [
$sqlQuery,
$timeTaken,
$result ? $result->count() : null,
$result !== null ? $result->count() : null,
];
}

Expand Down
Expand Up @@ -28,10 +28,10 @@ public function getConfigTreeBuilder()
// @formatter:off
$treeBuilder->getRootNode()
->beforeNormalization()
->ifTrue(static function ($v) {
->ifTrue(static function ($v): bool {
return is_array($v) && !array_key_exists('connections', $v);
})
->then(static function ($v) {
->then(static function ($v): array {
return [
'connections' => ['default' => $v],
'default_connection' => 'default',
Expand Down
2 changes: 1 addition & 1 deletion src/Connection.php
Expand Up @@ -342,7 +342,7 @@ private function nativeQuery(string $sql): Result

private function createDriver(): IDriver
{
if (empty($this->config['driver'])) {
if (!isset($this->config['driver'])) {
throw new InvalidArgumentException('Undefined driver. Choose from: mysqli, pgsql, sqlsrv.');
} elseif ($this->config['driver'] instanceof IDriver) {
return $this->config['driver'];
Expand Down
8 changes: 4 additions & 4 deletions src/Drivers/Exception/QueryException.php
Expand Up @@ -8,7 +8,7 @@

class QueryException extends DriverException
{
/** @var string */
/** @var string|null */
private $sqlQuery;


Expand All @@ -17,15 +17,15 @@ public function __construct(
int $errorCode = 0,
string $errorSqlState = '',
Exception $previousException = null,
string $sqlQuery = null
?string $sqlQuery = null
)
{
parent::__construct($message, $errorCode, $errorSqlState, $previousException);
$this->sqlQuery = (string) $sqlQuery;
$this->sqlQuery = $sqlQuery;
}


public function getSqlQuery(): string
public function getSqlQuery(): ?string
{
return $this->sqlQuery;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Drivers/IDriver.php
Expand Up @@ -67,7 +67,7 @@ public function query(string $query): Result;
* @return mixed
* @internal
*/
public function getLastInsertedId(string $sequenceName = null);
public function getLastInsertedId(?string $sequenceName = null);


/**
Expand Down
20 changes: 11 additions & 9 deletions src/Drivers/Mysqli/MysqliDriver.php
Expand Up @@ -58,9 +58,10 @@ public function connect(array $params, ILogger $logger): void
$this->logger = $logger;

$host = $params['host'] ?? ini_get('mysqli.default_host');
$port = $params['port'] ?? (int) (ini_get('mysqli.default_port') ?: 3306);
$port = (int) ($params['port'] ?? ini_get('mysqli.default_port'));
$port = $port === 0 ? 3306 : $port;
$dbname = $params['database'] ?? '';
$socket = ($params['unix_socket'] ?? ini_get('mysqli.default_socket')) ?: '';
$socket = $params['unix_socket'] ?? ini_get('mysqli.default_socket');
$flags = $params['flags'] ?? 0;

$this->connection = new mysqli();
Expand All @@ -72,7 +73,8 @@ public function connect(array $params, ILogger $logger): void
if (!@$this->connection->real_connect($host, $params['username'], (string) $params['password'], $dbname, $port, $socket, $flags)) {
throw $this->createException(
$this->connection->connect_error,
(int) $this->connection->connect_errno,
$this->connection->connect_errno,
// @phpstan-ignore-next-line - Property access is not allowed yet
@$this->connection->sqlstate ?: 'HY000'
);
}
Expand All @@ -83,7 +85,7 @@ public function connect(array $params, ILogger $logger): void

public function disconnect(): void
{
if ($this->connection) {
if ($this->connection !== null) {
$this->connection->close();
$this->connection = null;
}
Expand Down Expand Up @@ -130,7 +132,7 @@ public function query(string $query): Result
}


public function getLastInsertedId(string $sequenceName = null)
public function getLastInsertedId(?string $sequenceName = null)
{
assert($this->connection !== null);
return $this->connection->insert_id;
Expand Down Expand Up @@ -261,7 +263,7 @@ protected function processInitialSettings(array $params): void

if (isset($params['charset'])) {
$charset = $params['charset'];
} elseif (($version = $this->getServerVersion()) && version_compare($version, '5.5.3', '>=')) {
} elseif (version_compare($this->getServerVersion(), '5.5.3', '>=')) {
$charset = 'utf8mb4';
} else {
$charset = 'utf8';
Expand Down Expand Up @@ -318,7 +320,7 @@ public function convertStringToSql(string $value): string
public function convertJsonToSql($value): string
{
$encoded = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION);
if (json_last_error()) {
if (json_last_error() !== JSON_ERROR_NONE) {
throw new InvalidArgumentException('JSON Encode Error: ' . json_last_error_msg());
}
assert(is_string($encoded));
Expand All @@ -345,7 +347,7 @@ public function convertIdentifierToSql(string $value): string
}


public function convertDatetimeToSql(DateTimeInterface $value): string
public function convertDateTimeToSql(DateTimeInterface $value): string
{
assert($value instanceof DateTime || $value instanceof DateTimeImmutable);
if ($value->getTimezone()->getName() !== $this->connectionTz->getName()) {
Expand All @@ -360,7 +362,7 @@ public function convertDatetimeToSql(DateTimeInterface $value): string
}


public function convertDatetimeSimpleToSql(DateTimeInterface $value): string
public function convertDateTimeSimpleToSql(DateTimeInterface $value): string
{
return "'" . $value->format('Y-m-d H:i:s.u') . "'";
}
Expand Down
13 changes: 7 additions & 6 deletions src/Drivers/Pgsql/PgsqlDriver.php
Expand Up @@ -80,7 +80,7 @@ public function connect(array $params, ILogger $logger): void
}
}

set_error_handler(function ($code, $message) {
set_error_handler(function (int $code, string $message): bool {
restore_error_handler();
throw $this->createException($message, $code, null);
}, E_ALL);
Expand All @@ -107,7 +107,7 @@ public function connect(array $params, ILogger $logger): void

public function disconnect(): void
{
if ($this->connection) {
if ($this->connection !== null) {
pg_close($this->connection);
$this->connection = null;
}
Expand Down Expand Up @@ -143,17 +143,18 @@ public function query(string $query): Result

$state = pg_result_error_field($resource, PGSQL_DIAG_SQLSTATE);
if (is_string($state)) {
throw $this->createException(pg_result_error($resource) ?: 'Unknown error', 0, $state, $query);
$error = pg_result_error($resource);
throw $this->createException($error !== false ? $error : 'Unknown error', 0, $state, $query);
}

$this->affectedRows = pg_affected_rows($resource);
return new Result(new PgsqlResultAdapter($resource), $this);
}


public function getLastInsertedId(string $sequenceName = null)
public function getLastInsertedId(?string $sequenceName = null)
{
if (empty($sequenceName)) {
if ($sequenceName === null) {
throw new InvalidArgumentException('PgsqlDriver requires to pass sequence name for getLastInsertedId() method.');
}
assert($this->connection !== null);
Expand Down Expand Up @@ -284,7 +285,7 @@ public function convertStringToSql(string $value): string
public function convertJsonToSql($value): string
{
$encoded = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION);
if (json_last_error()) {
if (json_last_error() !== JSON_ERROR_NONE) {
throw new InvalidArgumentException('JSON Encode Error: ' . json_last_error_msg());
}
assert(is_string($encoded));
Expand Down
3 changes: 2 additions & 1 deletion src/Drivers/Pgsql/PgsqlResultAdapter.php
Expand Up @@ -73,7 +73,8 @@ public function seek(int $index): void

public function fetch(): ?array
{
return pg_fetch_array($this->result, null, PGSQL_ASSOC) ?: null;
$row = pg_fetch_array($this->result, null, PGSQL_ASSOC);
return $row !== false ? $row : null;
}


Expand Down
28 changes: 14 additions & 14 deletions src/Drivers/Sqlsrv/SqlsrvDriver.php
Expand Up @@ -82,7 +82,7 @@ public function connect(array $params, ILogger $logger): void
if ($key === 'username') {
$connectionOptions['UID'] = $value;
} elseif ($key === 'password') {
$connectionOptions['PWD'] = $value ?: '';
$connectionOptions['PWD'] = $value ?? '';
} elseif ($key === 'database') {
$connectionOptions['Database'] = $value;
} elseif ($key === 'connectionTz') {
Expand All @@ -97,16 +97,17 @@ public function connect(array $params, ILogger $logger): void
}
$connectionOptions['ReturnDatesAsStrings'] = true;

$this->connection = sqlsrv_connect($connectionString, $connectionOptions) ?: null;
if (!$this->connection) {
$connectionResource = sqlsrv_connect($connectionString, $connectionOptions);
if ($connectionResource === false) {
$this->throwErrors();
}
$this->connection = $connectionResource;
}


public function disconnect(): void
{
if ($this->connection) {
if ($this->connection !== null) {
sqlsrv_close($this->connection);
$this->connection = null;
}
Expand Down Expand Up @@ -139,21 +140,20 @@ public function query(string $query): Result
}

$affectedRowsStatement = sqlsrv_query($this->connection, 'SELECT @@ROWCOUNT');
if (!$affectedRowsStatement) {
if ($affectedRowsStatement === false) {
$this->throwErrors();
}
assert($affectedRowsStatement !== false);
if ($affectedRowsResult = sqlsrv_fetch_array($affectedRowsStatement, SQLSRV_FETCH_NUMERIC)) {
$this->affectedRows = $affectedRowsResult[0];
} else {
$affectedRowsResult = sqlsrv_fetch_array($affectedRowsStatement, SQLSRV_FETCH_NUMERIC);
if (!is_array($affectedRowsResult)) {
$this->throwErrors();
}
$this->affectedRows = $affectedRowsResult[0];

return new Result(new SqlsrvResultAdapter($statement), $this);
}


public function getLastInsertedId(string $sequenceName = null)
public function getLastInsertedId(?string $sequenceName = null)
{
return $this->loggedQuery('SELECT SCOPE_IDENTITY()')->fetchField();
}
Expand Down Expand Up @@ -294,7 +294,7 @@ public function convertStringToSql(string $value): string
public function convertJsonToSql($value): string
{
$encoded = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION);
if (json_last_error()) {
if (json_last_error() !== JSON_ERROR_NONE) {
throw new InvalidArgumentException('JSON Encode Error: ' . json_last_error_msg());
}
assert(is_string($encoded));
Expand Down Expand Up @@ -353,7 +353,7 @@ public function convertBlobToSql(string $value): string

public function modifyLimitQuery(string $query, ?int $limit, ?int $offset): string
{
$query .= ' OFFSET ' . ($offset ?: 0) . ' ROWS';
$query .= ' OFFSET ' . ($offset !== null ? $offset : 0) . ' ROWS';
if ($limit !== null) {
$query .= ' FETCH NEXT ' . $limit . ' ROWS ONLY';
}
Expand All @@ -366,8 +366,8 @@ public function modifyLimitQuery(string $query, ?int $limit, ?int $offset): stri
*/
private function throwErrors(?string $query = null): void
{
$errors = sqlsrv_errors(SQLSRV_ERR_ERRORS) ?: [];
$errors = array_unique($errors, SORT_REGULAR);
$errors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
$errors = $errors === null ? [] : array_unique($errors, SORT_REGULAR);
$error = array_shift($errors);
if ($error === null) {
return;
Expand Down

0 comments on commit 5ae8bae

Please sign in to comment.