Compare commits

..

2 Commits

Author SHA1 Message Date
Clemens Schwaighofer
da0d939068 First phpstan strict check 2023-02-28 06:54:20 +09:00
Clemens Schwaighofer
537bc0a477 add phpstan strict 2023-02-28 06:39:36 +09:00
103 changed files with 4312 additions and 663 deletions

View File

@@ -27,7 +27,6 @@ use Phan\Config;
return [
// "target_php_version" => "8.2",
"minimum_target_php_version" => "8.1",
// turn color on (-C)
"color_issue_messages_if_supported" => true,
// If true, missing properties will be created when

View File

@@ -15,8 +15,8 @@ php_bin="";
if [ ! -z "${1}" ]; then
case "${1}" in
# "7.3") php_bin="/usr/bin/php7.3 "; ;;
# "7.4") php_bin="/usr/bin/php7.4 "; ;;
# "8.0") php_bin="/usr/bin/php8.0 "; ;;
"7.4") php_bin="/usr/bin/php7.4 "; ;;
"8.0") php_bin="/usr/bin/php8.0 "; ;;
"8.1") php_bin="/usr/bin/php8.1 "; ;;
"8.2") php_bin="/usr/bin/php8.2 "; ;;
*) echo "Not support PHP: ${1}"; exit; ;;
@@ -25,8 +25,8 @@ fi;
if [ ! -z "${2}" ] && [ -z "${php_bin}" ]; then
case "${2}" in
# "7.3") php_bin="/usr/bin/php7.3 "; ;;
# "7.4") php_bin="/usr/bin/php7.4 "; ;;
# "8.0") php_bin="/usr/bin/php8.0 "; ;;
"7.4") php_bin="/usr/bin/php7.4 "; ;;
"8.0") php_bin="/usr/bin/php8.0 "; ;;
"8.1") php_bin="/usr/bin/php8.1 "; ;;
"8.2") php_bin="/usr/bin/php8.2 "; ;;
*) echo "Not support PHP: ${1}"; exit; ;;

View File

@@ -1729,7 +1729,7 @@ final class CoreLibsACLLoginTest extends TestCase
],
20
],
'invalid search' => [
'invalud search' => [
12,
'foo',
[],

View File

@@ -107,13 +107,6 @@ final class CoreLibsCombinedArrayHandlerTest extends TestCase
*/
public function arraySearchRecursiveAllProvider(): array
{
/*
0: $needle,
1: array $input,
2: ?string $key_search_for,
3: bool $flag,
4: array $expected
*/
return [
'find value' => [
0 => 'bar',
@@ -179,13 +172,6 @@ final class CoreLibsCombinedArrayHandlerTest extends TestCase
*/
public function arraySearchSimpleProvider(): array
{
/*
0: array $input,
1: $key,
2: $value,
3: bool $flag,
4: bool $expected
*/
return [
'key/value exist' => [
0 => self::$array,
@@ -679,7 +665,7 @@ final class CoreLibsCombinedArrayHandlerTest extends TestCase
*
* @param array $input
* @param string|int $key
* @param string|int|bool $value
* @param string|int $value
* @param bool $expected
* @return void
*/

View File

@@ -1253,14 +1253,10 @@ final class CoreLibsDBIOTest extends TestCase
'string value literal' => ['string literal', 'tl', '\'string literal\'',],
'empty string value literal' => ['', 'tl', '\'\'',],
'null string value literal' => [null, 'tl', 'NULL',],
// escape string, but set all empty strings to null ('' is null)
// ?d (I have no idea what that does, is like string)
'string value d' => ['string d', 'd', '\'string d\'',],
'empty string value d' => ['', 'd', 'NULL',],
'null string value d' => [null, 'd', 'NULL',],
// escape literal string, but set all empty strings to null ('' is null)
'string value literal d' => ['string d', 'dl', '\'string d\'',],
'empty string value literal d' => ['', 'dl', 'NULL',],
'null string value literal d' => [null, 'dl', 'NULL',],
// by bytea
'string value d' => ['string d', 'by', '\x737472696e672064',],
'empty string value d' => ['', 'by', 'NULL',],
@@ -1285,7 +1281,7 @@ final class CoreLibsDBIOTest extends TestCase
* @dataProvider sqlEscapeProvider
* @testdox Input value $input as $flag to $expected [$_dataName]
*
* @param int|float|string|bool|null $input
* @param int|float|string|null $input
* @param string $flag
* @param int|float|string $expected
* @return void

View File

@@ -1,19 +1,13 @@
{
"name": "egrajp/development-corelibs-dev",
"version": "dev-master",
"description": "CoreLibs: Development package",
"type": "library",
"require-dev": {
"phpstan/phpstan": "^1.10",
"phan/phan": "^5.4",
"phpstan/extension-installer": "^1.2"
"phpstan/extension-installer": "^1.2",
"phpstan/phpstan-strict-rules": "^1.5"
},
"config": {
"allow-plugins": {
"phpstan/extension-installer": true
}
},
"require": {
"php": ">=8.1"
}
}

63
composer.lock generated
View File

@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "e0be39c8d67ae1599bb76d055debab50",
"content-hash": "7bfba596d1c7c3885f4d4aeea97c4926",
"packages": [],
"packages-dev": [
{
@@ -656,16 +656,16 @@
},
{
"name": "phpstan/phpstan",
"version": "1.10.3",
"version": "1.10.2",
"source": {
"type": "git",
"url": "https://github.com/phpstan/phpstan.git",
"reference": "5419375b5891add97dc74be71e6c1c34baaddf64"
"reference": "a2ffec7db373d8da4973d1d62add872db5cd22dd"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/5419375b5891add97dc74be71e6c1c34baaddf64",
"reference": "5419375b5891add97dc74be71e6c1c34baaddf64",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/a2ffec7db373d8da4973d1d62add872db5cd22dd",
"reference": "a2ffec7db373d8da4973d1d62add872db5cd22dd",
"shasum": ""
},
"require": {
@@ -695,7 +695,7 @@
],
"support": {
"issues": "https://github.com/phpstan/phpstan/issues",
"source": "https://github.com/phpstan/phpstan/tree/1.10.3"
"source": "https://github.com/phpstan/phpstan/tree/1.10.2"
},
"funding": [
{
@@ -711,7 +711,56 @@
"type": "tidelift"
}
],
"time": "2023-02-25T14:47:13+00:00"
"time": "2023-02-23T14:36:46+00:00"
},
{
"name": "phpstan/phpstan-strict-rules",
"version": "1.5.0",
"source": {
"type": "git",
"url": "https://github.com/phpstan/phpstan-strict-rules.git",
"reference": "b7dd96a5503919a43b3cd06a2dced9d4252492f2"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpstan/phpstan-strict-rules/zipball/b7dd96a5503919a43b3cd06a2dced9d4252492f2",
"reference": "b7dd96a5503919a43b3cd06a2dced9d4252492f2",
"shasum": ""
},
"require": {
"php": "^7.2 || ^8.0",
"phpstan/phpstan": "^1.10"
},
"require-dev": {
"nikic/php-parser": "^4.13.0",
"php-parallel-lint/php-parallel-lint": "^1.2",
"phpstan/phpstan-deprecation-rules": "^1.1",
"phpstan/phpstan-phpunit": "^1.0",
"phpunit/phpunit": "^9.5"
},
"type": "phpstan-extension",
"extra": {
"phpstan": {
"includes": [
"rules.neon"
]
}
},
"autoload": {
"psr-4": {
"PHPStan\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"description": "Extra strict and opinionated rules for PHPStan",
"support": {
"issues": "https://github.com/phpstan/phpstan-strict-rules/issues",
"source": "https://github.com/phpstan/phpstan-strict-rules/tree/1.5.0"
},
"time": "2023-02-21T10:17:10+00:00"
},
{
"name": "psr/container",

View File

@@ -6,6 +6,20 @@ parameters:
level: 8 # max is now 9
checkMissingCallableSignature: true
treatPhpDocTypesAsCertain: false
strictRules:
allRules: false
disallowedLooseComparison: false
booleansInConditions: false
uselessCast: true
requireParentConstructorCall: false
disallowedConstructs: false
overwriteVariablesWithLoop: false
closureUsesThis: false
matchingInheritedMethodNames: false
numericOperandsInArithmeticOperators: false
strictCalls: false
switchConditionsMatchingType: false
noVariableVariables: false
paths:
- %currentWorkingDirectory%/www
bootstrapFiles:
@@ -30,10 +44,9 @@ parameters:
- www/admin/error_test.php
# admin synlink files
- www/admin/edit_*.php
# config symlinks
- www/admin/config.php
- www/frontend/config.php
- www/frontend/*/config.php
# frotend symlink
- www/frontend/*config.php
# ignore admin header stuff
# - www/includes/admin_header.php # ignore the admin include stuff
- www/includes/admin_footer.php # ignore the admin include stuff
@@ -47,6 +60,8 @@ parameters:
- www/log
- www/media
- www/tmp
# File uploader
- www/lib/FileUpload
# ignore composer
- www/vendor
# ignore errores with
@@ -54,9 +69,9 @@ parameters:
#- # this error is ignore because of the PHP 8.0 to 8.1 change for pg_*, only for 8.0 or lower
# message: "#^Parameter \\#1 \\$(result|connection) of function pg_\\w+ expects resource(\\|null)?, object\\|resource(\\|bool)? given\\.$#"
# path: %currentWorkingDirectory%/www/lib/CoreLibs/DB/SQL/PgSQL.php
# - # this is for 8.1 or newer
# message: "#^Parameter \\#1 \\$(result|connection) of function pg_\\w+ expects PgSql\\\\(Result|Connection(\\|string)?(\\|null)?), object\\|resource given\\.$#"
# path: %currentWorkingDirectory%/www/lib/CoreLibs/DB/SQL/PgSQL.php
- # this is for 8.1 or newer
message: "#^Parameter \\#1 \\$(result|connection) of function pg_\\w+ expects PgSql\\\\(Result|Connection(\\|string)?(\\|null)?), object\\|resource given\\.$#"
path: %currentWorkingDirectory%/www/lib/CoreLibs/DB/SQL/PgSQL.php
# this is ignored for now
# - '#Expression in empty\(\) is always falsy.#'
# -

View File

@@ -10,9 +10,9 @@ return array(
'320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php',
'8825ede83f2f289127722d4e842cf7e8' => $vendorDir . '/symfony/polyfill-intl-grapheme/bootstrap.php',
'e69f7f6ee287b969198c3c9d6777bd38' => $vendorDir . '/symfony/polyfill-intl-normalizer/bootstrap.php',
'9b38cf48e83f5d8f60375221cd213eee' => $vendorDir . '/phpstan/phpstan/bootstrap.php',
'6e3fae29631ef280660b3cdad06f25a8' => $vendorDir . '/symfony/deprecation-contracts/function.php',
'b6b991a57620e2fb6b2f66f03fe9ddc2' => $vendorDir . '/symfony/string/Resources/functions.php',
'9b38cf48e83f5d8f60375221cd213eee' => $vendorDir . '/phpstan/phpstan/bootstrap.php',
'2b9d0f43f9552984cfa82fee95491826' => $vendorDir . '/sabre/event/lib/coroutine.php',
'd81bab31d3feb45bfe2f283ea3c8fdf7' => $vendorDir . '/sabre/event/lib/Loop/functions.php',
'a1cce3d26cc15c00fcd0b3354bd72c88' => $vendorDir . '/sabre/event/lib/Promise/functions.php',

View File

@@ -22,6 +22,7 @@ return array(
'Psr\\Container\\' => array($vendorDir . '/psr/container/src'),
'Phan\\' => array($vendorDir . '/phan/phan/src/Phan'),
'PHPStan\\ExtensionInstaller\\' => array($vendorDir . '/phpstan/extension-installer/src'),
'PHPStan\\' => array($vendorDir . '/phpstan/phpstan-strict-rules/src'),
'Microsoft\\PhpParser\\' => array($vendorDir . '/microsoft/tolerant-php-parser/src'),
'Composer\\XdebugHandler\\' => array($vendorDir . '/composer/xdebug-handler/src'),
'Composer\\Semver\\' => array($vendorDir . '/composer/semver/src'),

View File

@@ -11,9 +11,9 @@ class ComposerStaticInitdd705c6e8ab22e0d642372dec7767718
'320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php',
'8825ede83f2f289127722d4e842cf7e8' => __DIR__ . '/..' . '/symfony/polyfill-intl-grapheme/bootstrap.php',
'e69f7f6ee287b969198c3c9d6777bd38' => __DIR__ . '/..' . '/symfony/polyfill-intl-normalizer/bootstrap.php',
'9b38cf48e83f5d8f60375221cd213eee' => __DIR__ . '/..' . '/phpstan/phpstan/bootstrap.php',
'6e3fae29631ef280660b3cdad06f25a8' => __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php',
'b6b991a57620e2fb6b2f66f03fe9ddc2' => __DIR__ . '/..' . '/symfony/string/Resources/functions.php',
'9b38cf48e83f5d8f60375221cd213eee' => __DIR__ . '/..' . '/phpstan/phpstan/bootstrap.php',
'2b9d0f43f9552984cfa82fee95491826' => __DIR__ . '/..' . '/sabre/event/lib/coroutine.php',
'd81bab31d3feb45bfe2f283ea3c8fdf7' => __DIR__ . '/..' . '/sabre/event/lib/Loop/functions.php',
'a1cce3d26cc15c00fcd0b3354bd72c88' => __DIR__ . '/..' . '/sabre/event/lib/Promise/functions.php',
@@ -52,6 +52,7 @@ class ComposerStaticInitdd705c6e8ab22e0d642372dec7767718
'Psr\\Container\\' => 14,
'Phan\\' => 5,
'PHPStan\\ExtensionInstaller\\' => 27,
'PHPStan\\' => 8,
),
'M' =>
array (
@@ -136,6 +137,10 @@ class ComposerStaticInitdd705c6e8ab22e0d642372dec7767718
array (
0 => __DIR__ . '/..' . '/phpstan/extension-installer/src',
),
'PHPStan\\' =>
array (
0 => __DIR__ . '/..' . '/phpstan/phpstan-strict-rules/src',
),
'Microsoft\\PhpParser\\' =>
array (
0 => __DIR__ . '/..' . '/microsoft/tolerant-php-parser/src',

View File

@@ -682,17 +682,17 @@
},
{
"name": "phpstan/phpstan",
"version": "1.10.3",
"version_normalized": "1.10.3.0",
"version": "1.10.2",
"version_normalized": "1.10.2.0",
"source": {
"type": "git",
"url": "https://github.com/phpstan/phpstan.git",
"reference": "5419375b5891add97dc74be71e6c1c34baaddf64"
"reference": "a2ffec7db373d8da4973d1d62add872db5cd22dd"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/5419375b5891add97dc74be71e6c1c34baaddf64",
"reference": "5419375b5891add97dc74be71e6c1c34baaddf64",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/a2ffec7db373d8da4973d1d62add872db5cd22dd",
"reference": "a2ffec7db373d8da4973d1d62add872db5cd22dd",
"shasum": ""
},
"require": {
@@ -701,7 +701,7 @@
"conflict": {
"phpstan/phpstan-shim": "*"
},
"time": "2023-02-25T14:47:13+00:00",
"time": "2023-02-23T14:36:46+00:00",
"bin": [
"phpstan",
"phpstan.phar"
@@ -724,7 +724,7 @@
],
"support": {
"issues": "https://github.com/phpstan/phpstan/issues",
"source": "https://github.com/phpstan/phpstan/tree/1.10.3"
"source": "https://github.com/phpstan/phpstan/tree/1.10.2"
},
"funding": [
{
@@ -742,6 +742,58 @@
],
"install-path": "../phpstan/phpstan"
},
{
"name": "phpstan/phpstan-strict-rules",
"version": "1.5.0",
"version_normalized": "1.5.0.0",
"source": {
"type": "git",
"url": "https://github.com/phpstan/phpstan-strict-rules.git",
"reference": "b7dd96a5503919a43b3cd06a2dced9d4252492f2"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpstan/phpstan-strict-rules/zipball/b7dd96a5503919a43b3cd06a2dced9d4252492f2",
"reference": "b7dd96a5503919a43b3cd06a2dced9d4252492f2",
"shasum": ""
},
"require": {
"php": "^7.2 || ^8.0",
"phpstan/phpstan": "^1.10"
},
"require-dev": {
"nikic/php-parser": "^4.13.0",
"php-parallel-lint/php-parallel-lint": "^1.2",
"phpstan/phpstan-deprecation-rules": "^1.1",
"phpstan/phpstan-phpunit": "^1.0",
"phpunit/phpunit": "^9.5"
},
"time": "2023-02-21T10:17:10+00:00",
"type": "phpstan-extension",
"extra": {
"phpstan": {
"includes": [
"rules.neon"
]
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"PHPStan\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"description": "Extra strict and opinionated rules for PHPStan",
"support": {
"issues": "https://github.com/phpstan/phpstan-strict-rules/issues",
"source": "https://github.com/phpstan/phpstan-strict-rules/tree/1.5.0"
},
"install-path": "../phpstan/phpstan-strict-rules"
},
{
"name": "psr/container",
"version": "2.0.2",
@@ -1835,6 +1887,7 @@
"phpdocumentor/type-resolver",
"phpstan/extension-installer",
"phpstan/phpstan",
"phpstan/phpstan-strict-rules",
"psr/container",
"psr/log",
"sabre/event",

View File

@@ -3,7 +3,7 @@
'name' => '__root__',
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'reference' => '44f37b7f74e1fcbfbbdf26036117d14404011abd',
'reference' => '537bc0a4773bf70d8b4ea978185dbd4fc30c640d',
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
@@ -13,7 +13,7 @@
'__root__' => array(
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'reference' => '44f37b7f74e1fcbfbbdf26036117d14404011abd',
'reference' => '537bc0a4773bf70d8b4ea978185dbd4fc30c640d',
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
@@ -119,14 +119,23 @@
'dev_requirement' => true,
),
'phpstan/phpstan' => array(
'pretty_version' => '1.10.3',
'version' => '1.10.3.0',
'reference' => '5419375b5891add97dc74be71e6c1c34baaddf64',
'pretty_version' => '1.10.2',
'version' => '1.10.2.0',
'reference' => 'a2ffec7db373d8da4973d1d62add872db5cd22dd',
'type' => 'library',
'install_path' => __DIR__ . '/../phpstan/phpstan',
'aliases' => array(),
'dev_requirement' => true,
),
'phpstan/phpstan-strict-rules' => array(
'pretty_version' => '1.5.0',
'version' => '1.5.0.0',
'reference' => 'b7dd96a5503919a43b3cd06a2dced9d4252492f2',
'type' => 'phpstan-extension',
'install_path' => __DIR__ . '/../phpstan/phpstan-strict-rules',
'aliases' => array(),
'dev_requirement' => true,
),
'psr/container' => array(
'pretty_version' => '2.0.2',
'version' => '2.0.2.0',

View File

@@ -0,0 +1,27 @@
root = true
[*]
end_of_line = lf
insert_final_newline = true
charset = utf-8
trim_trailing_whitespace = true
[*.{php,phpt}]
indent_style = tab
indent_size = 4
[*.xml]
indent_style = tab
indent_size = 4
[*.neon]
indent_style = tab
indent_size = 4
[*.{yaml,yml}]
indent_style = space
indent_size = 2
[composer.json]
indent_style = tab
indent_size = 4

View File

@@ -0,0 +1,22 @@
MIT License
Copyright (c) 2016 Ondřej Mirtes
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,98 @@
# Extra strict and opinionated rules for PHPStan
[![Build](https://github.com/phpstan/phpstan-strict-rules/workflows/Build/badge.svg)](https://github.com/phpstan/phpstan-strict-rules/actions)
[![Latest Stable Version](https://poser.pugx.org/phpstan/phpstan-strict-rules/v/stable)](https://packagist.org/packages/phpstan/phpstan-strict-rules)
[![License](https://poser.pugx.org/phpstan/phpstan-strict-rules/license)](https://packagist.org/packages/phpstan/phpstan-strict-rules)
[PHPStan](https://phpstan.org/) focuses on finding bugs in your code. But in PHP there's a lot of leeway in how stuff can be written. This repository contains additional rules that revolve around strictly and strongly typed code with no loose casting for those who want additional safety in extremely defensive programming:
* Require booleans in `if`, `elseif`, ternary operator, after `!`, and on both sides of `&&` and `||`.
* Require numeric operands or arrays in `+` and numeric operands in `-`/`*`/`/`/`**`/`%`.
* Require numeric operand in `$var++`, `$var--`, `++$var`and `--$var`.
* These functions contain a `$strict` parameter for better type safety, it must be set to `true`:
* `in_array` (3rd parameter)
* `array_search` (3rd parameter)
* `array_keys` (3rd parameter; only if the 2nd parameter `$search_value` is provided)
* `base64_decode` (2nd parameter)
* Variables assigned in `while` loop condition and `for` loop initial assignment cannot be used after the loop.
* Variables set in foreach that's always looped thanks to non-empty arrays cannot be used after the loop.
* Types in `switch` condition and `case` value must match. PHP compares them loosely by default and that can lead to unexpected results.
* Check that statically declared methods are called statically.
* Disallow `empty()` - it's a very loose comparison (see [manual](https://php.net/empty)), it's recommended to use more strict one.
* Disallow short ternary operator (`?:`) - implies weak comparison, it's recommended to use null coalesce operator (`??`) or ternary operator with strict condition.
* Disallow variable variables (`$$foo`, `$this->$method()` etc.)
* Disallow overwriting variables with foreach key and value variables
* Always true `instanceof`, type-checking `is_*` functions and strict comparisons `===`/`!==`. These checks can be turned off by setting `checkAlwaysTrueInstanceof`/`checkAlwaysTrueCheckTypeFunctionCall`/`checkAlwaysTrueStrictComparison` to false.
* Correct case for referenced and called function names.
* Correct case for inherited and implemented method names.
* Contravariance for parameter types and covariance for return types in inherited methods (also known as Liskov substitution principle - LSP)
* Check LSP even for static methods
* Require calling parent constructor
* Disallow usage of backtick operator (`` $ls = `ls -la` ``)
* Closure should use `$this` directly instead of using `$this` variable indirectly
Additional rules are coming in subsequent releases!
## Installation
To use this extension, require it in [Composer](https://getcomposer.org/):
```
composer require --dev phpstan/phpstan-strict-rules
```
If you also install [phpstan/extension-installer](https://github.com/phpstan/extension-installer) then you're all set!
<details>
<summary>Manual installation</summary>
If you don't want to use `phpstan/extension-installer`, include rules.neon in your project's PHPStan config:
```
includes:
- vendor/phpstan/phpstan-strict-rules/rules.neon
```
</details>
## Disabling rules
You can disable rules using configuration parameters:
```neon
parameters:
strictRules:
disallowedLooseComparison: false
booleansInConditions: false
uselessCast: false
requireParentConstructorCall: false
disallowedConstructs: false
overwriteVariablesWithLoop: false
closureUsesThis: false
matchingInheritedMethodNames: false
numericOperandsInArithmeticOperators: false
strictCalls: false
switchConditionsMatchingType: false
noVariableVariables: false
```
## Enabling rules one-by-one
If you don't want to start using all the available strict rules at once but only one or two, you can!
You can disable all rules from the included `rules.neon` with:
```neon
parameters:
strictRules:
allRules: false
```
Then you can re-enable individual rules with configuration parameters:
```neon
parameters:
strictRules:
allRules: false
booleansInConditions: true
```

View File

@@ -0,0 +1,12 @@
{
"require-dev": {
"consistence-community/coding-standard": "^3.10",
"dealerdirect/phpcodesniffer-composer-installer": "^0.7.0",
"slevomat/coding-standard": "^7.0"
},
"config": {
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": true
}
}
}

View File

@@ -0,0 +1,322 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "4485bbedba7bcc71ace5f69dbb9b6c47",
"packages": [],
"packages-dev": [
{
"name": "consistence-community/coding-standard",
"version": "3.11.1",
"source": {
"type": "git",
"url": "https://github.com/consistence-community/coding-standard.git",
"reference": "4632fead8c9ee8f50044fcbce9f66c797b34c0df"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/consistence-community/coding-standard/zipball/4632fead8c9ee8f50044fcbce9f66c797b34c0df",
"reference": "4632fead8c9ee8f50044fcbce9f66c797b34c0df",
"shasum": ""
},
"require": {
"php": ">=7.4",
"slevomat/coding-standard": "~7.0",
"squizlabs/php_codesniffer": "~3.6.0"
},
"replace": {
"consistence/coding-standard": "3.10.*"
},
"require-dev": {
"phing/phing": "2.16.4",
"php-parallel-lint/php-parallel-lint": "1.3.0",
"phpunit/phpunit": "9.5.4"
},
"type": "library",
"autoload": {
"psr-4": {
"Consistence\\": [
"Consistence"
]
},
"classmap": [
"Consistence"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Vašek Purchart",
"email": "me@vasekpurchart.cz",
"homepage": "http://vasekpurchart.cz"
}
],
"description": "Consistence - Coding Standard - PHP Code Sniffer rules",
"keywords": [
"Coding Standard",
"PHPCodeSniffer",
"codesniffer",
"coding",
"cs",
"phpcs",
"ruleset",
"sniffer",
"standard"
],
"support": {
"issues": "https://github.com/consistence-community/coding-standard/issues",
"source": "https://github.com/consistence-community/coding-standard/tree/3.11.1"
},
"time": "2021-05-03T18:13:22+00:00"
},
{
"name": "dealerdirect/phpcodesniffer-composer-installer",
"version": "v0.7.2",
"source": {
"type": "git",
"url": "https://github.com/Dealerdirect/phpcodesniffer-composer-installer.git",
"reference": "1c968e542d8843d7cd71de3c5c9c3ff3ad71a1db"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/Dealerdirect/phpcodesniffer-composer-installer/zipball/1c968e542d8843d7cd71de3c5c9c3ff3ad71a1db",
"reference": "1c968e542d8843d7cd71de3c5c9c3ff3ad71a1db",
"shasum": ""
},
"require": {
"composer-plugin-api": "^1.0 || ^2.0",
"php": ">=5.3",
"squizlabs/php_codesniffer": "^2.0 || ^3.1.0 || ^4.0"
},
"require-dev": {
"composer/composer": "*",
"php-parallel-lint/php-parallel-lint": "^1.3.1",
"phpcompatibility/php-compatibility": "^9.0"
},
"type": "composer-plugin",
"extra": {
"class": "Dealerdirect\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\Plugin"
},
"autoload": {
"psr-4": {
"Dealerdirect\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Franck Nijhof",
"email": "franck.nijhof@dealerdirect.com",
"homepage": "http://www.frenck.nl",
"role": "Developer / IT Manager"
},
{
"name": "Contributors",
"homepage": "https://github.com/Dealerdirect/phpcodesniffer-composer-installer/graphs/contributors"
}
],
"description": "PHP_CodeSniffer Standards Composer Installer Plugin",
"homepage": "http://www.dealerdirect.com",
"keywords": [
"PHPCodeSniffer",
"PHP_CodeSniffer",
"code quality",
"codesniffer",
"composer",
"installer",
"phpcbf",
"phpcs",
"plugin",
"qa",
"quality",
"standard",
"standards",
"style guide",
"stylecheck",
"tests"
],
"support": {
"issues": "https://github.com/dealerdirect/phpcodesniffer-composer-installer/issues",
"source": "https://github.com/dealerdirect/phpcodesniffer-composer-installer"
},
"time": "2022-02-04T12:51:07+00:00"
},
{
"name": "phpstan/phpdoc-parser",
"version": "1.5.1",
"source": {
"type": "git",
"url": "https://github.com/phpstan/phpdoc-parser.git",
"reference": "981cc368a216c988e862a75e526b6076987d1b50"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpstan/phpdoc-parser/zipball/981cc368a216c988e862a75e526b6076987d1b50",
"reference": "981cc368a216c988e862a75e526b6076987d1b50",
"shasum": ""
},
"require": {
"php": "^7.2 || ^8.0"
},
"require-dev": {
"php-parallel-lint/php-parallel-lint": "^1.2",
"phpstan/extension-installer": "^1.0",
"phpstan/phpstan": "^1.5",
"phpstan/phpstan-strict-rules": "^1.0",
"phpunit/phpunit": "^9.5",
"symfony/process": "^5.2"
},
"type": "library",
"autoload": {
"psr-4": {
"PHPStan\\PhpDocParser\\": [
"src/"
]
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"description": "PHPDoc parser with support for nullable, intersection and generic types",
"support": {
"issues": "https://github.com/phpstan/phpdoc-parser/issues",
"source": "https://github.com/phpstan/phpdoc-parser/tree/1.5.1"
},
"time": "2022-05-05T11:32:40+00:00"
},
{
"name": "slevomat/coding-standard",
"version": "7.2.1",
"source": {
"type": "git",
"url": "https://github.com/slevomat/coding-standard.git",
"reference": "aff06ae7a84e4534bf6f821dc982a93a5d477c90"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/slevomat/coding-standard/zipball/aff06ae7a84e4534bf6f821dc982a93a5d477c90",
"reference": "aff06ae7a84e4534bf6f821dc982a93a5d477c90",
"shasum": ""
},
"require": {
"dealerdirect/phpcodesniffer-composer-installer": "^0.6.2 || ^0.7",
"php": "^7.2 || ^8.0",
"phpstan/phpdoc-parser": "^1.5.1",
"squizlabs/php_codesniffer": "^3.6.2"
},
"require-dev": {
"phing/phing": "2.17.3",
"php-parallel-lint/php-parallel-lint": "1.3.2",
"phpstan/phpstan": "1.4.10|1.7.1",
"phpstan/phpstan-deprecation-rules": "1.0.0",
"phpstan/phpstan-phpunit": "1.0.0|1.1.1",
"phpstan/phpstan-strict-rules": "1.2.3",
"phpunit/phpunit": "7.5.20|8.5.21|9.5.20"
},
"type": "phpcodesniffer-standard",
"extra": {
"branch-alias": {
"dev-master": "7.x-dev"
}
},
"autoload": {
"psr-4": {
"SlevomatCodingStandard\\": "SlevomatCodingStandard"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"description": "Slevomat Coding Standard for PHP_CodeSniffer complements Consistence Coding Standard by providing sniffs with additional checks.",
"support": {
"issues": "https://github.com/slevomat/coding-standard/issues",
"source": "https://github.com/slevomat/coding-standard/tree/7.2.1"
},
"funding": [
{
"url": "https://github.com/kukulich",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/slevomat/coding-standard",
"type": "tidelift"
}
],
"time": "2022-05-25T10:58:12+00:00"
},
{
"name": "squizlabs/php_codesniffer",
"version": "3.6.2",
"source": {
"type": "git",
"url": "https://github.com/squizlabs/PHP_CodeSniffer.git",
"reference": "5e4e71592f69da17871dba6e80dd51bce74a351a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/5e4e71592f69da17871dba6e80dd51bce74a351a",
"reference": "5e4e71592f69da17871dba6e80dd51bce74a351a",
"shasum": ""
},
"require": {
"ext-simplexml": "*",
"ext-tokenizer": "*",
"ext-xmlwriter": "*",
"php": ">=5.4.0"
},
"require-dev": {
"phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0"
},
"bin": [
"bin/phpcs",
"bin/phpcbf"
],
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.x-dev"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Greg Sherwood",
"role": "lead"
}
],
"description": "PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.",
"homepage": "https://github.com/squizlabs/PHP_CodeSniffer",
"keywords": [
"phpcs",
"standards"
],
"support": {
"issues": "https://github.com/squizlabs/PHP_CodeSniffer/issues",
"source": "https://github.com/squizlabs/PHP_CodeSniffer",
"wiki": "https://github.com/squizlabs/PHP_CodeSniffer/wiki"
},
"time": "2021-12-12T21:44:58+00:00"
}
],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"prefer-stable": false,
"prefer-lowest": false,
"platform": [],
"platform-dev": [],
"plugin-api-version": "2.3.0"
}

View File

@@ -0,0 +1,44 @@
{
"name": "phpstan/phpstan-strict-rules",
"type": "phpstan-extension",
"description": "Extra strict and opinionated rules for PHPStan",
"license": [
"MIT"
],
"require": {
"php": "^7.2 || ^8.0",
"phpstan/phpstan": "^1.10"
},
"require-dev": {
"nikic/php-parser": "^4.13.0",
"php-parallel-lint/php-parallel-lint": "^1.2",
"phpstan/phpstan-deprecation-rules": "^1.1",
"phpstan/phpstan-phpunit": "^1.0",
"phpunit/phpunit": "^9.5"
},
"config": {
"platform": {
"php": "7.4.6"
},
"sort-packages": true
},
"extra": {
"phpstan": {
"includes": [
"rules.neon"
]
}
},
"autoload": {
"psr-4": {
"PHPStan\\": "src/"
}
},
"autoload-dev": {
"classmap": [
"tests/"
]
},
"minimum-stability": "dev",
"prefer-stable": true
}

View File

@@ -0,0 +1,478 @@
parameters:
ignoreErrors:
-
message: "#^Class PHPStan\\\\Rules\\\\BooleansInConditions\\\\BooleanInBooleanNotRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/BooleansInConditions/BooleanInBooleanNotRule.php
-
message: "#^Parameter \\#1 \\$node \\(PhpParser\\\\Node\\\\Expr\\\\BooleanNot\\) of method PHPStan\\\\Rules\\\\BooleansInConditions\\\\BooleanInBooleanNotRule\\:\\:processNode\\(\\) should be contravariant with parameter \\$node \\(PhpParser\\\\Node\\) of method PHPStan\\\\Rules\\\\Rule\\<PhpParser\\\\Node\\>\\:\\:processNode\\(\\)$#"
count: 1
path: src/Rules/BooleansInConditions/BooleanInBooleanNotRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\BooleansInConditions\\\\BooleanInElseIfConditionRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/BooleansInConditions/BooleanInElseIfConditionRule.php
-
message: "#^Parameter \\#1 \\$node \\(PhpParser\\\\Node\\\\Stmt\\\\ElseIf_\\) of method PHPStan\\\\Rules\\\\BooleansInConditions\\\\BooleanInElseIfConditionRule\\:\\:processNode\\(\\) should be contravariant with parameter \\$node \\(PhpParser\\\\Node\\) of method PHPStan\\\\Rules\\\\Rule\\<PhpParser\\\\Node\\>\\:\\:processNode\\(\\)$#"
count: 1
path: src/Rules/BooleansInConditions/BooleanInElseIfConditionRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\BooleansInConditions\\\\BooleanInIfConditionRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/BooleansInConditions/BooleanInIfConditionRule.php
-
message: "#^Parameter \\#1 \\$node \\(PhpParser\\\\Node\\\\Stmt\\\\If_\\) of method PHPStan\\\\Rules\\\\BooleansInConditions\\\\BooleanInIfConditionRule\\:\\:processNode\\(\\) should be contravariant with parameter \\$node \\(PhpParser\\\\Node\\) of method PHPStan\\\\Rules\\\\Rule\\<PhpParser\\\\Node\\>\\:\\:processNode\\(\\)$#"
count: 1
path: src/Rules/BooleansInConditions/BooleanInIfConditionRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\BooleansInConditions\\\\BooleanInTernaryOperatorRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/BooleansInConditions/BooleanInTernaryOperatorRule.php
-
message: "#^Parameter \\#1 \\$node \\(PhpParser\\\\Node\\\\Expr\\\\Ternary\\) of method PHPStan\\\\Rules\\\\BooleansInConditions\\\\BooleanInTernaryOperatorRule\\:\\:processNode\\(\\) should be contravariant with parameter \\$node \\(PhpParser\\\\Node\\) of method PHPStan\\\\Rules\\\\Rule\\<PhpParser\\\\Node\\>\\:\\:processNode\\(\\)$#"
count: 1
path: src/Rules/BooleansInConditions/BooleanInTernaryOperatorRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\Cast\\\\UselessCastRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/Cast/UselessCastRule.php
-
message: "#^Parameter \\#1 \\$node \\(PhpParser\\\\Node\\\\Expr\\\\Cast\\) of method PHPStan\\\\Rules\\\\Cast\\\\UselessCastRule\\:\\:processNode\\(\\) should be contravariant with parameter \\$node \\(PhpParser\\\\Node\\) of method PHPStan\\\\Rules\\\\Rule\\<PhpParser\\\\Node\\>\\:\\:processNode\\(\\)$#"
count: 1
path: src/Rules/Cast/UselessCastRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\Classes\\\\RequireParentConstructCallRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/Classes/RequireParentConstructCallRule.php
-
message: "#^Parameter \\#1 \\$node \\(PhpParser\\\\Node\\\\Stmt\\\\ClassMethod\\) of method PHPStan\\\\Rules\\\\Classes\\\\RequireParentConstructCallRule\\:\\:processNode\\(\\) should be contravariant with parameter \\$node \\(PhpParser\\\\Node\\) of method PHPStan\\\\Rules\\\\Rule\\<PhpParser\\\\Node\\>\\:\\:processNode\\(\\)$#"
count: 1
path: src/Rules/Classes/RequireParentConstructCallRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\DisallowedConstructs\\\\DisallowedBacktickRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/DisallowedConstructs/DisallowedBacktickRule.php
-
message: "#^Parameter \\#1 \\$node \\(PhpParser\\\\Node\\\\Expr\\\\Empty_\\) of method PHPStan\\\\Rules\\\\DisallowedConstructs\\\\DisallowedBacktickRule\\:\\:processNode\\(\\) should be contravariant with parameter \\$node \\(PhpParser\\\\Node\\) of method PHPStan\\\\Rules\\\\Rule\\<PhpParser\\\\Node\\>\\:\\:processNode\\(\\)$#"
count: 1
path: src/Rules/DisallowedConstructs/DisallowedBacktickRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\DisallowedConstructs\\\\DisallowedEmptyRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/DisallowedConstructs/DisallowedEmptyRule.php
-
message: "#^Parameter \\#1 \\$node \\(PhpParser\\\\Node\\\\Expr\\\\Empty_\\) of method PHPStan\\\\Rules\\\\DisallowedConstructs\\\\DisallowedEmptyRule\\:\\:processNode\\(\\) should be contravariant with parameter \\$node \\(PhpParser\\\\Node\\) of method PHPStan\\\\Rules\\\\Rule\\<PhpParser\\\\Node\\>\\:\\:processNode\\(\\)$#"
count: 1
path: src/Rules/DisallowedConstructs/DisallowedEmptyRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\DisallowedConstructs\\\\DisallowedImplicitArrayCreationRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/DisallowedConstructs/DisallowedImplicitArrayCreationRule.php
-
message: "#^Parameter \\#1 \\$node \\(PhpParser\\\\Node\\\\Expr\\\\Assign\\) of method PHPStan\\\\Rules\\\\DisallowedConstructs\\\\DisallowedImplicitArrayCreationRule\\:\\:processNode\\(\\) should be contravariant with parameter \\$node \\(PhpParser\\\\Node\\) of method PHPStan\\\\Rules\\\\Rule\\<PhpParser\\\\Node\\>\\:\\:processNode\\(\\)$#"
count: 1
path: src/Rules/DisallowedConstructs/DisallowedImplicitArrayCreationRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\ForeachLoop\\\\OverwriteVariablesWithForeachRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/ForeachLoop/OverwriteVariablesWithForeachRule.php
-
message: "#^Parameter \\#1 \\$node \\(PhpParser\\\\Node\\\\Stmt\\\\Foreach_\\) of method PHPStan\\\\Rules\\\\ForeachLoop\\\\OverwriteVariablesWithForeachRule\\:\\:processNode\\(\\) should be contravariant with parameter \\$node \\(PhpParser\\\\Node\\) of method PHPStan\\\\Rules\\\\Rule\\<PhpParser\\\\Node\\>\\:\\:processNode\\(\\)$#"
count: 1
path: src/Rules/ForeachLoop/OverwriteVariablesWithForeachRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\Operators\\\\OperandsInArithmeticAdditionRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/Operators/OperandsInArithmeticAdditionRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\Operators\\\\OperandsInArithmeticDivisionRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/Operators/OperandsInArithmeticDivisionRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\Operators\\\\OperandsInArithmeticExponentiationRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/Operators/OperandsInArithmeticExponentiationRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\Operators\\\\OperandsInArithmeticModuloRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/Operators/OperandsInArithmeticModuloRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\Operators\\\\OperandsInArithmeticMultiplicationRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/Operators/OperandsInArithmeticMultiplicationRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\Operators\\\\OperandsInArithmeticSubtractionRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/Operators/OperandsInArithmeticSubtractionRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\StrictCalls\\\\DynamicCallOnStaticMethodsRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/StrictCalls/DynamicCallOnStaticMethodsRule.php
-
message: "#^Parameter \\#1 \\$node \\(PhpParser\\\\Node\\\\Expr\\\\MethodCall\\) of method PHPStan\\\\Rules\\\\StrictCalls\\\\DynamicCallOnStaticMethodsRule\\:\\:processNode\\(\\) should be contravariant with parameter \\$node \\(PhpParser\\\\Node\\) of method PHPStan\\\\Rules\\\\Rule\\<PhpParser\\\\Node\\>\\:\\:processNode\\(\\)$#"
count: 1
path: src/Rules/StrictCalls/DynamicCallOnStaticMethodsRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\StrictCalls\\\\StrictFunctionCallsRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/StrictCalls/StrictFunctionCallsRule.php
-
message: "#^Parameter \\#1 \\$node \\(PhpParser\\\\Node\\\\Expr\\\\FuncCall\\) of method PHPStan\\\\Rules\\\\StrictCalls\\\\StrictFunctionCallsRule\\:\\:processNode\\(\\) should be contravariant with parameter \\$node \\(PhpParser\\\\Node\\) of method PHPStan\\\\Rules\\\\Rule\\<PhpParser\\\\Node\\>\\:\\:processNode\\(\\)$#"
count: 1
path: src/Rules/StrictCalls/StrictFunctionCallsRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\VariableVariables\\\\VariableMethodCallRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/VariableVariables/VariableMethodCallRule.php
-
message: "#^Parameter \\#1 \\$node \\(PhpParser\\\\Node\\\\Expr\\\\MethodCall\\) of method PHPStan\\\\Rules\\\\VariableVariables\\\\VariableMethodCallRule\\:\\:processNode\\(\\) should be contravariant with parameter \\$node \\(PhpParser\\\\Node\\) of method PHPStan\\\\Rules\\\\Rule\\<PhpParser\\\\Node\\>\\:\\:processNode\\(\\)$#"
count: 1
path: src/Rules/VariableVariables/VariableMethodCallRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\VariableVariables\\\\VariablePropertyFetchRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/VariableVariables/VariablePropertyFetchRule.php
-
message: "#^Parameter \\#1 \\$node \\(PhpParser\\\\Node\\\\Expr\\\\PropertyFetch\\) of method PHPStan\\\\Rules\\\\VariableVariables\\\\VariablePropertyFetchRule\\:\\:processNode\\(\\) should be contravariant with parameter \\$node \\(PhpParser\\\\Node\\) of method PHPStan\\\\Rules\\\\Rule\\<PhpParser\\\\Node\\>\\:\\:processNode\\(\\)$#"
count: 1
path: src/Rules/VariableVariables/VariablePropertyFetchRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\VariableVariables\\\\VariableStaticMethodCallRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/VariableVariables/VariableStaticMethodCallRule.php
-
message: "#^Parameter \\#1 \\$node \\(PhpParser\\\\Node\\\\Expr\\\\StaticCall\\) of method PHPStan\\\\Rules\\\\VariableVariables\\\\VariableStaticMethodCallRule\\:\\:processNode\\(\\) should be contravariant with parameter \\$node \\(PhpParser\\\\Node\\) of method PHPStan\\\\Rules\\\\Rule\\<PhpParser\\\\Node\\>\\:\\:processNode\\(\\)$#"
count: 1
path: src/Rules/VariableVariables/VariableStaticMethodCallRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\VariableVariables\\\\VariableStaticPropertyFetchRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/VariableVariables/VariableStaticPropertyFetchRule.php
-
message: "#^Parameter \\#1 \\$node \\(PhpParser\\\\Node\\\\Expr\\\\StaticPropertyFetch\\) of method PHPStan\\\\Rules\\\\VariableVariables\\\\VariableStaticPropertyFetchRule\\:\\:processNode\\(\\) should be contravariant with parameter \\$node \\(PhpParser\\\\Node\\) of method PHPStan\\\\Rules\\\\Rule\\<PhpParser\\\\Node\\>\\:\\:processNode\\(\\)$#"
count: 1
path: src/Rules/VariableVariables/VariableStaticPropertyFetchRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\VariableVariables\\\\VariableVariablesRule implements generic interface PHPStan\\\\Rules\\\\Rule but does not specify its types\\: TNodeType$#"
count: 1
path: src/Rules/VariableVariables/VariableVariablesRule.php
-
message: "#^Parameter \\#1 \\$node \\(PhpParser\\\\Node\\\\Expr\\\\Variable\\) of method PHPStan\\\\Rules\\\\VariableVariables\\\\VariableVariablesRule\\:\\:processNode\\(\\) should be contravariant with parameter \\$node \\(PhpParser\\\\Node\\) of method PHPStan\\\\Rules\\\\Rule\\<PhpParser\\\\Node\\>\\:\\:processNode\\(\\)$#"
count: 1
path: src/Rules/VariableVariables/VariableVariablesRule.php
-
message: "#^Class PHPStan\\\\Rules\\\\BooleansInConditions\\\\BooleanInBooleanNotRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/BooleansInConditions/BooleanInBooleanNotRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\BooleansInConditions\\\\BooleanInBooleanNotRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/BooleansInConditions/BooleanInBooleanNotRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\BooleansInConditions\\\\BooleanInElseIfConditionRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/BooleansInConditions/BooleanInElseIfConditionRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\BooleansInConditions\\\\BooleanInElseIfConditionRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/BooleansInConditions/BooleanInElseIfConditionRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\BooleansInConditions\\\\BooleanInIfConditionRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/BooleansInConditions/BooleanInIfConditionRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\BooleansInConditions\\\\BooleanInIfConditionRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/BooleansInConditions/BooleanInIfConditionRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\BooleansInConditions\\\\BooleanInTernaryOperatorRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/BooleansInConditions/BooleanInTernaryOperatorRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\BooleansInConditions\\\\BooleanInTernaryOperatorRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/BooleansInConditions/BooleanInTernaryOperatorRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\Cast\\\\UselessCastRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/Cast/UselessCastRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\Cast\\\\UselessCastRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/Cast/UselessCastRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\Classes\\\\RequireParentConstructCallRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/Classes/RequireParentConstructCallRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\Classes\\\\RequireParentConstructCallRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/Classes/RequireParentConstructCallRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\DisallowedConstructs\\\\DisallowedBacktickRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/DisallowedConstructs/DisallowedBacktickRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\DisallowedConstructs\\\\DisallowedBacktickRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/DisallowedConstructs/DisallowedBacktickRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\DisallowedConstructs\\\\DisallowedEmptyRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/DisallowedConstructs/DisallowedEmptyRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\DisallowedConstructs\\\\DisallowedEmptyRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/DisallowedConstructs/DisallowedEmptyRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\DisallowedConstructs\\\\DisallowedImplicitArrayCreationRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/DisallowedConstructs/DisallowedImplicitArrayCreationRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\DisallowedConstructs\\\\DisallowedImplicitArrayCreationRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/DisallowedConstructs/DisallowedImplicitArrayCreationRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\ForeachLoop\\\\OverwriteVariablesWithForeachRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/ForeachLoop/OverwriteVariablesWithForeachRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\ForeachLoop\\\\OverwriteVariablesWithForeachRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/ForeachLoop/OverwriteVariablesWithForeachRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\Methods\\\\WrongCaseOfInheritedMethodRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/Methods/WrongCaseOfInheritedMethodRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\Methods\\\\WrongCaseOfInheritedMethodRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/Methods/WrongCaseOfInheritedMethodRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\Operators\\\\OperandInArithmeticIncrementOrDecrementRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/Operators/OperandInArithmeticIncrementOrDecrementRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\Operators\\\\OperandInArithmeticIncrementOrDecrementRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/Operators/OperandInArithmeticIncrementOrDecrementRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\Operators\\\\OperandInArithmeticIncrementOrDecrementRuleTest\\:\\:createRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/Operators/OperandInArithmeticIncrementOrDecrementRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\Operators\\\\OperandInArithmeticPostDecrementRuleTest\\:\\:createRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/Operators/OperandInArithmeticPostDecrementRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\Operators\\\\OperandInArithmeticPostIncrementRuleTest\\:\\:createRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/Operators/OperandInArithmeticPostIncrementRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\Operators\\\\OperandInArithmeticPreDecrementRuleTest\\:\\:createRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/Operators/OperandInArithmeticPreDecrementRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\Operators\\\\OperandInArithmeticPreIncrementRuleTest\\:\\:createRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/Operators/OperandInArithmeticPreIncrementRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\Operators\\\\OperandsInArithmeticAdditionRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/Operators/OperandsInArithmeticAdditionRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\Operators\\\\OperandsInArithmeticAdditionRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/Operators/OperandsInArithmeticAdditionRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\Operators\\\\OperandsInArithmeticDivisionRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/Operators/OperandsInArithmeticDivisionRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\Operators\\\\OperandsInArithmeticDivisionRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/Operators/OperandsInArithmeticDivisionRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\Operators\\\\OperandsInArithmeticExponentiationRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/Operators/OperandsInArithmeticExponentiationRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\Operators\\\\OperandsInArithmeticExponentiationRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/Operators/OperandsInArithmeticExponentiationRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\Operators\\\\OperandsInArithmeticModuloRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/Operators/OperandsInArithmeticModuloRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\Operators\\\\OperandsInArithmeticModuloRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/Operators/OperandsInArithmeticModuloRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\Operators\\\\OperandsInArithmeticMultiplicationRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/Operators/OperandsInArithmeticMultiplicationRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\Operators\\\\OperandsInArithmeticMultiplicationRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/Operators/OperandsInArithmeticMultiplicationRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\Operators\\\\OperandsInArithmeticSubtractionRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/Operators/OperandsInArithmeticSubtractionRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\Operators\\\\OperandsInArithmeticSubtractionRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/Operators/OperandsInArithmeticSubtractionRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\StrictCalls\\\\DynamicCallOnStaticMethodsRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/StrictCalls/DynamicCallOnStaticMethodsRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\StrictCalls\\\\DynamicCallOnStaticMethodsRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/StrictCalls/DynamicCallOnStaticMethodsRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\StrictCalls\\\\StrictFunctionCallsRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/StrictCalls/StrictFunctionCallsRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\StrictCalls\\\\StrictFunctionCallsRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/StrictCalls/StrictFunctionCallsRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\VariableVariables\\\\VariableMethodCallRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/VariableVariables/VariableMethodCallRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\VariableVariables\\\\VariableMethodCallRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/VariableVariables/VariableMethodCallRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\VariableVariables\\\\VariablePropertyFetchRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/VariableVariables/VariablePropertyFetchRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\VariableVariables\\\\VariablePropertyFetchRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/VariableVariables/VariablePropertyFetchRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\VariableVariables\\\\VariableStaticMethodCallRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/VariableVariables/VariableStaticMethodCallRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\VariableVariables\\\\VariableStaticMethodCallRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/VariableVariables/VariableStaticMethodCallRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\VariableVariables\\\\VariableStaticPropertyFetchRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/VariableVariables/VariableStaticPropertyFetchRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\VariableVariables\\\\VariableStaticPropertyFetchRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/VariableVariables/VariableStaticPropertyFetchRuleTest.php
-
message: "#^Class PHPStan\\\\Rules\\\\VariableVariables\\\\VariableVariablesRuleTest extends generic class PHPStan\\\\Testing\\\\RuleTestCase but does not specify its types\\: TRule$#"
count: 1
path: tests/Rules/VariableVariables/VariableVariablesRuleTest.php
-
message: "#^Method PHPStan\\\\Rules\\\\VariableVariables\\\\VariableVariablesRuleTest\\:\\:getRule\\(\\) return type with generic interface PHPStan\\\\Rules\\\\Rule does not specify its types\\: TNodeType$#"
count: 1
path: tests/Rules/VariableVariables/VariableVariablesRuleTest.php

View File

@@ -0,0 +1,263 @@
parameters:
polluteScopeWithLoopInitialAssignments: false
polluteScopeWithAlwaysIterableForeach: false
checkAlwaysTrueCheckTypeFunctionCall: true
checkAlwaysTrueInstanceof: true
checkAlwaysTrueStrictComparison: true
checkAlwaysTrueLooseComparison: true
checkDynamicProperties: %featureToggles.bleedingEdge%
checkExplicitMixedMissingReturn: true
checkFunctionNameCase: true
checkInternalClassCaseSensitivity: true
reportMaybesInMethodSignatures: true
reportStaticMethodSignatures: true
reportMaybesInPropertyPhpDocTypes: true
reportWrongPhpDocTypeInVarTag: %featureToggles.bleedingEdge%
featureToggles:
illegalConstructorMethodCall: %featureToggles.bleedingEdge%
strictRules:
allRules: true
disallowedLooseComparison: [%strictRules.allRules%, %featureToggles.bleedingEdge%]
booleansInConditions: %strictRules.allRules%
uselessCast: %strictRules.allRules%
requireParentConstructorCall: %strictRules.allRules%
disallowedConstructs: %strictRules.allRules%
overwriteVariablesWithLoop: %strictRules.allRules%
closureUsesThis: %strictRules.allRules%
matchingInheritedMethodNames: %strictRules.allRules%
numericOperandsInArithmeticOperators: %strictRules.allRules%
strictCalls: %strictRules.allRules%
switchConditionsMatchingType: %strictRules.allRules%
noVariableVariables: %strictRules.allRules%
parametersSchema:
strictRules: structure([
allRules: anyOf(bool(), arrayOf(bool())),
disallowedLooseComparison: anyOf(bool(), arrayOf(bool())),
booleansInConditions: anyOf(bool(), arrayOf(bool()))
uselessCast: anyOf(bool(), arrayOf(bool()))
requireParentConstructorCall: anyOf(bool(), arrayOf(bool()))
disallowedConstructs: anyOf(bool(), arrayOf(bool()))
overwriteVariablesWithLoop: anyOf(bool(), arrayOf(bool()))
closureUsesThis: anyOf(bool(), arrayOf(bool()))
matchingInheritedMethodNames: anyOf(bool(), arrayOf(bool()))
numericOperandsInArithmeticOperators: anyOf(bool(), arrayOf(bool()))
strictCalls: anyOf(bool(), arrayOf(bool()))
switchConditionsMatchingType: anyOf(bool(), arrayOf(bool()))
noVariableVariables: anyOf(bool(), arrayOf(bool()))
])
conditionalTags:
PHPStan\Rules\DisallowedConstructs\DisallowedLooseComparisonRule:
phpstan.rules.rule: %strictRules.disallowedLooseComparison%
PHPStan\Rules\BooleansInConditions\BooleanInBooleanAndRule:
phpstan.rules.rule: %strictRules.booleansInConditions%
PHPStan\Rules\BooleansInConditions\BooleanInBooleanNotRule:
phpstan.rules.rule: %strictRules.booleansInConditions%
PHPStan\Rules\BooleansInConditions\BooleanInBooleanOrRule:
phpstan.rules.rule: %strictRules.booleansInConditions%
PHPStan\Rules\BooleansInConditions\BooleanInElseIfConditionRule:
phpstan.rules.rule: %strictRules.booleansInConditions%
PHPStan\Rules\BooleansInConditions\BooleanInIfConditionRule:
phpstan.rules.rule: %strictRules.booleansInConditions%
PHPStan\Rules\BooleansInConditions\BooleanInTernaryOperatorRule:
phpstan.rules.rule: %strictRules.booleansInConditions%
PHPStan\Rules\Cast\UselessCastRule:
phpstan.rules.rule: %strictRules.uselessCast%
PHPStan\Rules\Classes\RequireParentConstructCallRule:
phpstan.rules.rule: %strictRules.requireParentConstructorCall%
PHPStan\Rules\DisallowedConstructs\DisallowedBacktickRule:
phpstan.rules.rule: %strictRules.disallowedConstructs%
PHPStan\Rules\DisallowedConstructs\DisallowedEmptyRule:
phpstan.rules.rule: %strictRules.disallowedConstructs%
PHPStan\Rules\DisallowedConstructs\DisallowedImplicitArrayCreationRule:
phpstan.rules.rule: %strictRules.disallowedConstructs%
PHPStan\Rules\DisallowedConstructs\DisallowedShortTernaryRule:
phpstan.rules.rule: %strictRules.disallowedConstructs%
PHPStan\Rules\ForeachLoop\OverwriteVariablesWithForeachRule:
phpstan.rules.rule: %strictRules.overwriteVariablesWithLoop%
PHPStan\Rules\ForLoop\OverwriteVariablesWithForLoopInitRule:
phpstan.rules.rule: %strictRules.overwriteVariablesWithLoop%
PHPStan\Rules\Functions\ClosureUsesThisRule:
phpstan.rules.rule: %strictRules.closureUsesThis%
PHPStan\Rules\Methods\WrongCaseOfInheritedMethodRule:
phpstan.rules.rule: %strictRules.matchingInheritedMethodNames%
PHPStan\Rules\Operators\OperandInArithmeticPostDecrementRule:
phpstan.rules.rule: %strictRules.numericOperandsInArithmeticOperators%
PHPStan\Rules\Operators\OperandInArithmeticPostIncrementRule:
phpstan.rules.rule: %strictRules.numericOperandsInArithmeticOperators%
PHPStan\Rules\Operators\OperandInArithmeticPreDecrementRule:
phpstan.rules.rule: %strictRules.numericOperandsInArithmeticOperators%
PHPStan\Rules\Operators\OperandInArithmeticPreIncrementRule:
phpstan.rules.rule: %strictRules.numericOperandsInArithmeticOperators%
PHPStan\Rules\Operators\OperandsInArithmeticAdditionRule:
phpstan.rules.rule: %strictRules.numericOperandsInArithmeticOperators%
PHPStan\Rules\Operators\OperandsInArithmeticDivisionRule:
phpstan.rules.rule: %strictRules.numericOperandsInArithmeticOperators%
PHPStan\Rules\Operators\OperandsInArithmeticExponentiationRule:
phpstan.rules.rule: %strictRules.numericOperandsInArithmeticOperators%
PHPStan\Rules\Operators\OperandsInArithmeticModuloRule:
phpstan.rules.rule: %strictRules.numericOperandsInArithmeticOperators%
PHPStan\Rules\Operators\OperandsInArithmeticMultiplicationRule:
phpstan.rules.rule: %strictRules.numericOperandsInArithmeticOperators%
PHPStan\Rules\Operators\OperandsInArithmeticSubtractionRule:
phpstan.rules.rule: %strictRules.numericOperandsInArithmeticOperators%
PHPStan\Rules\StrictCalls\DynamicCallOnStaticMethodsRule:
phpstan.rules.rule: %strictRules.strictCalls%
PHPStan\Rules\StrictCalls\DynamicCallOnStaticMethodsCallableRule:
phpstan.rules.rule: %strictRules.strictCalls%
PHPStan\Rules\StrictCalls\StrictFunctionCallsRule:
phpstan.rules.rule: %strictRules.strictCalls%
PHPStan\Rules\SwitchConditions\MatchingTypeInSwitchCaseConditionRule:
phpstan.rules.rule: %strictRules.switchConditionsMatchingType%
PHPStan\Rules\VariableVariables\VariableMethodCallRule:
phpstan.rules.rule: %strictRules.noVariableVariables%
PHPStan\Rules\VariableVariables\VariableMethodCallableRule:
phpstan.rules.rule: %strictRules.noVariableVariables%
PHPStan\Rules\VariableVariables\VariableStaticMethodCallRule:
phpstan.rules.rule: %strictRules.noVariableVariables%
PHPStan\Rules\VariableVariables\VariableStaticMethodCallableRule:
phpstan.rules.rule: %strictRules.noVariableVariables%
PHPStan\Rules\VariableVariables\VariableStaticPropertyFetchRule:
phpstan.rules.rule: %strictRules.noVariableVariables%
PHPStan\Rules\VariableVariables\VariableVariablesRule:
phpstan.rules.rule: %strictRules.noVariableVariables%
PHPStan\Rules\VariableVariables\VariablePropertyFetchRule:
phpstan.rules.rule: %strictRules.noVariableVariables%
services:
-
class: PHPStan\Rules\BooleansInConditions\BooleanRuleHelper
-
class: PHPStan\Rules\Operators\OperatorRuleHelper
-
class: PHPStan\Rules\VariableVariables\VariablePropertyFetchRule
arguments:
universalObjectCratesClasses: %universalObjectCratesClasses%
-
class: PHPStan\Rules\DisallowedConstructs\DisallowedLooseComparisonRule
-
class: PHPStan\Rules\BooleansInConditions\BooleanInBooleanAndRule
-
class: PHPStan\Rules\BooleansInConditions\BooleanInBooleanNotRule
-
class: PHPStan\Rules\BooleansInConditions\BooleanInBooleanOrRule
-
class: PHPStan\Rules\BooleansInConditions\BooleanInElseIfConditionRule
-
class: PHPStan\Rules\BooleansInConditions\BooleanInIfConditionRule
-
class: PHPStan\Rules\BooleansInConditions\BooleanInTernaryOperatorRule
-
class: PHPStan\Rules\Cast\UselessCastRule
arguments:
treatPhpDocTypesAsCertain: %treatPhpDocTypesAsCertain%
-
class: PHPStan\Rules\Classes\RequireParentConstructCallRule
-
class: PHPStan\Rules\DisallowedConstructs\DisallowedBacktickRule
-
class: PHPStan\Rules\DisallowedConstructs\DisallowedEmptyRule
-
class: PHPStan\Rules\DisallowedConstructs\DisallowedImplicitArrayCreationRule
-
class: PHPStan\Rules\DisallowedConstructs\DisallowedShortTernaryRule
-
class: PHPStan\Rules\ForeachLoop\OverwriteVariablesWithForeachRule
-
class: PHPStan\Rules\ForLoop\OverwriteVariablesWithForLoopInitRule
-
class: PHPStan\Rules\Functions\ClosureUsesThisRule
-
class: PHPStan\Rules\Methods\WrongCaseOfInheritedMethodRule
-
class: PHPStan\Rules\Operators\OperandInArithmeticPostDecrementRule
-
class: PHPStan\Rules\Operators\OperandInArithmeticPostIncrementRule
-
class: PHPStan\Rules\Operators\OperandInArithmeticPreDecrementRule
-
class: PHPStan\Rules\Operators\OperandInArithmeticPreIncrementRule
-
class: PHPStan\Rules\Operators\OperandsInArithmeticAdditionRule
arguments:
bleedingEdge: %featureToggles.bleedingEdge%
-
class: PHPStan\Rules\Operators\OperandsInArithmeticDivisionRule
arguments:
bleedingEdge: %featureToggles.bleedingEdge%
-
class: PHPStan\Rules\Operators\OperandsInArithmeticExponentiationRule
arguments:
bleedingEdge: %featureToggles.bleedingEdge%
-
class: PHPStan\Rules\Operators\OperandsInArithmeticModuloRule
arguments:
bleedingEdge: %featureToggles.bleedingEdge%
-
class: PHPStan\Rules\Operators\OperandsInArithmeticMultiplicationRule
arguments:
bleedingEdge: %featureToggles.bleedingEdge%
-
class: PHPStan\Rules\Operators\OperandsInArithmeticSubtractionRule
arguments:
bleedingEdge: %featureToggles.bleedingEdge%
-
class: PHPStan\Rules\StrictCalls\DynamicCallOnStaticMethodsRule
-
class: PHPStan\Rules\StrictCalls\DynamicCallOnStaticMethodsCallableRule
-
class: PHPStan\Rules\StrictCalls\StrictFunctionCallsRule
-
class: PHPStan\Rules\SwitchConditions\MatchingTypeInSwitchCaseConditionRule
-
class: PHPStan\Rules\VariableVariables\VariableMethodCallRule
-
class: PHPStan\Rules\VariableVariables\VariableMethodCallableRule
-
class: PHPStan\Rules\VariableVariables\VariableStaticMethodCallRule
-
class: PHPStan\Rules\VariableVariables\VariableStaticMethodCallableRule
-
class: PHPStan\Rules\VariableVariables\VariableStaticPropertyFetchRule
-
class: PHPStan\Rules\VariableVariables\VariableVariablesRule

View File

@@ -0,0 +1,55 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\BooleansInConditions;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Node\BooleanAndNode;
use PHPStan\Rules\Rule;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
/**
* @implements Rule<BooleanAndNode>
*/
class BooleanInBooleanAndRule implements Rule
{
/** @var BooleanRuleHelper */
private $helper;
public function __construct(BooleanRuleHelper $helper)
{
$this->helper = $helper;
}
public function getNodeType(): string
{
return BooleanAndNode::class;
}
public function processNode(Node $node, Scope $scope): array
{
$originalNode = $node->getOriginalNode();
$messages = [];
if (!$this->helper->passesAsBoolean($scope, $originalNode->left)) {
$leftType = $scope->getType($originalNode->left);
$messages[] = sprintf(
'Only booleans are allowed in &&, %s given on the left side.',
$leftType->describe(VerbosityLevel::typeOnly())
);
}
$rightScope = $node->getRightScope();
if (!$this->helper->passesAsBoolean($rightScope, $originalNode->right)) {
$rightType = $rightScope->getType($originalNode->right);
$messages[] = sprintf(
'Only booleans are allowed in &&, %s given on the right side.',
$rightType->describe(VerbosityLevel::typeOnly())
);
}
return $messages;
}
}

View File

@@ -0,0 +1,48 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\BooleansInConditions;
use PhpParser\Node;
use PhpParser\Node\Expr\BooleanNot;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
class BooleanInBooleanNotRule implements Rule
{
/** @var BooleanRuleHelper */
private $helper;
public function __construct(BooleanRuleHelper $helper)
{
$this->helper = $helper;
}
public function getNodeType(): string
{
return BooleanNot::class;
}
/**
* @param BooleanNot $node
* @return string[] errors
*/
public function processNode(Node $node, Scope $scope): array
{
if ($this->helper->passesAsBoolean($scope, $node->expr)) {
return [];
}
$expressionType = $scope->getType($node->expr);
return [
sprintf(
'Only booleans are allowed in a negated boolean, %s given.',
$expressionType->describe(VerbosityLevel::typeOnly())
),
];
}
}

View File

@@ -0,0 +1,55 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\BooleansInConditions;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Node\BooleanOrNode;
use PHPStan\Rules\Rule;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
/**
* @implements Rule<BooleanOrNode>
*/
class BooleanInBooleanOrRule implements Rule
{
/** @var BooleanRuleHelper */
private $helper;
public function __construct(BooleanRuleHelper $helper)
{
$this->helper = $helper;
}
public function getNodeType(): string
{
return BooleanOrNode::class;
}
public function processNode(Node $node, Scope $scope): array
{
$originalNode = $node->getOriginalNode();
$messages = [];
if (!$this->helper->passesAsBoolean($scope, $originalNode->left)) {
$leftType = $scope->getType($originalNode->left);
$messages[] = sprintf(
'Only booleans are allowed in ||, %s given on the left side.',
$leftType->describe(VerbosityLevel::typeOnly())
);
}
$rightScope = $node->getRightScope();
if (!$this->helper->passesAsBoolean($rightScope, $originalNode->right)) {
$rightType = $rightScope->getType($originalNode->right);
$messages[] = sprintf(
'Only booleans are allowed in ||, %s given on the right side.',
$rightType->describe(VerbosityLevel::typeOnly())
);
}
return $messages;
}
}

View File

@@ -0,0 +1,48 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\BooleansInConditions;
use PhpParser\Node;
use PhpParser\Node\Stmt\ElseIf_;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
class BooleanInElseIfConditionRule implements Rule
{
/** @var BooleanRuleHelper */
private $helper;
public function __construct(BooleanRuleHelper $helper)
{
$this->helper = $helper;
}
public function getNodeType(): string
{
return ElseIf_::class;
}
/**
* @param ElseIf_ $node
* @return string[] errors
*/
public function processNode(Node $node, Scope $scope): array
{
if ($this->helper->passesAsBoolean($scope, $node->cond)) {
return [];
}
$conditionExpressionType = $scope->getType($node->cond);
return [
sprintf(
'Only booleans are allowed in an elseif condition, %s given.',
$conditionExpressionType->describe(VerbosityLevel::typeOnly())
),
];
}
}

View File

@@ -0,0 +1,48 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\BooleansInConditions;
use PhpParser\Node;
use PhpParser\Node\Stmt\If_;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
class BooleanInIfConditionRule implements Rule
{
/** @var BooleanRuleHelper */
private $helper;
public function __construct(BooleanRuleHelper $helper)
{
$this->helper = $helper;
}
public function getNodeType(): string
{
return If_::class;
}
/**
* @param If_ $node
* @return string[] errors
*/
public function processNode(Node $node, Scope $scope): array
{
if ($this->helper->passesAsBoolean($scope, $node->cond)) {
return [];
}
$conditionExpressionType = $scope->getType($node->cond);
return [
sprintf(
'Only booleans are allowed in an if condition, %s given.',
$conditionExpressionType->describe(VerbosityLevel::typeOnly())
),
];
}
}

View File

@@ -0,0 +1,52 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\BooleansInConditions;
use PhpParser\Node;
use PhpParser\Node\Expr\Ternary;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
class BooleanInTernaryOperatorRule implements Rule
{
/** @var BooleanRuleHelper */
private $helper;
public function __construct(BooleanRuleHelper $helper)
{
$this->helper = $helper;
}
public function getNodeType(): string
{
return Ternary::class;
}
/**
* @param Ternary $node
* @return string[] errors
*/
public function processNode(Node $node, Scope $scope): array
{
if ($node->if === null) {
return []; // elvis ?:
}
if ($this->helper->passesAsBoolean($scope, $node->cond)) {
return [];
}
$conditionExpressionType = $scope->getType($node->cond);
return [
sprintf(
'Only booleans are allowed in a ternary operator condition, %s given.',
$conditionExpressionType->describe(VerbosityLevel::typeOnly())
),
];
}
}

View File

@@ -0,0 +1,45 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\BooleansInConditions;
use PhpParser\Node\Expr;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\RuleLevelHelper;
use PHPStan\Type\ErrorType;
use PHPStan\Type\MixedType;
use PHPStan\Type\Type;
class BooleanRuleHelper
{
/** @var RuleLevelHelper */
private $ruleLevelHelper;
public function __construct(RuleLevelHelper $ruleLevelHelper)
{
$this->ruleLevelHelper = $ruleLevelHelper;
}
public function passesAsBoolean(Scope $scope, Expr $expr): bool
{
$type = $scope->getType($expr);
if ($type instanceof MixedType) {
return !$type->isExplicitMixed();
}
$typeToCheck = $this->ruleLevelHelper->findTypeToCheck(
$scope,
$expr,
'',
static function (Type $type): bool {
return $type->isBoolean()->yes();
}
);
$foundType = $typeToCheck->getType();
if ($foundType instanceof ErrorType) {
return true;
}
return $foundType->isBoolean()->yes();
}
}

View File

@@ -0,0 +1,74 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Cast;
use PhpParser\Node;
use PhpParser\Node\Expr\Cast;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleError;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\ErrorType;
use PHPStan\Type\GeneralizePrecision;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
class UselessCastRule implements Rule
{
/** @var bool */
private $treatPhpDocTypesAsCertain;
public function __construct(bool $treatPhpDocTypesAsCertain)
{
$this->treatPhpDocTypesAsCertain = $treatPhpDocTypesAsCertain;
}
public function getNodeType(): string
{
return Cast::class;
}
/**
* @param Cast $node
* @return RuleError[] errors
*/
public function processNode(Node $node, Scope $scope): array
{
$castType = $scope->getType($node);
if ($castType instanceof ErrorType) {
return [];
}
$castType = $castType->generalize(GeneralizePrecision::lessSpecific());
if ($this->treatPhpDocTypesAsCertain) {
$expressionType = $scope->getType($node->expr);
} else {
$expressionType = $scope->getNativeType($node->expr);
}
if ($castType->isSuperTypeOf($expressionType)->yes()) {
$addTip = function (RuleErrorBuilder $ruleErrorBuilder) use ($scope, $node, $castType): RuleErrorBuilder {
if (!$this->treatPhpDocTypesAsCertain) {
return $ruleErrorBuilder;
}
$expressionTypeWithoutPhpDoc = $scope->getNativeType($node->expr);
if ($castType->isSuperTypeOf($expressionTypeWithoutPhpDoc)->yes()) {
return $ruleErrorBuilder;
}
return $ruleErrorBuilder->tip('Because the type is coming from a PHPDoc, you can turn off this check by setting <fg=cyan>treatPhpDocTypesAsCertain: false</> in your <fg=cyan>%configurationFile%</>.');
};
return [
$addTip(RuleErrorBuilder::message(sprintf(
'Casting to %s something that\'s already %s.',
$castType->describe(VerbosityLevel::typeOnly()),
$expressionType->describe(VerbosityLevel::typeOnly())
)))->build(),
];
}
return [];
}
}

View File

@@ -0,0 +1,157 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Classes;
use PhpParser\Node;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt\ClassMethod;
use PHPStan\Analyser\Scope;
use PHPStan\BetterReflection\Reflection\Adapter\ReflectionClass;
use PHPStan\BetterReflection\Reflection\Adapter\ReflectionEnum;
use PHPStan\Rules\Rule;
use PHPStan\ShouldNotHappenException;
use function property_exists;
use function sprintf;
class RequireParentConstructCallRule implements Rule
{
public function getNodeType(): string
{
return ClassMethod::class;
}
/**
* @param ClassMethod $node
* @return string[]
*/
public function processNode(Node $node, Scope $scope): array
{
if (!$scope->isInClass()) {
throw new ShouldNotHappenException();
}
if ($scope->isInTrait()) {
return [];
}
if ($node->name->name !== '__construct') {
return [];
}
if ($node->isAbstract()) {
return [];
}
$classReflection = $scope->getClassReflection()->getNativeReflection();
if ($classReflection->isInterface() || $classReflection->isAnonymous()) {
return [];
}
if ($this->callsParentConstruct($node)) {
if ($classReflection->getParentClass() === false) {
return [
sprintf(
'%s::__construct() calls parent constructor but does not extend any class.',
$classReflection->getName()
),
];
}
if ($this->getParentConstructorClass($classReflection) === false) {
return [
sprintf(
'%s::__construct() calls parent constructor but parent does not have one.',
$classReflection->getName()
),
];
}
} else {
$parentClass = $this->getParentConstructorClass($classReflection);
if ($parentClass !== false) {
return [
sprintf(
'%s::__construct() does not call parent constructor from %s.',
$classReflection->getName(),
$parentClass->getName()
),
];
}
}
return [];
}
private function callsParentConstruct(Node $parserNode): bool
{
if (!property_exists($parserNode, 'stmts')) {
return false;
}
foreach ($parserNode->stmts as $statement) {
if ($statement instanceof Node\Stmt\Expression) {
$statement = $statement->expr;
}
$statement = $this->ignoreErrorSuppression($statement);
if ($statement instanceof StaticCall) {
if (
$statement->class instanceof Name
&& ((string) $statement->class === 'parent')
&& $statement->name instanceof Node\Identifier
&& $statement->name->name === '__construct'
) {
return true;
}
} else {
if ($this->callsParentConstruct($statement)) {
return true;
}
}
}
return false;
}
/**
* @param ReflectionClass|ReflectionEnum $classReflection
* @return ReflectionClass|false
*/
private function getParentConstructorClass($classReflection)
{
while ($classReflection->getParentClass() !== false) {
$constructor = $classReflection->getParentClass()->hasMethod('__construct') ? $classReflection->getParentClass()->getMethod('__construct') : null;
$constructorWithClassName = $classReflection->getParentClass()->hasMethod($classReflection->getParentClass()->getName()) ? $classReflection->getParentClass()->getMethod($classReflection->getParentClass()->getName()) : null;
if (
(
$constructor !== null
&& $constructor->getDeclaringClass()->getName() === $classReflection->getParentClass()->getName()
&& !$constructor->isAbstract()
&& !$constructor->isPrivate()
) || (
$constructorWithClassName !== null
&& $constructorWithClassName->getDeclaringClass()->getName() === $classReflection->getParentClass()->getName()
&& !$constructorWithClassName->isAbstract()
)
) {
return $classReflection->getParentClass();
}
$classReflection = $classReflection->getParentClass();
}
return false;
}
private function ignoreErrorSuppression(Node $statement): Node
{
if ($statement instanceof Node\Expr\ErrorSuppress) {
return $statement->expr;
}
return $statement;
}
}

View File

@@ -0,0 +1,30 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\DisallowedConstructs;
use PhpParser\Node;
use PhpParser\Node\Expr\Empty_;
use PhpParser\Node\Expr\ShellExec;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
class DisallowedBacktickRule implements Rule
{
public function getNodeType(): string
{
return ShellExec::class;
}
/**
* @param Empty_ $node
* @return string[]
*/
public function processNode(Node $node, Scope $scope): array
{
return [
'Backtick operator is not allowed. Use shell_exec() instead.',
];
}
}

View File

@@ -0,0 +1,29 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\DisallowedConstructs;
use PhpParser\Node;
use PhpParser\Node\Expr\Empty_;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
class DisallowedEmptyRule implements Rule
{
public function getNodeType(): string
{
return Empty_::class;
}
/**
* @param Empty_ $node
* @return string[]
*/
public function processNode(Node $node, Scope $scope): array
{
return [
'Construct empty() is not allowed. Use more strict comparison.',
];
}
}

View File

@@ -0,0 +1,61 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\DisallowedConstructs;
use PhpParser\Node;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\Variable;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use function is_string;
use function sprintf;
class DisallowedImplicitArrayCreationRule implements Rule
{
public function getNodeType(): string
{
return Assign::class;
}
/**
* @param Assign $node
* @return string[]
*/
public function processNode(Node $node, Scope $scope): array
{
if (!$node->var instanceof ArrayDimFetch) {
return [];
}
$node = $node->var;
while ($node instanceof ArrayDimFetch) {
$node = $node->var;
}
if (!$node instanceof Variable) {
return [];
}
if (!is_string($node->name)) {
return [];
}
$certainty = $scope->hasVariableType($node->name);
if ($certainty->no()) {
return [
sprintf('Implicit array creation is not allowed - variable $%s does not exist.', $node->name),
];
}
if ($certainty->maybe()) {
return [
sprintf('Implicit array creation is not allowed - variable $%s might not exist.', $node->name),
];
}
return [];
}
}

View File

@@ -0,0 +1,44 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\DisallowedConstructs;
use PhpParser\Node;
use PhpParser\Node\Expr\BinaryOp;
use PhpParser\Node\Expr\BinaryOp\Equal;
use PhpParser\Node\Expr\BinaryOp\NotEqual;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
/**
* @implements Rule<BinaryOp>
*/
class DisallowedLooseComparisonRule implements Rule
{
public function getNodeType(): string
{
return BinaryOp::class;
}
public function processNode(Node $node, Scope $scope): array
{
if ($node instanceof Equal) {
return [
RuleErrorBuilder::message(
'Loose comparison via "==" is not allowed.'
)->tip('Use strict comparison via "===" instead.')->build(),
];
}
if ($node instanceof NotEqual) {
return [
RuleErrorBuilder::message(
'Loose comparison via "!=" is not allowed.'
)->tip('Use strict comparison via "!==" instead.')->build(),
];
}
return [];
}
}

View File

@@ -0,0 +1,32 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\DisallowedConstructs;
use PhpParser\Node;
use PhpParser\Node\Expr\Ternary;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
/**
* @implements Rule<Ternary>
*/
class DisallowedShortTernaryRule implements Rule
{
public function getNodeType(): string
{
return Ternary::class;
}
public function processNode(Node $node, Scope $scope): array
{
if ($node->if !== null) {
return [];
}
return [
'Short ternary operator is not allowed. Use null coalesce operator if applicable or consider using long ternary.',
];
}
}

View File

@@ -0,0 +1,77 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\ForLoop;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Stmt\For_;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use function is_string;
use function sprintf;
/**
* @implements Rule<For_>
*/
class OverwriteVariablesWithForLoopInitRule implements Rule
{
public function getNodeType(): string
{
return For_::class;
}
/**
* @param For_ $node
* @return string[]
*/
public function processNode(Node $node, Scope $scope): array
{
$errors = [];
foreach ($node->init as $expr) {
if (!($expr instanceof Assign)) {
continue;
}
foreach ($this->checkValueVar($scope, $expr->var) as $error) {
$errors[] = $error;
}
}
return $errors;
}
/**
* @return string[]
*/
private function checkValueVar(Scope $scope, Expr $expr): array
{
$errors = [];
if (
$expr instanceof Node\Expr\Variable
&& is_string($expr->name)
&& $scope->hasVariableType($expr->name)->yes()
) {
$errors[] = sprintf('For loop initial assignment overwrites variable $%s.', $expr->name);
}
if (
$expr instanceof Node\Expr\List_
|| $expr instanceof Node\Expr\Array_
) {
foreach ($expr->items as $item) {
if ($item === null) {
continue;
}
foreach ($this->checkValueVar($scope, $item->value) as $error) {
$errors[] = $error;
}
}
}
return $errors;
}
}

View File

@@ -0,0 +1,75 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\ForeachLoop;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Stmt\Foreach_;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use function is_string;
use function sprintf;
class OverwriteVariablesWithForeachRule implements Rule
{
public function getNodeType(): string
{
return Node\Stmt\Foreach_::class;
}
/**
* @param Foreach_ $node
* @return string[]
*/
public function processNode(Node $node, Scope $scope): array
{
$errors = [];
if (
$node->keyVar instanceof Node\Expr\Variable
&& is_string($node->keyVar->name)
&& $scope->hasVariableType($node->keyVar->name)->yes()
) {
$errors[] = sprintf('Foreach overwrites $%s with its key variable.', $node->keyVar->name);
}
foreach ($this->checkValueVar($scope, $node->valueVar) as $error) {
$errors[] = $error;
}
return $errors;
}
/**
* @return string[]
*/
private function checkValueVar(Scope $scope, Expr $expr): array
{
$errors = [];
if (
$expr instanceof Node\Expr\Variable
&& is_string($expr->name)
&& $scope->hasVariableType($expr->name)->yes()
) {
$errors[] = sprintf('Foreach overwrites $%s with its value variable.', $expr->name);
}
if (
$expr instanceof Node\Expr\List_
|| $expr instanceof Node\Expr\Array_
) {
foreach ($expr->items as $item) {
if ($item === null) {
continue;
}
foreach ($this->checkValueVar($scope, $item->value) as $error) {
$errors[] = $error;
}
}
}
return $errors;
}
}

View File

@@ -0,0 +1,51 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Functions;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\ThisType;
use function is_string;
use function sprintf;
/**
* @implements Rule<Node\Expr\Closure>
*/
class ClosureUsesThisRule implements Rule
{
public function getNodeType(): string
{
return Node\Expr\Closure::class;
}
public function processNode(Node $node, Scope $scope): array
{
if ($node->static) {
return [];
}
if ($scope->isInClosureBind()) {
return [];
}
$messages = [];
foreach ($node->uses as $closureUse) {
$varType = $scope->getType($closureUse->var);
if (!is_string($closureUse->var->name)) {
continue;
}
if (!$varType instanceof ThisType) {
continue;
}
$messages[] = RuleErrorBuilder::message(sprintf('Anonymous function uses $this assigned to variable $%s. Use $this directly in the function body.', $closureUse->var->name))
->line($closureUse->getLine())
->build();
}
return $messages;
}
}

View File

@@ -0,0 +1,87 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Methods;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Node\InClassMethodNode;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Rules\Rule;
use function sprintf;
/**
* @implements Rule<InClassMethodNode>
*/
class WrongCaseOfInheritedMethodRule implements Rule
{
public function getNodeType(): string
{
return InClassMethodNode::class;
}
public function processNode(
Node $node,
Scope $scope
): array
{
$methodReflection = $node->getMethodReflection();
$declaringClass = $methodReflection->getDeclaringClass();
$messages = [];
if ($declaringClass->getParentClass() !== null) {
$parentMessage = $this->findMethod(
$declaringClass,
$declaringClass->getParentClass(),
$methodReflection->getName()
);
if ($parentMessage !== null) {
$messages[] = $parentMessage;
}
}
foreach ($declaringClass->getInterfaces() as $interface) {
$interfaceMessage = $this->findMethod(
$declaringClass,
$interface,
$methodReflection->getName()
);
if ($interfaceMessage === null) {
continue;
}
/** @var string $interfaceMessage */
$interfaceMessage = $interfaceMessage;
$messages[] = $interfaceMessage;
}
return $messages;
}
private function findMethod(
ClassReflection $declaringClass,
ClassReflection $classReflection,
string $methodName
): ?string
{
if (!$classReflection->hasNativeMethod($methodName)) {
return null;
}
$parentMethod = $classReflection->getNativeMethod($methodName);
if ($parentMethod->getName() === $methodName) {
return null;
}
return sprintf(
'Method %s::%s() does not match %s method name: %s::%s().',
$declaringClass->getDisplayName(),
$methodName,
$classReflection->isInterface() ? 'interface' : 'parent',
$classReflection->getDisplayName(),
$parentMethod->getName()
);
}
}

View File

@@ -0,0 +1,57 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Operators;
use PhpParser\Node;
use PhpParser\Node\Expr\PostDec;
use PhpParser\Node\Expr\PostInc;
use PhpParser\Node\Expr\PreDec;
use PhpParser\Node\Expr\PreInc;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
/**
* @phpstan-template TNodeType of PreInc|PreDec|PostInc|PostDec
* @phpstan-implements Rule<TNodeType>
*/
abstract class OperandInArithmeticIncrementOrDecrementRule implements Rule
{
/** @var OperatorRuleHelper */
private $helper;
public function __construct(OperatorRuleHelper $helper)
{
$this->helper = $helper;
}
/**
* @param PreInc|PreDec|PostInc|PostDec $node
* @return string[] errors
*/
public function processNode(Node $node, Scope $scope): array
{
$messages = [];
$varType = $scope->getType($node->var);
if (
($node instanceof PreInc || $node instanceof PostInc)
&& !$this->helper->isValidForIncrement($scope, $node->var)
|| ($node instanceof PreDec || $node instanceof PostDec)
&& !$this->helper->isValidForDecrement($scope, $node->var)
) {
$messages[] = sprintf(
'Only numeric types are allowed in %s, %s given.',
$this->describeOperation(),
$varType->describe(VerbosityLevel::typeOnly())
);
}
return $messages;
}
abstract protected function describeOperation(): string;
}

View File

@@ -0,0 +1,23 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Operators;
use PhpParser\Node\Expr\PostDec;
/**
* @phpstan-extends OperandInArithmeticIncrementOrDecrementRule<PostDec>
*/
class OperandInArithmeticPostDecrementRule extends OperandInArithmeticIncrementOrDecrementRule
{
public function getNodeType(): string
{
return PostDec::class;
}
protected function describeOperation(): string
{
return 'post-decrement';
}
}

View File

@@ -0,0 +1,23 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Operators;
use PhpParser\Node\Expr\PostInc;
/**
* @phpstan-extends OperandInArithmeticIncrementOrDecrementRule<PostInc>
*/
class OperandInArithmeticPostIncrementRule extends OperandInArithmeticIncrementOrDecrementRule
{
public function getNodeType(): string
{
return PostInc::class;
}
protected function describeOperation(): string
{
return 'post-increment';
}
}

View File

@@ -0,0 +1,23 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Operators;
use PhpParser\Node\Expr\PreDec;
/**
* @phpstan-extends OperandInArithmeticIncrementOrDecrementRule<PreDec>
*/
class OperandInArithmeticPreDecrementRule extends OperandInArithmeticIncrementOrDecrementRule
{
public function getNodeType(): string
{
return PreDec::class;
}
protected function describeOperation(): string
{
return 'pre-decrement';
}
}

View File

@@ -0,0 +1,23 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Operators;
use PhpParser\Node\Expr\PreInc;
/**
* @phpstan-extends OperandInArithmeticIncrementOrDecrementRule<PreInc>
*/
class OperandInArithmeticPreIncrementRule extends OperandInArithmeticIncrementOrDecrementRule
{
public function getNodeType(): string
{
return PreInc::class;
}
protected function describeOperation(): string
{
return 'pre-increment';
}
}

View File

@@ -0,0 +1,73 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Operators;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\AssignOp\Plus as AssignOpPlus;
use PhpParser\Node\Expr\BinaryOp\Plus as BinaryOpPlus;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Type\VerbosityLevel;
use function count;
use function sprintf;
class OperandsInArithmeticAdditionRule implements Rule
{
/** @var OperatorRuleHelper */
private $helper;
/** @var bool */
private $bleedingEdge;
public function __construct(OperatorRuleHelper $helper, bool $bleedingEdge)
{
$this->helper = $helper;
$this->bleedingEdge = $bleedingEdge;
}
public function getNodeType(): string
{
return Expr::class;
}
/**
* @return string[] errors
*/
public function processNode(Node $node, Scope $scope): array
{
if ($node instanceof BinaryOpPlus) {
$left = $node->left;
$right = $node->right;
} elseif ($node instanceof AssignOpPlus && $this->bleedingEdge) {
$left = $node->var;
$right = $node->expr;
} else {
return [];
}
$leftType = $scope->getType($left);
$rightType = $scope->getType($right);
if (count($leftType->getArrays()) > 0 && count($rightType->getArrays()) > 0) {
return [];
}
$messages = [];
if (!$this->helper->isValidForArithmeticOperation($scope, $left)) {
$messages[] = sprintf(
'Only numeric types are allowed in +, %s given on the left side.',
$leftType->describe(VerbosityLevel::typeOnly())
);
}
if (!$this->helper->isValidForArithmeticOperation($scope, $right)) {
$messages[] = sprintf(
'Only numeric types are allowed in +, %s given on the right side.',
$rightType->describe(VerbosityLevel::typeOnly())
);
}
return $messages;
}
}

View File

@@ -0,0 +1,69 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Operators;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\AssignOp\Div as AssignOpDiv;
use PhpParser\Node\Expr\BinaryOp\Div as BinaryOpDiv;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
class OperandsInArithmeticDivisionRule implements Rule
{
/** @var OperatorRuleHelper */
private $helper;
/** @var bool */
private $bleedingEdge;
public function __construct(OperatorRuleHelper $helper, bool $bleedingEdge)
{
$this->helper = $helper;
$this->bleedingEdge = $bleedingEdge;
}
public function getNodeType(): string
{
return Expr::class;
}
/**
* @return string[] errors
*/
public function processNode(Node $node, Scope $scope): array
{
if ($node instanceof BinaryOpDiv) {
$left = $node->left;
$right = $node->right;
} elseif ($node instanceof AssignOpDiv && $this->bleedingEdge) {
$left = $node->var;
$right = $node->expr;
} else {
return [];
}
$messages = [];
$leftType = $scope->getType($left);
if (!$this->helper->isValidForArithmeticOperation($scope, $left)) {
$messages[] = sprintf(
'Only numeric types are allowed in /, %s given on the left side.',
$leftType->describe(VerbosityLevel::typeOnly())
);
}
$rightType = $scope->getType($right);
if (!$this->helper->isValidForArithmeticOperation($scope, $right)) {
$messages[] = sprintf(
'Only numeric types are allowed in /, %s given on the right side.',
$rightType->describe(VerbosityLevel::typeOnly())
);
}
return $messages;
}
}

View File

@@ -0,0 +1,69 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Operators;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\AssignOp\Pow as AssignOpPow;
use PhpParser\Node\Expr\BinaryOp\Pow as BinaryOpPow;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
class OperandsInArithmeticExponentiationRule implements Rule
{
/** @var OperatorRuleHelper */
private $helper;
/** @var bool */
private $bleedingEdge;
public function __construct(OperatorRuleHelper $helper, bool $bleedingEdge)
{
$this->helper = $helper;
$this->bleedingEdge = $bleedingEdge;
}
public function getNodeType(): string
{
return Expr::class;
}
/**
* @return string[] errors
*/
public function processNode(Node $node, Scope $scope): array
{
if ($node instanceof BinaryOpPow) {
$left = $node->left;
$right = $node->right;
} elseif ($node instanceof AssignOpPow && $this->bleedingEdge) {
$left = $node->var;
$right = $node->expr;
} else {
return [];
}
$messages = [];
$leftType = $scope->getType($left);
if (!$this->helper->isValidForArithmeticOperation($scope, $left)) {
$messages[] = sprintf(
'Only numeric types are allowed in **, %s given on the left side.',
$leftType->describe(VerbosityLevel::typeOnly())
);
}
$rightType = $scope->getType($right);
if (!$this->helper->isValidForArithmeticOperation($scope, $right)) {
$messages[] = sprintf(
'Only numeric types are allowed in **, %s given on the right side.',
$rightType->describe(VerbosityLevel::typeOnly())
);
}
return $messages;
}
}

View File

@@ -0,0 +1,69 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Operators;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\AssignOp\Mod as AssignOpMod;
use PhpParser\Node\Expr\BinaryOp\Mod as BinaryOpMod;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
class OperandsInArithmeticModuloRule implements Rule
{
/** @var OperatorRuleHelper */
private $helper;
/** @var bool */
private $bleedingEdge;
public function __construct(OperatorRuleHelper $helper, bool $bleedingEdge)
{
$this->helper = $helper;
$this->bleedingEdge = $bleedingEdge;
}
public function getNodeType(): string
{
return Expr::class;
}
/**
* @return string[] errors
*/
public function processNode(Node $node, Scope $scope): array
{
if ($node instanceof BinaryOpMod) {
$left = $node->left;
$right = $node->right;
} elseif ($node instanceof AssignOpMod && $this->bleedingEdge) {
$left = $node->var;
$right = $node->expr;
} else {
return [];
}
$messages = [];
$leftType = $scope->getType($left);
if (!$this->helper->isValidForArithmeticOperation($scope, $left)) {
$messages[] = sprintf(
'Only numeric types are allowed in %%, %s given on the left side.',
$leftType->describe(VerbosityLevel::typeOnly())
);
}
$rightType = $scope->getType($right);
if (!$this->helper->isValidForArithmeticOperation($scope, $right)) {
$messages[] = sprintf(
'Only numeric types are allowed in %%, %s given on the right side.',
$rightType->describe(VerbosityLevel::typeOnly())
);
}
return $messages;
}
}

View File

@@ -0,0 +1,69 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Operators;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\AssignOp\Mul as AssignOpMul;
use PhpParser\Node\Expr\BinaryOp\Mul as BinaryOpMul;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
class OperandsInArithmeticMultiplicationRule implements Rule
{
/** @var OperatorRuleHelper */
private $helper;
/** @var bool */
private $bleedingEdge;
public function __construct(OperatorRuleHelper $helper, bool $bleedingEdge)
{
$this->helper = $helper;
$this->bleedingEdge = $bleedingEdge;
}
public function getNodeType(): string
{
return Expr::class;
}
/**
* @return string[] errors
*/
public function processNode(Node $node, Scope $scope): array
{
if ($node instanceof BinaryOpMul) {
$left = $node->left;
$right = $node->right;
} elseif ($node instanceof AssignOpMul && $this->bleedingEdge) {
$left = $node->var;
$right = $node->expr;
} else {
return [];
}
$messages = [];
$leftType = $scope->getType($left);
if (!$this->helper->isValidForArithmeticOperation($scope, $left)) {
$messages[] = sprintf(
'Only numeric types are allowed in *, %s given on the left side.',
$leftType->describe(VerbosityLevel::typeOnly())
);
}
$rightType = $scope->getType($right);
if (!$this->helper->isValidForArithmeticOperation($scope, $right)) {
$messages[] = sprintf(
'Only numeric types are allowed in *, %s given on the right side.',
$rightType->describe(VerbosityLevel::typeOnly())
);
}
return $messages;
}
}

View File

@@ -0,0 +1,69 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Operators;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\AssignOp\Minus as AssignOpMinus;
use PhpParser\Node\Expr\BinaryOp\Minus as BinaryOpMinus;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
class OperandsInArithmeticSubtractionRule implements Rule
{
/** @var OperatorRuleHelper */
private $helper;
/** @var bool */
private $bleedingEdge;
public function __construct(OperatorRuleHelper $helper, bool $bleedingEdge)
{
$this->helper = $helper;
$this->bleedingEdge = $bleedingEdge;
}
public function getNodeType(): string
{
return Expr::class;
}
/**
* @return string[] errors
*/
public function processNode(Node $node, Scope $scope): array
{
if ($node instanceof BinaryOpMinus) {
$left = $node->left;
$right = $node->right;
} elseif ($node instanceof AssignOpMinus && $this->bleedingEdge) {
$left = $node->var;
$right = $node->expr;
} else {
return [];
}
$messages = [];
$leftType = $scope->getType($left);
if (!$this->helper->isValidForArithmeticOperation($scope, $left)) {
$messages[] = sprintf(
'Only numeric types are allowed in -, %s given on the left side.',
$leftType->describe(VerbosityLevel::typeOnly())
);
}
$rightType = $scope->getType($right);
if (!$this->helper->isValidForArithmeticOperation($scope, $right)) {
$messages[] = sprintf(
'Only numeric types are allowed in -, %s given on the right side.',
$rightType->describe(VerbosityLevel::typeOnly())
);
}
return $messages;
}
}

View File

@@ -0,0 +1,95 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Operators;
use PhpParser\Node\Expr;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\RuleLevelHelper;
use PHPStan\Type\Accessory\AccessoryNumericStringType;
use PHPStan\Type\BenevolentUnionType;
use PHPStan\Type\ErrorType;
use PHPStan\Type\FloatType;
use PHPStan\Type\IntegerType;
use PHPStan\Type\IntersectionType;
use PHPStan\Type\MixedType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\UnionType;
class OperatorRuleHelper
{
/** @var RuleLevelHelper */
private $ruleLevelHelper;
public function __construct(RuleLevelHelper $ruleLevelHelper)
{
$this->ruleLevelHelper = $ruleLevelHelper;
}
public function isValidForArithmeticOperation(Scope $scope, Expr $expr): bool
{
$type = $scope->getType($expr);
if ($type instanceof MixedType) {
return true;
}
// already reported by PHPStan core
if ($type->toNumber() instanceof ErrorType) {
return true;
}
return $this->isSubtypeOfNumber($scope, $expr);
}
public function isValidForIncrement(Scope $scope, Expr $expr): bool
{
$type = $scope->getType($expr);
if ($type instanceof MixedType) {
return true;
}
if ($type->isString()->yes()) {
// Because `$a = 'a'; $a++;` is valid
return true;
}
return $this->isSubtypeOfNumber($scope, $expr);
}
public function isValidForDecrement(Scope $scope, Expr $expr): bool
{
$type = $scope->getType($expr);
if ($type instanceof MixedType) {
return true;
}
return $this->isSubtypeOfNumber($scope, $expr);
}
private function isSubtypeOfNumber(Scope $scope, Expr $expr): bool
{
$acceptedType = new UnionType([new IntegerType(), new FloatType(), new IntersectionType([new StringType(), new AccessoryNumericStringType()])]);
$type = $this->ruleLevelHelper->findTypeToCheck(
$scope,
$expr,
'',
static function (Type $type) use ($acceptedType): bool {
return $acceptedType->isSuperTypeOf($type)->yes();
}
)->getType();
if ($type instanceof ErrorType) {
return true;
}
$isSuperType = $acceptedType->isSuperTypeOf($type);
if ($type instanceof BenevolentUnionType) {
return !$isSuperType->no();
}
return $isSuperType->yes();
}
}

View File

@@ -0,0 +1,65 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\StrictCalls;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Node\MethodCallableNode;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleLevelHelper;
use PHPStan\Type\ErrorType;
use PHPStan\Type\Type;
use function sprintf;
/**
* @implements Rule<MethodCallableNode>
*/
class DynamicCallOnStaticMethodsCallableRule implements Rule
{
/** @var RuleLevelHelper */
private $ruleLevelHelper;
public function __construct(RuleLevelHelper $ruleLevelHelper)
{
$this->ruleLevelHelper = $ruleLevelHelper;
}
public function getNodeType(): string
{
return MethodCallableNode::class;
}
public function processNode(Node $node, Scope $scope): array
{
if (!$node->getName() instanceof Node\Identifier) {
return [];
}
$name = $node->getName()->name;
$type = $this->ruleLevelHelper->findTypeToCheck(
$scope,
$node->getVar(),
'',
static function (Type $type) use ($name): bool {
return $type->canCallMethods()->yes() && $type->hasMethod($name)->yes();
}
)->getType();
if ($type instanceof ErrorType || !$type->canCallMethods()->yes() || !$type->hasMethod($name)->yes()) {
return [];
}
$methodReflection = $type->getMethod($name, $scope);
if ($methodReflection->isStatic()) {
return [sprintf(
'Dynamic call to static method %s::%s().',
$methodReflection->getDeclaringClass()->getDisplayName(),
$methodReflection->getName()
)];
}
return [];
}
}

View File

@@ -0,0 +1,66 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\StrictCalls;
use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleLevelHelper;
use PHPStan\Type\ErrorType;
use PHPStan\Type\Type;
use function sprintf;
class DynamicCallOnStaticMethodsRule implements Rule
{
/** @var RuleLevelHelper */
private $ruleLevelHelper;
public function __construct(RuleLevelHelper $ruleLevelHelper)
{
$this->ruleLevelHelper = $ruleLevelHelper;
}
public function getNodeType(): string
{
return MethodCall::class;
}
/**
* @param MethodCall $node
* @return string[]
*/
public function processNode(Node $node, Scope $scope): array
{
if (!$node->name instanceof Node\Identifier) {
return [];
}
$name = $node->name->name;
$type = $this->ruleLevelHelper->findTypeToCheck(
$scope,
$node->var,
'',
static function (Type $type) use ($name): bool {
return $type->canCallMethods()->yes() && $type->hasMethod($name)->yes();
}
)->getType();
if ($type instanceof ErrorType || !$type->canCallMethods()->yes() || !$type->hasMethod($name)->yes()) {
return [];
}
$methodReflection = $type->getMethod($name, $scope);
if ($methodReflection->isStatic()) {
return [sprintf(
'Dynamic call to static method %s::%s().',
$methodReflection->getDeclaringClass()->getDisplayName(),
$methodReflection->getName()
)];
}
return [];
}
}

View File

@@ -0,0 +1,77 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\StrictCalls;
use PhpParser\Node;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Name;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\Rule;
use PHPStan\Type\Constant\ConstantBooleanType;
use function array_key_exists;
use function sprintf;
use function strtolower;
class StrictFunctionCallsRule implements Rule
{
/** @var int[] */
private $functionArguments = [
'in_array' => 2,
'array_search' => 2,
'base64_decode' => 1,
'array_keys' => 2,
];
/** @var ReflectionProvider */
private $reflectionProvider;
public function __construct(ReflectionProvider $reflectionProvider)
{
$this->reflectionProvider = $reflectionProvider;
}
public function getNodeType(): string
{
return FuncCall::class;
}
/**
* @param FuncCall $node
* @return string[] errors
*/
public function processNode(Node $node, Scope $scope): array
{
if (!$node->name instanceof Name) {
return [];
}
$functionName = $this->reflectionProvider->resolveFunctionName($node->name, $scope);
if ($functionName === null) {
return [];
}
$functionName = strtolower($functionName);
if (!array_key_exists($functionName, $this->functionArguments)) {
return [];
}
if ($functionName === 'array_keys' && !array_key_exists(1, $node->getArgs())) {
return [];
}
$argumentPosition = $this->functionArguments[$functionName];
if (!array_key_exists($argumentPosition, $node->getArgs())) {
return [sprintf('Call to function %s() requires parameter #%d to be set.', $functionName, $argumentPosition + 1)];
}
$argumentType = $scope->getType($node->getArgs()[$argumentPosition]->value);
$trueType = new ConstantBooleanType(true);
if (!$trueType->isSuperTypeOf($argumentType)->yes()) {
return [sprintf('Call to function %s() requires parameter #%d to be true.', $functionName, $argumentPosition + 1)];
}
return [];
}
}

View File

@@ -0,0 +1,58 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\SwitchConditions;
use PhpParser\Node;
use PhpParser\Node\Stmt\Switch_;
use PhpParser\PrettyPrinter\Standard;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
/**
* @implements Rule<Switch_>
*/
class MatchingTypeInSwitchCaseConditionRule implements Rule
{
/** @var Standard */
private $printer;
public function __construct(Standard $printer)
{
$this->printer = $printer;
}
public function getNodeType(): string
{
return Switch_::class;
}
public function processNode(Node $node, Scope $scope): array
{
$messages = [];
$conditionType = $scope->getType($node->cond);
foreach ($node->cases as $case) {
if ($case->cond === null) {
continue;
}
$caseType = $scope->getType($case->cond);
if (!$conditionType->isSuperTypeOf($caseType)->no()) {
continue;
}
$messages[] = RuleErrorBuilder::message(sprintf(
'Switch condition type (%s) does not match case condition %s (%s).',
$conditionType->describe(VerbosityLevel::value()),
$this->printer->prettyPrintExpr($case->cond),
$caseType->describe(VerbosityLevel::typeOnly())
))->line($case->getLine())->build();
}
return $messages;
}
}

View File

@@ -0,0 +1,38 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\VariableVariables;
use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
class VariableMethodCallRule implements Rule
{
public function getNodeType(): string
{
return Node\Expr\MethodCall::class;
}
/**
* @param MethodCall $node
* @return string[]
*/
public function processNode(Node $node, Scope $scope): array
{
if ($node->name instanceof Node\Identifier) {
return [];
}
return [
sprintf(
'Variable method call on %s.',
$scope->getType($node->var)->describe(VerbosityLevel::typeOnly())
),
];
}
}

View File

@@ -0,0 +1,37 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\VariableVariables;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Node\MethodCallableNode;
use PHPStan\Rules\Rule;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
/**
* @implements Rule<MethodCallableNode>
*/
class VariableMethodCallableRule implements Rule
{
public function getNodeType(): string
{
return MethodCallableNode::class;
}
public function processNode(Node $node, Scope $scope): array
{
if ($node->getName() instanceof Node\Identifier) {
return [];
}
return [
sprintf(
'Variable method call on %s.',
$scope->getType($node->getVar())->describe(VerbosityLevel::typeOnly())
),
];
}
}

View File

@@ -0,0 +1,86 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\VariableVariables;
use PhpParser\Node;
use PhpParser\Node\Expr\PropertyFetch;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\Rule;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
class VariablePropertyFetchRule implements Rule
{
/** @var ReflectionProvider */
private $reflectionProvider;
/** @var string[] */
private $universalObjectCratesClasses;
/**
* @param string[] $universalObjectCratesClasses
*/
public function __construct(ReflectionProvider $reflectionProvider, array $universalObjectCratesClasses)
{
$this->reflectionProvider = $reflectionProvider;
$this->universalObjectCratesClasses = $universalObjectCratesClasses;
}
public function getNodeType(): string
{
return Node\Expr\PropertyFetch::class;
}
/**
* @param PropertyFetch $node
* @return string[]
*/
public function processNode(Node $node, Scope $scope): array
{
if ($node->name instanceof Node\Identifier) {
return [];
}
$fetchedOnType = $scope->getType($node->var);
foreach ($fetchedOnType->getObjectClassNames() as $referencedClass) {
if (!$this->reflectionProvider->hasClass($referencedClass)) {
continue;
}
if ($this->isUniversalObjectCrate($this->reflectionProvider->getClass($referencedClass))) {
return [];
}
}
return [
sprintf(
'Variable property access on %s.',
$fetchedOnType->describe(VerbosityLevel::typeOnly())
),
];
}
private function isUniversalObjectCrate(
ClassReflection $classReflection
): bool
{
foreach ($this->universalObjectCratesClasses as $className) {
if (!$this->reflectionProvider->hasClass($className)) {
continue;
}
if (
$classReflection->getName() === $className
|| $classReflection->isSubclassOf($className)
) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,44 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\VariableVariables;
use PhpParser\Node;
use PhpParser\Node\Expr\StaticCall;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
class VariableStaticMethodCallRule implements Rule
{
public function getNodeType(): string
{
return Node\Expr\StaticCall::class;
}
/**
* @param StaticCall $node
* @return string[]
*/
public function processNode(Node $node, Scope $scope): array
{
if ($node->name instanceof Node\Identifier) {
return [];
}
if ($node->class instanceof Node\Name) {
$methodCalledOn = $scope->resolveName($node->class);
} else {
$methodCalledOn = $scope->getType($node->class)->describe(VerbosityLevel::typeOnly());
}
return [
sprintf(
'Variable static method call on %s.',
$methodCalledOn
),
];
}
}

View File

@@ -0,0 +1,43 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\VariableVariables;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Node\StaticMethodCallableNode;
use PHPStan\Rules\Rule;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
/**
* @implements Rule<StaticMethodCallableNode>
*/
class VariableStaticMethodCallableRule implements Rule
{
public function getNodeType(): string
{
return StaticMethodCallableNode::class;
}
public function processNode(Node $node, Scope $scope): array
{
if ($node->getName() instanceof Node\Identifier) {
return [];
}
if ($node->getClass() instanceof Node\Name) {
$methodCalledOn = $scope->resolveName($node->getClass());
} else {
$methodCalledOn = $scope->getType($node->getClass())->describe(VerbosityLevel::typeOnly());
}
return [
sprintf(
'Variable static method call on %s.',
$methodCalledOn
),
];
}
}

View File

@@ -0,0 +1,44 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\VariableVariables;
use PhpParser\Node;
use PhpParser\Node\Expr\StaticPropertyFetch;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Type\VerbosityLevel;
use function sprintf;
class VariableStaticPropertyFetchRule implements Rule
{
public function getNodeType(): string
{
return Node\Expr\StaticPropertyFetch::class;
}
/**
* @param StaticPropertyFetch $node
* @return string[]
*/
public function processNode(Node $node, Scope $scope): array
{
if ($node->name instanceof Node\Identifier) {
return [];
}
if ($node->class instanceof Node\Name) {
$propertyAccessedOn = $scope->resolveName($node->class);
} else {
$propertyAccessedOn = $scope->getType($node->class)->describe(VerbosityLevel::typeOnly());
}
return [
sprintf(
'Variable static property access on %s.',
$propertyAccessedOn
),
];
}
}

View File

@@ -0,0 +1,34 @@
<?php declare(strict_types = 1);
namespace PHPStan\Rules\VariableVariables;
use PhpParser\Node;
use PhpParser\Node\Expr\Variable;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use function is_string;
class VariableVariablesRule implements Rule
{
public function getNodeType(): string
{
return Node\Expr\Variable::class;
}
/**
* @param Variable $node
* @return string[]
*/
public function processNode(Node $node, Scope $scope): array
{
if (is_string($node->name)) {
return [];
}
return [
'Variable variables are not allowed.',
];
}
}

Binary file not shown.

View File

@@ -1,16 +1,16 @@
-----BEGIN PGP SIGNATURE-----
iQIzBAABCgAdFiEE0yaA1ZV9xxFr4pwUzxoQjQ565yAFAmP6H1oACgkQzxoQjQ56
5yCVhxAAlXqhfvKCITSAJjkaIhncEBHpT5Ogby65BX1O5+SkKyc/OO7JnjlN8cLB
DKbJpdc8P2Dbfo/uBHVR5YiNX5CWYzgdMzCpLQI20Ffa7qkeRbA5ZS2AfdIfLqhD
PswlQIYxg0F3lj0L+joTxfBiHgmR5wnOUx1sLXnEbqGtFzzGstPGDg9gjKKh5EnO
g207jrm1we05+k3kKzr233/ENvQD6bBWLr2yngyMoirOuDpurAuPjkBL7vN6PDbx
DlyGDazsgU/R7aE2FtqmFC8KIU/BgnpbCSWTHBEJAqtncHbwTgneyEm+88lT6cUt
YM72Rh1+QTvS3WgJ/q7AQRik2aE83Kz2rc3XOl1ADd45J3Oan1rqQXdnKtH6qZeT
wMk6PE8SQPJ8NMHy3LT048PfMOakAtgBL5xonbVqX0IFAvKAMRijwBCNKat2yRsB
0VGnoeH7klf1fSSo0xOD20Pd0uIILAWZlBjb2e/1NRytFQkokAr1bsLD/VJHiNYh
lPQ4OztCT/uumJOAgTKm10T56CK1u0VxhIVtQ+/NkTvAwrmpX0KKqbYPP/1hZqVO
vFaWJR4iLFNt+il7dlv56jmTAneUrGrWkQdVFbz5FVpqz7abIo+/cevbSSndFZCI
K1mn42aFdYXSqVTFpkzeOQeJPPysEYDysFk7ClhE+F48HN7WAtw=
=A7BG
iQIzBAABCgAdFiEE0yaA1ZV9xxFr4pwUzxoQjQ565yAFAmP3eecACgkQzxoQjQ56
5yAH6A//R+CaBjUmbQhmamLiYATpskxv25DC/BQQ1+aK5sz8IlKcxPViN3Ke9QAq
qikQQ3ZDcNmBFR+p5ew9WuW4c99B/MX+Pg0Nc47keq/TxU/sslE1G7SuHssSCCxp
o1W3HihbZtDmPWYj3VWSmyEvFAbho/qpTsu9d34qDcryRCZ3A46NZ5zOdNa5uI2R
8hyhuPsWF0fnd3sxYSRCL0fPp6CAEWxIRiG53gmMjTfVdTsZQZVwzgsfiW3GAIRf
J7tYbGcBN3tyrJEFyFJCJkWt2ATla1LzucL6rrDUa9HzNsA5NUTOLj6j6PACQ0Vj
eCMfcDxKj/t6EJlHBpO2A5AiE8DOLs+lWmKiG7DqWOqqOnoYc/Fbv9RL3p25r7N2
gv4hhyEfBE0hoUxKSzsa7M++Ler+Js0Slxc881dpDuqvBEZFyA4M9YJTM4ckK92M
LcFC1RJ5xdHx/COpYVN3w2DvZ9BVk2kvdByJGnyQ9Tp/R8HdW+cv88kYopIXZ0R5
8m7B/zbtxMbtEzEn38JqfTtiQpE6vNH3iaWInIkP/ZZgfetCoHdXUF+NTTpTyUCm
C+NqRlgtA9NyjkdjX/kbohuxAcGsxlZu4/CfYKEIVAeCpM5sdjf4tRmmYn/5wCRF
226D4n9yPZ9YHE7HYLrRcmlx2jzsKH8wv8Z5IZ8KqZK/9tPhHoM=
=aGUS
-----END PGP SIGNATURE-----

View File

@@ -23,7 +23,6 @@ ob_end_flush();
use CoreLibs\Debug\Support;
use CoreLibs\Debug\RunningTime;
use CoreLibs\Convert\SetVarType;
$log = new CoreLibs\Debug\Logging([
'log_folder' => BASE . LOG,
@@ -79,9 +78,7 @@ for ($i = 1; $i <= 6; $i++) {
(is_array($res) ?
"Array: " . $db->log->prBl(is_array($res)) : '{-}')
) . ", "
. "cursor_ext: <pre>" . Support::printAr(
SetVarType::setArray($db->dbGetCursorExt($q_db_ret))
) . "</pre>";
. "cursor_ext: <pre>" . Support::printAr($db->dbGetCursorExt($q_db_ret)) . "</pre>";
print "Run time: " . RunningTime::hrRunningTime() . "<br>";
}
// reset all read data
@@ -98,9 +95,7 @@ for ($i = 1; $i <= 6; $i++) {
(is_array($res) ?
"Array: " . $db->log->prBl(is_array($res)) : '{-}')
) . ", "
. "cursor_ext: <pre>" . Support::printAr(
SetVarType::setArray($db->dbGetCursorExt($q_db_ret))
) . "</pre>";
. "cursor_ext: <pre>" . Support::printAr($db->dbGetCursorExt($q_db_ret)) . "</pre>";
print "Run time: " . RunningTime::hrRunningTime() . "<br>";
}
// reset all read data
@@ -117,9 +112,7 @@ for ($i = 1; $i <= 6; $i++) {
(is_array($res) ?
"Array: " . $db->log->prBl(is_array($res)) : '{-}')
) . ", "
. "cursor_ext: <pre>" . Support::printAr(
SetVarType::setArray($db->dbGetCursorExt($q_db_ret))
) . "</pre>";
. "cursor_ext: <pre>" . Support::printAr($db->dbGetCursorExt($q_db_ret)) . "</pre>";
print "Run time: " . RunningTime::hrRunningTime() . "<br>";
}
// reset all read data
@@ -136,9 +129,7 @@ for ($i = 1; $i <= 6; $i++) {
(is_array($res) ?
"Array: " . $db->log->prBl(is_array($res)) : '{-}')
) . ", "
. "cursor_ext: <pre>" . Support::printAr(
SetVarType::setArray($db->dbGetCursorExt($q_db_ret))
) . "</pre>";
. "cursor_ext: <pre>" . Support::printAr($db->dbGetCursorExt($q_db_ret)) . "</pre>";
print "Run time: " . RunningTime::hrRunningTime() . "<br>";
}
// reset all data

View File

@@ -62,11 +62,7 @@ print "VERSION LONG DB: " . $db->dbVersionInfo('server', false) . "<br>";
print "VERSION NUMERIC DB: " . $db->dbVersionNumeric() . "<br>";
print "SERVER ENCODING: " . $db->dbVersionInfo('server_encoding') . "<br>";
print "ALL PG VERSION PARAMETERS: <pre>" . print_r($db->dbVersionInfoParameters(), true) . "</pre><br>";
if (($dbh = $db->dbGetDbh()) instanceof \PgSql\Connection) {
print "ALL OUTPUT [TEST]: <pre>" . print_r(pg_version($dbh), true) . "</pre><br>";
} else {
print "NO DB HANDLER<br>";
}
print "ALL OUTPUT [TEST]: <pre>" . print_r(pg_version($db->dbGetDbh()), true) . "</pre><br>";
print "DB Version smaller $to_db_version: " . $db->dbCompareVersion('<' . $to_db_version) . "<br>";
print "DB Version smaller than $to_db_version: " . $db->dbCompareVersion('<=' . $to_db_version) . "<br>";
print "DB Version equal $to_db_version: " . $db->dbCompareVersion('=' . $to_db_version) . "<br>";
@@ -112,11 +108,7 @@ print "<br>";
print "<pre>";
if (($dbh = $db->dbGetDbh()) instanceof \PgSql\Connection) {
print "SOCKET: " . pg_socket($dbh) . "<br>";
} else {
print "NO SOCKET<br>";
}
print "SOCKET: " . pg_socket($db->dbGetDbh()) . "<br>";
// truncate test_foo table before testing
print "<b>TRUNCATE test_foo</b><br>";

View File

@@ -24,7 +24,6 @@
}
},
"require": {
"egrajp/smarty-extended": "^4.3",
"php": ">=8.1"
"egrajp/smarty-extended": "^4.3"
}
}

View File

@@ -233,11 +233,13 @@ if (
}
// set SSL on
$is_secure = false;
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
$is_secure = true;
} elseif (
!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ||
!empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on'
!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
$_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ||
!empty($_SERVER['HTTP_X_FORWARDED_SSL']) &&
$_SERVER['HTTP_X_FORWARDED_SSL'] === 'on'
) {
$is_secure = true;
}

View File

@@ -63,10 +63,8 @@ if (!defined('DIR')) {
exit('Base config could not be loaded');
}
// find trigger name "admin/" or "frontend/" in the getcwd() folder
$folder = '';
foreach (['admin', 'frontend'] as $_folder) {
if (strstr(getcwd() ?: '', DIRECTORY_SEPARATOR . $_folder)) {
$folder = $_folder;
foreach (['admin', 'frontend'] as $folder) {
if (strstr(getcwd() ?: '', DIRECTORY_SEPARATOR . $folder)) {
break;
}
}

View File

@@ -157,7 +157,7 @@ class Login
private $acl = [];
/** @var array<mixed> */
private $default_acl_list = [];
/** @var array<string,int> Reverse list to lookup level from type */
/** @var array<int|string,mixed> Reverse list to lookup level from type */
private $default_acl_list_type = [];
/** @var int default ACL level to be based on if nothing set */
private $default_acl_level = 0;
@@ -332,7 +332,7 @@ class Login
'type' => $res['type'],
'name' => $res['name']
];
$this->default_acl_list_type[(string)$res['type']] = (int)$res['level'];
$this->default_acl_list_type[$res['type']] = $res['level'];
}
// write that into the session
$_SESSION['DEFAULT_ACL_LIST'] = $this->default_acl_list;
@@ -986,7 +986,7 @@ class Login
* @param string $password the new password
* @return bool true or false if valid password or not
*/
private function loginPasswordChangeValidPassword(string $password): bool
private function loginPasswordChangeValidPassword($password): bool
{
$is_valid_password = true;
// check for valid in regex arrays in list
@@ -1126,7 +1126,7 @@ class Login
*
* @return string|null html data for login page, or null for nothing
*/
private function loginCreateLoginHTML(): ?string
private function loginCreateLoginHTML()
{
$html_string = null;
// if permission is ok, return null
@@ -1423,12 +1423,8 @@ EOM;
* @param string $username login user username
* @return void has no return
*/
private function writeLog(
string $event,
string $data,
string|int $error = '',
string $username = ''
): void {
private function writeLog(string $event, string $data, $error = '', string $username = ''): void
{
if ($this->login) {
$this->action = 'Login';
} elseif ($this->logout) {
@@ -2074,12 +2070,9 @@ EOM;
* @param string $type Type name to look in the acl list
* @return int|bool Either int level or false for not found
*/
public function loginGetAclListFromType(string $type): int|bool
public function loginGetAclListFromType(string $type)
{
if (!isset($this->default_acl_list_type[$type])) {
return false;
}
return (int)$this->default_acl_list_type[$type];
return $this->default_acl_list_type[$type] ?? false;
}
/**
@@ -2089,7 +2082,7 @@ EOM;
* @return bool true/false: if the edit access is not
* in the valid list: false
*/
public function loginCheckEditAccess(?int $edit_access_id): bool
public function loginCheckEditAccess($edit_access_id): bool
{
if ($edit_access_id === null) {
return false;
@@ -2130,10 +2123,8 @@ EOM;
* @param string|int $data_key key value to search for
* @return bool|string false for not found or string for found data
*/
public function loginGetEditAccessData(
int $edit_access_id,
string|int $data_key
): bool|string {
public function loginGetEditAccessData(int $edit_access_id, $data_key)
{
if (!isset($_SESSION['UNIT'][$edit_access_id]['data'][$data_key])) {
return false;
}
@@ -2147,12 +2138,9 @@ EOM;
* @param string $uid Edit Access UID to look for
* @return int|bool Either primary key in int or false in bool for not found
*/
public function loginGetEditAccessIdFromUid(string $uid): int|bool
public function loginGetEditAccessIdFromUid(string $uid)
{
if (!isset($_SESSION['UNIT_UID'][$uid])) {
return false;
}
return (int)$_SESSION['UNIT_UID'][$uid];
return $_SESSION['UNIT_UID'][$uid] ?? false;
}
/**
@@ -2217,10 +2205,8 @@ EOM;
* @param string|int $data_key
* @return bool|string
*/
public function loginSetEditAccessData(
int $edit_access_id,
string|int $data_key
): bool|string {
public function loginSetEditAccessData(int $edit_access_id, $data_key)
{
return $this->loginGetEditAccessData($edit_access_id, $data_key);
}
}

View File

@@ -194,7 +194,7 @@ class Backend
*/
public function adbEditLog(
string $event = '',
string|array $data = '',
$data = '',
string $write_type = 'STRING'
): void {
$data_binary = '';
@@ -262,7 +262,7 @@ class Backend
* @param string|int $menu_show_flag
* @return string|int
*/
public function adbSetMenuShowFlag(string|int $menu_show_flag): string|int
public function adbSetMenuShowFlag($menu_show_flag)
{
// must be string or int
$this->menu_show_flag = $menu_show_flag;
@@ -274,7 +274,7 @@ class Backend
*
* @return string|int
*/
public function adbGetMenuShowFlag(): string|int
public function adbGetMenuShowFlag()
{
return $this->menu_show_flag;
}
@@ -437,7 +437,7 @@ class Backend
* @return array<mixed> associative array
* @deprecated \CoreLibs\Combined\ArrayHandler::genAssocArray()
*/
public function adbAssocArray(array $db_array, string|int|bool $key, string|int|bool $value): array
public function adbAssocArray(array $db_array, $key, $value): array
{
trigger_error(
'Method ' . __METHOD__ . ' is deprecated: \CoreLibs\Combined\ArrayHandler::genAssocArray',
@@ -453,7 +453,7 @@ class Backend
* @return string formatted string
* @deprecated \CoreLibs\Convert\Byte::humanReadableByteFormat()
*/
public function adbByteStringFormat(string|int|float $number): string
public function adbByteStringFormat($number): string
{
trigger_error(
'Method ' . __METHOD__ . ' is deprecated: \CoreLibs\Convert\Byte::humanReadableByteFormat()',
@@ -482,7 +482,7 @@ class Backend
string $dummy = '',
string $path = '',
string $cache = ''
): string|bool {
) {
trigger_error(
'Method ' . __METHOD__ . ' is deprecated: \CoreLibs\Output\Image::createThumbnail()',
E_USER_DEPRECATED
@@ -569,28 +569,28 @@ class Backend
* Basic class holds exact the same, except the Year/Month/Day/etc strings
* are translated in this call
*
* @param int|string $year year YYYY
* @param int|string $month month m
* @param int|string $day day d
* @param int|string $hour hour H
* @param int|string $min min i
* @param string $suffix additional info printed after the date time
* variable in the drop down
* also used for ID in the on change JS call
* @param int $min_steps default is 1 (minute), can set to anything,
* is used as sum up from 0
* @param bool $name_pos_back default false, if set to true,
* the name will be printend
* after the drop down and not before the drop down
* @return string HTML formated strings for drop down lists
* of date and time
* @param int $year year YYYY
* @param int $month month m
* @param int $day day d
* @param int $hour hour H
* @param int $min min i
* @param string $suffix additional info printed after the date time
* variable in the drop down
* also used for ID in the on change JS call
* @param int $min_steps default is 1 (minute), can set to anything,
* is used as sum up from 0
* @param bool $name_pos_back default false, if set to true,
* the name will be printend
* after the drop down and not before the drop down
* @return string HTML formated strings for drop down lists
* of date and time
*/
public function adbPrintDateTime(
int|string $year,
int|string $month,
int|string $day,
int|string $hour,
int|string $min,
$year,
$month,
$day,
$hour,
$min,
string $suffix = '',
int $min_steps = 1,
bool $name_pos_back = false

View File

@@ -414,8 +414,6 @@ class EditBase
$elements[] = $this->form->formCreateElement('additional_acl');
break;
case 'edit_schemes':
// @deprecated Will be removed
case 'edit_schemas':
$elements[] = $this->form->formCreateElement('enabled');
$elements[] = $this->form->formCreateElement('name');
$elements[] = $this->form->formCreateElement('header_color');
@@ -534,7 +532,7 @@ class EditBase
* @throws Exception
* @throws SmartyException
*/
public function editBaseRun(): void
public function editBaseRun()
{
// set the template dir
// WARNING: this has a special check for the mailing tool layout (old layout)

View File

@@ -42,11 +42,8 @@ class Colors
* @param int|false $hsl_flag flag to check for hsl type
* @return bool True if no error, False if error
*/
private static function rgbHslContentCheck(
string $color,
int|false $rgb_flag,
int|false $hsl_flag
): bool {
private static function rgbHslContentCheck(string $color, $rgb_flag, $hsl_flag): bool
{
// extract string between () and split into elements
preg_match("/\((.*)\)/", $color, $matches);
if (

View File

@@ -25,7 +25,7 @@ class Encoding
* if null is set then "none"
* @return void
*/
public static function setErrorChar(string|int|null $string): void
public static function setErrorChar($string): void
{
if (empty($string)) {
$string = 'none';
@@ -52,7 +52,7 @@ class Encoding
* directly
* @return string|int Set error character
*/
public static function getErrorChar(bool $return_substitute_func = false): string|int
public static function getErrorChar(bool $return_substitute_func = false)
{
// return mb_substitute_character();
if ($return_substitute_func === true) {
@@ -78,14 +78,14 @@ class Encoding
* @param string $string string to test
* @param string $from_encoding encoding of string to test
* @param string $to_encoding target encoding
* @return array<string>|false false if no error or
* @return bool|array<string> false if no error or
* array with failed characters
*/
public static function checkConvertEncoding(
string $string,
string $from_encoding,
string $to_encoding
): array|false {
) {
// convert to target encoding and convert back
$temp = mb_convert_encoding($string, $to_encoding, $from_encoding);
$compare = mb_convert_encoding($temp, $from_encoding, $to_encoding);

View File

@@ -0,0 +1,41 @@
<?php
/*
* DEPRECATED: Use correct Convert\Json:: instead
*/
declare(strict_types=1);
namespace CoreLibs\Check;
use CoreLibs\Convert\Json;
class Jason
{
/**
* @param string|null $json a json string, or null data
* @param bool $override if set to true, then on json error
* set original value as array
* @return array<mixed> returns an array from the json values
* @deprecated Use Json::jsonConvertToArray()
*/
public static function jsonConvertToArray(?string $json, bool $override = false): array
{
return Json::jsonConvertToArray($json, $override);
}
/**
* @param bool|boolean $return_string [default=false] if set to true
* it will return the message string and not
* the error number
* @return int|string Either error number (0 for no error)
* or error string ('' for no error)
* @deprecated Use Json::jsonGetLastError()
*/
public static function jsonGetLastError(bool $return_string = false)
{
return Json::jsonGetLastError($return_string);
}
}
// __END__

View File

@@ -21,12 +21,12 @@ class ArrayHandler
* the needle can be found in the
* haystack array
*/
public static function arraySearchRecursive(
string|int $needle,
array $haystack,
?string $key_search_for = null
): array {
public static function arraySearchRecursive($needle, array $haystack, ?string $key_search_for = null): array
{
$path = [];
if (!is_array($haystack)) {
$haystack = [];
}
if (
$key_search_for != null &&
array_key_exists($key_search_for, $haystack) &&
@@ -72,7 +72,7 @@ class ArrayHandler
*
* @param string|int $needle needle (search for)
* @param array<mixed> $haystack haystack (search in)
* @param string|int|null $key_search_for the key to look for in
* @param string|int $key_search_for the key to look for in
* @param bool $old [true], if set to false will
* return new flat layout
* @param array<mixed>|null $path recursive call for previous path
@@ -80,9 +80,9 @@ class ArrayHandler
* the element was found
*/
public static function arraySearchRecursiveAll(
string|int $needle,
$needle,
array $haystack,
string|int|null $key_search_for,
$key_search_for,
bool $old = true,
?array $path = null
): ?array {
@@ -101,6 +101,10 @@ class ArrayHandler
$path['work'] = [];
}
}
// should not be needed because it would trigger a php mehtod error
if (!is_array($haystack)) {
$haystack = [];
}
// go through the array,
foreach ($haystack as $_key => $_value) {
@@ -148,18 +152,17 @@ class ArrayHandler
* array search simple. looks for key, value combination, if found, returns true
* on default does not strict check, so string '4' will match int 4 and vica versa
*
* @param array<mixed> $array search in as array
* @param string|int $key key (key to search in)
* @param string|int|bool $value value (what to find)
* @param bool $strict [false], if set to true, will strict check key/value
* @return bool true on found, false on not found
* @param array<mixed> $array search in as array
* @param string|int $key key (key to search in)
* @param string|int $value value (what to find)
* @param bool $strict [false], if set to true, will strict check key/value
* @return bool true on found, false on not found
*/
public static function arraySearchSimple(
array $array,
string|int $key,
string|int|bool $value,
bool $strict = false
): bool {
public static function arraySearchSimple(array $array, $key, $value, bool $strict = false): bool
{
if (!is_array($array)) {
$array = [];
}
foreach ($array as $_key => $_value) {
// if value is an array, we search
if (is_array($_value)) {
@@ -186,9 +189,9 @@ class ArrayHandler
* bool key flag: true: handle keys as string or int
* default false: all keys are string
*
* @return array<mixed>|false merged array
* @return array<mixed>|bool merged array
*/
public static function arrayMergeRecursive(): array|false
public static function arrayMergeRecursive()
{
// croak on not enough arguemnts (we need at least two)
if (func_num_args() < 2) {
@@ -261,10 +264,10 @@ class ArrayHandler
* @param array<mixed> $needle elements to search for
* @param array<mixed> $haystack array where the $needle elements should
* be searched int
* @return array<mixed>|false either the found elements or
* @return array<mixed>|bool either the found elements or
* false for nothing found or error
*/
public static function inArrayAny(array $needle, array $haystack): array|false
public static function inArrayAny(array $needle, array $haystack)
{
$found = [];
foreach ($needle as $element) {
@@ -288,12 +291,8 @@ class ArrayHandler
* @param bool $set_only flag to return all (default), or set only
* @return array<mixed> associative array
*/
public static function genAssocArray(
array $db_array,
string|int|bool $key,
string|int|bool $value,
bool $set_only = false
): array {
public static function genAssocArray(array $db_array, $key, $value, bool $set_only = false): array
{
$ret_array = [];
// do this to only run count once
for ($i = 0, $iMax = count($db_array); $i < $iMax; $i++) {
@@ -386,8 +385,11 @@ class ArrayHandler
* and will be pushed up
* @return array<mixed> modified, flattened array
*/
public static function arrayFlatForKey(array $array, string|int $search): array
public static function arrayFlatForKey(array $array, $search): array
{
if (!is_array($array)) {
$array = [];
}
foreach ($array as $key => $value) {
// if it is not an array do just nothing
if (!is_array($value)) {

View File

@@ -74,7 +74,7 @@ class DateTime
* @return string formated date+time in Y-M-D h:m:s ms
*/
public static function dateStringFormat(
int|float $timestamp,
$timestamp,
bool $show_micro = false,
bool $micro_as_float = false
): string {
@@ -100,10 +100,8 @@ class DateTime
* @param bool $show_micro show micro seconds, default true
* @return string interval formatted string or string as is
*/
public static function timeStringFormat(
string|int|float $timestamp,
bool $show_micro = true
): string {
public static function timeStringFormat($timestamp, bool $show_micro = true): string
{
// check if the timestamp has any h/m/s/ms inside, if yes skip
if (!preg_match("/(h|m|s|ms)/", (string)$timestamp)) {
list($timestamp, $ms) = array_pad(explode('.', (string)round((float)$timestamp, 4)), 2, null);
@@ -159,7 +157,7 @@ class DateTime
* @param string|int|float $timestring formatted interval
* @return string|int|float converted float interval, or string as is
*/
public static function stringToTime(string|int|float $timestring): string|int|float
public static function stringToTime($timestring)
{
$timestamp = 0;
if (preg_match("/(d|h|m|s|ms)/", (string)$timestring)) {
@@ -249,9 +247,9 @@ class DateTime
* @param string $date a date string in the format YYYY-MM-DD
* @return bool true if valid date, false if date not valid
*/
public static function checkDate(string $date): bool
public static function checkDate($date): bool
{
if (empty($date)) {
if (!$date) {
return false;
}
list ($year, $month, $day) = array_pad(
@@ -326,7 +324,7 @@ class DateTime
* @return int|bool false on error
* or int -1 (s<e)/0 (s=e)/1 (s>e) as difference
*/
public static function compareDate(string $start_date, string $end_date): int|bool
public static function compareDate($start_date, $end_date)
{
// pre check for empty or wrong
if ($start_date == '--' || $end_date == '--' || !$start_date || !$end_date) {
@@ -369,7 +367,7 @@ class DateTime
* @return int|bool false for error
* or -1 (s<e)/0 (s=e)/1 (s>e) as difference
*/
public static function compareDateTime(string $start_datetime, string $end_datetime): int|bool
public static function compareDateTime($start_datetime, $end_datetime)
{
// pre check for empty or wrong
if ($start_datetime == '--' || $end_datetime == '--' || !$start_datetime || !$end_datetime) {
@@ -404,11 +402,8 @@ class DateTime
* @param bool $return_named return array type, false (default), true for named
* @return array<mixed> 0/overall, 1/weekday, 2/weekend
*/
public static function calcDaysInterval(
string $start_date,
string $end_date,
bool $return_named = false
): array {
public static function calcDaysInterval($start_date, $end_date, bool $return_named = false): array
{
// pos 0 all, pos 1 weekday, pos 2 weekend
$days = [];
// if anything invalid, return 0,0,0

View File

@@ -39,7 +39,7 @@ class Byte
* @return string converted byte number (float) with suffix
* @throws \Exception 1: no valid flag set
*/
public static function humanReadableByteFormat(string|int|float $bytes, int $flags = 0): string
public static function humanReadableByteFormat($bytes, int $flags = 0): string
{
// if not numeric, return as is
if (is_numeric($bytes)) {
@@ -121,7 +121,7 @@ class Byte
* @return string|int|float converted value or original value
* @throws \Exception 1: no valid flag set
*/
public static function stringByteFormat(string|int|float $number, int $flags = 0): string|int|float
public static function stringByteFormat($number, int $flags = 0)
{
// use SI 1000 mod and not 1024 mod
if ($flags & self::BYTE_FORMAT_SI) {

View File

@@ -31,12 +31,8 @@ class Colors
* @return string|bool rgb in hex values with leading # if set,
* false for invalid color
*/
public static function rgb2hex(
int $red,
int $green,
int $blue,
bool $hex_prefix = true
): string|bool {
public static function rgb2hex(int $red, int $green, int $blue, bool $hex_prefix = true)
{
$hex_color = '';
if ($hex_prefix === true) {
$hex_color = '#';
@@ -65,7 +61,7 @@ class Colors
string $hexStr,
bool $return_as_string = false,
string $seperator = ','
): string|array|bool {
) {
$hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string
if (!is_string($hexStr)) {
return false;
@@ -103,7 +99,7 @@ class Colors
* @return array<int|float>|bool Hue, Sat, Brightness/Value
* false for input value error
*/
public static function rgb2hsb(int $red, int $green, int $blue): array|bool
public static function rgb2hsb(int $red, int $green, int $blue)
{
// check that rgb is from 0 to 255
foreach (['red', 'green', 'blue'] as $c) {
@@ -150,7 +146,7 @@ class Colors
* @return array<int>|bool 0 red/1 green/2 blue array as 0-255
* false for input value error
*/
public static function hsb2rgb(float $H, float $S, float $V): array|bool
public static function hsb2rgb(float $H, float $S, float $V)
{
// check that H is 0 to 359, 360 = 0
// and S and V are 0 to 1
@@ -236,7 +232,7 @@ class Colors
* @return array<float>|bool hue/sat/luminance
* false for input value error
*/
public static function rgb2hsl(int $red, int $green, int $blue): array|bool
public static function rgb2hsl(int $red, int $green, int $blue)
{
// check that rgb is from 0 to 255
foreach (['red', 'green', 'blue'] as $c) {
@@ -289,8 +285,11 @@ class Colors
* @param float $lum luminance: 0-100
* @return array<int,float|int>|bool red/blue/green 0-255 each
*/
public static function hsl2rgb(float $hue, float $sat, float $lum): array|bool
public static function hsl2rgb(float $hue, float $sat, float $lum)
{
if (!is_numeric($hue)) {
return false;
}
if ($hue == 360) {
$hue = 0;
}

View File

@@ -19,7 +19,7 @@ class Html
* @param mixed $string string to html encode
* @return mixed if string, encoded, else as is (eg null)
*/
public static function htmlent(mixed $string): mixed
public static function htmlent($string)
{
if (is_string($string)) {
return htmlentities($string, ENT_COMPAT | ENT_HTML401, 'UTF-8', false);
@@ -52,7 +52,7 @@ class Html
* @return ?string returns checked or selected,
* else returns null
*/
public static function checked(array|string $haystack, string $needle, int $type = 0): ?string
public static function checked($haystack, string $needle, int $type = 0): ?string
{
if (is_array($haystack)) {
if (in_array($needle, $haystack)) {

View File

@@ -51,13 +51,13 @@ class Json
/**
* returns human readable string for json errors thrown in jsonConvertToArray
*
* @param bool $return_string [default=false] if set to true
* it will return the message string and not
* the error number
* @return int|string Either error number (0 for no error)
* or error string ('' for no error)
* @param bool|boolean $return_string [default=false] if set to true
* it will return the message string and not
* the error number
* @return int|string Either error number (0 for no error)
* or error string ('' for no error)
*/
public static function jsonGetLastError(bool $return_string = false): int|string
public static function jsonGetLastError(bool $return_string = false)
{
$json_error_string = '';
// valid errors as of php 8.0

View File

@@ -48,7 +48,7 @@ class Math
* @param string|int|float $number string or number to check
* @return float if not number, then returns 0, else original input
*/
public static function initNumeric(string|int|float $number): float
public static function initNumeric($number): float
{
if (!is_numeric($number)) {
return 0;

View File

@@ -32,7 +32,7 @@ class RandomKey
*
* @return void has no return
*/
private static function initRandomKeyData(): void
private static function initRandomKeyData()
{
// random key generation base string
self::$key_range = join('', array_merge(
@@ -52,6 +52,7 @@ class RandomKey
private static function validateRandomKeyLenght(int $key_length): bool
{
if (
is_numeric($key_length) &&
$key_length > 0 &&
$key_length <= self::$max_key_length
) {

View File

@@ -18,19 +18,6 @@ class Session
/** @var string list for errors */
private $session_intern_error_str = '';
/**
* init a session, if array is empty or array does not have session_name set
* then no auto init is run
*
* @param string $session_name if set and not empty, will start session
*/
public function __construct(string $session_name = '')
{
if (!empty($session_name)) {
$this->startSession($session_name);
}
}
/**
* Start session
* startSession should be called for complete check
@@ -44,6 +31,19 @@ class Session
session_start();
}
/**
* init a session, if array is empty or array does not have session_name set
* then no auto init is run
*
* @param string $session_name if set and not empty, will start session
*/
public function __construct(string $session_name = '')
{
if (!empty($session_name)) {
$this->startSession($session_name);
}
}
/**
* check if we are in CLI, we set this, so we can mock this
* Not this is just a wrapper for the static System::checkCLI call
@@ -116,7 +116,7 @@ class Session
* @param string|null $session_name
* @return string|bool
*/
public function startSession(?string $session_name = null): string|bool
public function startSession(?string $session_name = null)
{
// we can't start sessions on command line
if ($this->checkCliStatus()) {
@@ -163,7 +163,7 @@ class Session
*
* @return string|bool
*/
public function getSessionId(): string|bool
public function getSessionId()
{
return session_id();
}
@@ -173,7 +173,7 @@ class Session
*
* @return string|bool
*/
public function getSessionName(): string|bool
public function getSessionName()
{
return session_name();
}
@@ -275,7 +275,7 @@ class Session
* @param mixed $value value to set (can be anything)
* @return void
*/
public function setS(string|int $name, mixed $value): void
public function setS($name, $value): void
{
$_SESSION[$name] = $value;
}
@@ -286,7 +286,7 @@ class Session
* @param string|int $name value key to get from _SESSION
* @return mixed value stored in _SESSION
*/
public function getS(string|int $name): mixed
public function getS($name)
{
return $_SESSION[$name] ?? '';
}
@@ -297,7 +297,7 @@ class Session
* @param string|int $name Name to check for
* @return bool True for set, False fornot set
*/
public function issetS(string|int $name): bool
public function issetS($name): bool
{
return isset($_SESSION[$name]);
}
@@ -308,7 +308,7 @@ class Session
* @param string|int $name _SESSION key name to remove
* @return void
*/
public function unsetS(string|int $name): void
public function unsetS($name): void
{
if (isset($_SESSION[$name])) {
unset($_SESSION[$name]);
@@ -325,7 +325,7 @@ class Session
* @param mixed $value
* @return void
*/
public function __set(string|int $name, mixed $value): void
public function __set($name, $value): void
{
$_SESSION[$name] = $value;
}
@@ -334,14 +334,14 @@ class Session
* Undocumented function
*
* @param string|int $name
* @return mixed If name is not found, it will return null
* @return mixed
*/
public function __get(string|int $name): mixed
public function __get($name)
{
if (isset($_SESSION[$name])) {
return $_SESSION[$name];
}
return null;
return [];
}
/**
@@ -350,7 +350,7 @@ class Session
* @param string|int $name
* @return bool
*/
public function __isset(string|int $name): bool
public function __isset($name): bool
{
return isset($_SESSION[$name]);
}
@@ -361,7 +361,7 @@ class Session
* @param string|int $name
* @return void
*/
public function __unset(string|int $name): void
public function __unset($name): void
{
if (isset($_SESSION[$name])) {
unset($_SESSION[$name]);

View File

@@ -137,7 +137,7 @@ class ArrayIO extends \CoreLibs\DB\IO
* @param string $text any html encoded string
* @return string decoded html string
*/
public function convertData(string $text): string
public function convertData($text): string
{
$text = str_replace('&lt;b&gt;', '<b>', $text);
$text = str_replace('&lt;/b&gt;', '</b>', $text);
@@ -156,7 +156,7 @@ class ArrayIO extends \CoreLibs\DB\IO
* @param string $text encoded html string
* @return string decoded html string
*/
public function convertEntities(string $text): string
public function convertEntities($text): string
{
$text = str_replace('&lt;', '<', $text);
$text = str_replace('&gt;', '>', $text);
@@ -172,7 +172,7 @@ class ArrayIO extends \CoreLibs\DB\IO
* @param bool $write write to error message, default false
* @return string the array data as html string entry
*/
public function dbDumpArray(bool $write = false): string
public function dbDumpArray($write = false): string
{
reset($this->table_array);
$string = '';
@@ -192,7 +192,7 @@ class ArrayIO extends \CoreLibs\DB\IO
*
* @return bool true if pk value is set, else false
*/
public function dbCheckPkSet(): bool
public function dbCheckPkSet()
{
// if pk_id is set, overrule ...
if ($this->pk_id) {
@@ -210,10 +210,10 @@ class ArrayIO extends \CoreLibs\DB\IO
/**
* resets the whole array values
* @param bool $reset_pk true if we want to reset the pk too
* @param boolean $reset_pk true if we want to reset the pk too
* @return void has no return
*/
public function dbResetArray(bool $reset_pk = false): void
public function dbResetArray($reset_pk = false): void
{
reset($this->table_array);
foreach (array_keys($this->table_array) as $column) {
@@ -230,10 +230,10 @@ class ArrayIO extends \CoreLibs\DB\IO
*
* @param array<mixed> $table_array optional override for table array set
* set this as new table array too
* @param bool $acl_limit [false], if set to true, well do ACL limit check
* @param boolean $acl_limit [false], if set to true, well do ACL limit check
* @return array<mixed> returns the table array that was deleted
*/
public function dbDelete(array $table_array = [], bool $acl_limit = false): array
public function dbDelete($table_array = [], $acl_limit = false)
{
// is array and has values, override set and set new
if (is_array($table_array) && count($table_array)) {
@@ -294,12 +294,12 @@ class ArrayIO extends \CoreLibs\DB\IO
/**
* reads one row into the array
*
* @param bool $edit on true convert data, else as is
* @param boolean $edit on true convert data, else as is
* @param array<mixed> $table_array optional table array, overwrites
* internal set array
* @return array<mixed> set table array with values
*/
public function dbRead(bool $edit = false, array $table_array = []): array
public function dbRead($edit = false, $table_array = [])
{
// if array give, overrules internal array
if (is_array($table_array) && count($table_array)) {
@@ -381,9 +381,9 @@ class ArrayIO extends \CoreLibs\DB\IO
/**
* writes one set into DB or updates one set (if PK exists)
*
* @param bool $addslashes old convert entities and set set escape
* @param boolean $addslashes old convert entities and set set escape
* @param array<mixed> $table_array optional table array, overwrites internal one
* @param bool $acl_limit [false], if set to true, well do ACL limit check
* @param boolean $acl_limit [false], if set to true, well do ACL limit check
* @return array<mixed> table array or null
*/
public function dbWrite(
@@ -391,7 +391,7 @@ class ArrayIO extends \CoreLibs\DB\IO
array $table_array = [],
bool $acl_limit = false
): array {
if (count($table_array)) {
if (is_array($table_array) && count($table_array)) {
$this->table_array = $table_array;
}
// PK ID check
@@ -475,12 +475,13 @@ class ArrayIO extends \CoreLibs\DB\IO
$this->table_array[$column]['type'] != 'view' &&
strlen($column) > 0 &&
// no acl limiter
($acl_limit === false ||
(
$acl_limit === false ||
// acl limit is true, min edit must be at larger than set
$acl_limit === true &&
$this->base_acl_level >=
($this->table_array[$column]['min_edit_acl'] ?? 100)
)
))
) {
// for password use hidden value if main is not set
if (
@@ -527,7 +528,7 @@ class ArrayIO extends \CoreLibs\DB\IO
}
$q_data .= $_value;
} elseif (isset($this->table_array[$column]['bool'])) {
// bool storage (reverse check on ifset)
// boolean storeage (reverse check on ifset)
$q_data .= "'" . $this->dbBoolean($this->table_array[$column]['value'], true) . "'";
} elseif (
isset($this->table_array[$column]['interval']) ||

View File

@@ -12,7 +12,7 @@
* 2013/10/10, prepare/excute were added, including auto RETURNING primary key if
* possible for any INSERT query in exec or prepare/execute, better debugging and
* data dumping. Proper string escape wrapper, special db exec writer for complex
* array inserts in auto calls. bool converter from postresql to php
* array inserts in auto calls. boolean converter from postresql to php
*
* 2003/12/08, one major change: renamed db_exec_ext to db_return, as it has not
* much in common with the normal db_exec wrapper, as it was written only for
@@ -168,7 +168,7 @@
* - all HTML from the query data (color codes, etc) via flag to debug call
*
* HISTORY:
* 2008/10/25 (cs) add db_boolean to fix the postgres to php bool var problem
* 2008/10/25 (cs) add db_boolean to fix the postgres to php boolean var problem
* (TODO: implement this in any select return)
* 2008/07/03 (cs) add db_write_data function, original written for inventory tool "invSQLWriteData"
* 2008/04/16 (cs) add db_escape_string function for correct string escape
@@ -288,7 +288,7 @@ class IO
private $query; // the query string at the moment
// only inside
// basic vars
/** @var \PgSql\Connection|false|null */ // replace object with PgSql\Connection|
/** @var object|resource|bool|int|null */ // replace object with PgSql\Connection|
private $dbh; // the dbh handler, if disconnected by command is null, bool:false/int:-1 on error,
/** @var bool */
private $db_debug = false; // DB_DEBUG ... (if set prints out debug msgs)
@@ -315,7 +315,7 @@ class IO
/** @var array<mixed,mixed> */
private $cursor_ext; // hash of hashes
// per query vars
/** @var \PgSql\Result|false */ // replace object with PgSql\Result
/** @var object|resource|bool */ // replace object with PgSql\Result
private $cursor; // actual cursor (DBH)
/** @var int */
private $num_rows; // how many rows have been found
@@ -495,15 +495,15 @@ class IO
* OTOH this whole class is so PgSQL specific
* that non PgSQL doesn't make much sense anymore
*
* @return SQL\PgSQL|null DB functions object or false on error
* @return \CoreLibs\DB\SQL\PgSQL|null DB functions object or false on error
*/
private function __loadDBFunctions(): SQL\PgSQL|null
private function __loadDBFunctions()
{
$db_functions = null;
switch ($this->db_type) {
// list of valid DB function objects
case 'pgsql':
$db_functions = new SQL\PgSQL();
$db_functions = new \CoreLibs\DB\SQL\PgSQL();
break;
// if non set or none matching abort
default:
@@ -566,7 +566,7 @@ class IO
*/
private function __closeDB(): void
{
if (!empty($this->dbh)) {
if (!empty($this->dbh) && $this->dbh !== false) {
$this->db_functions->__dbClose();
$this->dbh = null;
}
@@ -632,6 +632,9 @@ class IO
private function __printArray(array $array): string
{
$string = '';
if (!is_array($array)) {
$array = [];
}
foreach ($array as $key => $value) {
$string .= $this->nbsp . '<b>' . $key . '</b> => ';
if (is_array($value)) {
@@ -698,7 +701,7 @@ class IO
/**
* Check if there is a cursor and write this cursors error info
* @param \PgSql\Result|false $cursor current cursor for pg_result_error,
* @param object|resource|bool $cursor current cursor for pg_result_error,
* pg_last_error too, but pg_result_error
* is more accurate (PgSql\Result)
* @return array<mixed> Pos 0: if we could get the method where it was called
@@ -706,7 +709,7 @@ class IO
* Pos 1: if we have the pg_error_string from last error
* if nothing then empty string
*/
private function __dbErrorPreprocessor(\PgSql\Result|false $cursor = false): array
private function __dbErrorPreprocessor($cursor = false): array
{
$pg_error_string = '';
// 1 = self/__dbErrorPreprocessor, 2 = __dbError, __dbWarning,
@@ -771,15 +774,12 @@ class IO
/**
* write an error
* @param integer $error_id Any Error ID, used in debug message string
* @param \PgSql\Result|false $cursor Optional cursor, passed on to preprocessor
* @param object|resource|bool $cursor Optional cursor, passed on to preprocessor
* @param string $msg optional message added to debug
* @return void
*/
protected function __dbError(
int $error_id,
\PgSql\Result|false $cursor = false,
string $msg = ''
): void {
protected function __dbError(int $error_id, $cursor = false, string $msg = ''): void
{
$error_id = (string)$error_id;
[$where_called, $pg_error_string] = $this->__dbErrorPreprocessor($cursor);
// write error msg ...
@@ -798,15 +798,12 @@ class IO
/**
* write a warning
* @param integer $warning_id Integer warning id added to debug
* @param \PgSql\Result|false $cursor Optional cursor, passed on to preprocessor
* @param object|resource|bool $cursor Optional cursor, passed on to preprocessor
* @param string $msg optional message added to debug
* @return void
*/
protected function __dbWarning(
int $warning_id,
\PgSql\Result|false $cursor = false,
string $msg = ''
): void {
protected function __dbWarning(int $warning_id, $cursor = false, string $msg = ''): void
{
$warning_id = (string)$warning_id;
[$where_called, $pg_error_string] = $this->__dbErrorPreprocessor($cursor);
$this->__dbDebug(
@@ -824,18 +821,18 @@ class IO
/**
* if there is the 'to_encoding' var set,
* and the field is in the wrong encoding converts it to the target
* @param array<mixed>|false $row Array from fetch_row
* @return array<mixed>|false Convert fetch_row array, or false
* @param array<mixed>|bool|null $row Array from fetch_row
* @return array<mixed>|bool Convert fetch_row array, or false
*/
private function __dbConvertEncoding(array|false $row): array|false
private function __dbConvertEncoding($row)
{
if (is_bool($row)) {
if ($row === null) {
return false;
}
// only do if array, else pass through row (can be false)
if (
!is_array($row) ||
empty($this->to_encoding)
empty($this->to_encoding)// || empty($this->db_encoding)
) {
return $row;
}
@@ -917,7 +914,7 @@ class IO
* check if there is another query running, or do we hang after a
* PHP error
* @param integer $timeout_seconds For complex timeout waits, default 3 seconds
* @return bool True for connection OK, else false
* @return boolean True for connection OK, else false
*/
private function __dbCheckConnectionOk(int $timeout_seconds = 3): bool
{
@@ -935,7 +932,7 @@ class IO
* dbReturn
* Read data from previous written data cache
* @param string $query_hash The hash for the current query
* @param bool $assoc_only Only return assoc value (key named)
* @param boolean $assoc_only Only return assoc value (key named)
* @return array<mixed> Current position query data from cache
*/
private function __dbReturnCacheRead(string $query_hash, bool $assoc_only): array
@@ -986,11 +983,10 @@ class IO
* - sets internal hash for query
* - checks multiple call count
* @param string $query query string
* @param string $pk_name primary key
* [if set to NULL no returning will be added]
* @return string|false queryt hash OR bool false on error
* @param string $pk_name primary key [if set to NULL no returning will be added]
* @return string|bool queryt hash OR boolean false on error
*/
private function __dbPrepareExec(string $query, string $pk_name): string|false
private function __dbPrepareExec(string $query, string $pk_name)
{
// reset current cursor before exec
$this->cursor = false;
@@ -1156,10 +1152,10 @@ class IO
* insert_id_ext [DEPRECATED, all in insert_id_arr]
* - holds all returning as array
* TODO: Only use insert_id_arr and use functions to get ok array or single
* @param bool $returning_id
* @param boolean $returning_id
* @param string $query
* @param string|null $pk_name
* @param \PgSql\Result|false $cursor (PgSql\Result)
* @param object|resource|bool $cursor (PgSql\Result)
* @param string|null $stm_name If not null, is dbExecutre run
* @return void
*/
@@ -1167,7 +1163,7 @@ class IO
bool $returning_id,
string $query,
?string $pk_name,
\PgSql\Result|false $cursor,
$cursor,
?string $stm_name = null
): void {
// $this->log->debug('DB SET INSERT ID', 'Ret: ' . ($returning_id ? 'Y' : 'N')
@@ -1275,10 +1271,10 @@ class IO
/**
* get certain settings like username, db name
* @param string $name what setting to query
* @return int|string|bool setting value, if not allowed name return false
* @param string $name what setting to query
* @return mixed setting value, if not allowed name return false
*/
public function dbGetSetting(string $name): int|string|bool
public function dbGetSetting(string $name)
{
$setting = '';
switch ($name) {
@@ -1377,7 +1373,7 @@ class IO
* extended version info, can access all additional information data
* @param string $parameter Array parameter name, if not valid returns
* empty string
* @param bool $strip Strip extended server info string, default true
* @param boolean $strip Strip extended server info string, default true
* eg nn.n (other info) will only return nn.n
* @return string Parameter value
*/
@@ -1396,15 +1392,14 @@ class IO
}
/**
* returns bool true or false if the string matches the database version
* returns boolean true or false if the string matches the database version
* @param string $compare string to match in type =X.Y, >X.Y, <X.Y, <=X.Y, >=X.Y
* @return bool true for ok, false on not ok
*/
public function dbCompareVersion(string $compare): bool
{
$matches = [];
// compare has =, >, < prefix, and gets stripped
// if the rest is not X.Y format then error
// compare has =, >, < prefix, and gets stripped, if the rest is not X.Y format then error
preg_match("/^([<>=]{1,})(\d{1,})\.(\d{1,})/", $compare, $matches);
$compare = $matches[1];
$to_master = $matches[2];
@@ -1469,7 +1464,7 @@ class IO
* else current cursor
* @return string Formated string with all the data in the array
*/
public function dbDumpData(string $query = ''): string
public function dbDumpData($query = ''): string
{
// set start array
if ($query) {
@@ -1495,7 +1490,7 @@ class IO
* @param string|int|float|bool $string string to escape
* @return string escaped string
*/
public function dbEscapeString(string|int|float|bool $string): string
public function dbEscapeString($string): string
{
return $this->db_functions->__dbEscapeString($string);
}
@@ -1506,7 +1501,7 @@ class IO
* @param string|int|float|bool $string string to escape
* @return string escaped string
*/
public function dbEscapeLiteral(string|int|float|bool $string): string
public function dbEscapeLiteral($string): string
{
return $this->db_functions->__dbEscapeLiteral($string);
}
@@ -1543,11 +1538,11 @@ class IO
/**
* clear up any data for valid DB insert
* @param int|float|string|bool|null $value to escape data
* @param string $kbn escape trigger type
* @return string escaped value
* @param int|float|string|null $value to escape data
* @param string $kbn escape trigger type
* @return string escaped value
*/
public function dbSqlEscape(int|float|string|bool|null $value, string $kbn = ''): string
public function dbSqlEscape($value, string $kbn = '')
{
switch ($kbn) {
case 'i':
@@ -1556,35 +1551,24 @@ class IO
case 'f':
$value = empty($value) ? 'NULL' : floatval($value);
break;
// string (null is null, else is string)
case 't':
$value = $value === null ?
'NULL' :
"'" . $this->dbEscapeString($value) . "'";
break;
// string litereal (null is null, else is stirng)
case 'tl':
$value = $value === null ?
'NULL' :
$this->dbEscapeLiteral($value);
break;
// escape string, set empty to null
// what is d?
case 'd':
$value = empty($value) ?
'NULL' :
"'" . $this->dbEscapeString($value) . "'";
break;
// escape string literal, set empty to null
case 'dl':
$value = empty($value) ?
'NULL' :
$this->dbEscapeLiteral($value);
$value = empty($value) ? 'NULL' : "'" . $this->dbEscapeString($value) . "'";
break;
// bytea data
case 'by':
$value = empty($value) ? 'NULL' : $this->dbEscapeBytea((string)$value);
break;
// bool
case 'b':
if (is_float($value)) {
$value = (int)$value;
@@ -1593,7 +1577,6 @@ class IO
'NULL' :
"'" . $this->dbBoolean($value, true) . "'";
break;
// int, but with empty value is 0
case 'i2':
$value = empty($value) ? 0 : intval($value);
break;
@@ -1607,14 +1590,14 @@ class IO
/**
* if the input is a single char 't' or 'f
* it will return the bool value instead
* it will return the boolean value instead
* also converts smallint 1/0 to true false
* @param string|bool|int $string 't' / 'f' or any string, or bool true/false
* @param bool $rev do reverse (bool to string)
* @return bool|string correct php bool true/false
* @param boolean $rev do reverse (bool to string)
* @return bool|string correct php boolean true/false
* or postgresql 't'/'f'
*/
public function dbBoolean(string|bool|int $string, bool $rev = false): bool|string
public function dbBoolean($string, $rev = false)
{
if (!$rev) {
if ($string == 't' || $string == 'true') {
@@ -1713,9 +1696,9 @@ class IO
* returns an array of the table with columns and values. FALSE on no table found
* @param string $table table name
* @param string $schema optional schema name
* @return array<mixed>|false array of table data, false on error (table not found)
* @return array<mixed>|bool array of table data, false on error (table not found)
*/
public function dbShowTableMetaData(string $table, string $schema = ''): array|false
public function dbShowTableMetaData(string $table, string $schema = '')
{
$this->__dbErrorReset();
$table = (!empty($schema) ? $schema . '.' : '') . $table;
@@ -1753,14 +1736,14 @@ class IO
* NO_CACHE/3: don't write cache
* @param bool $assoc_only True to only returned the named and not
* index position ones
* @return array<mixed>|false return array data or false on error/end
* @return array<mixed>|bool return array data or false on error/end
* @#suppress PhanTypeMismatchDimFetch
*/
public function dbReturn(
string $query,
int $cache = self::USE_CACHE,
bool $assoc_only = false
): array|false {
) {
$this->__dbErrorReset();
if (!$query) {
$this->__dbError(11);
@@ -1771,7 +1754,7 @@ class IO
// pre declare array
if (!isset($this->cursor_ext[$query_hash])) {
$this->cursor_ext[$query_hash] = [
// cursor, null: unset, 1: finished read/cache, 2: object reading
// cursor, null: unset, 1: finished read/cache, 2: object/resource reading
'cursor' => null,
// cached data
'data' => [],
@@ -2017,9 +2000,9 @@ class IO
* if pk name is table name and _id, pk_name
* is not needed to be set
* if NULL is given here, no RETURNING will be auto added
* @return \PgSql\Result|false cursor for this query or false on error
* @return object|resource|bool cursor for this query or false on error (PgSql\Result)
*/
public function dbExec(string $query = '', string $pk_name = ''): \PgSql\Result|false
public function dbExec(string $query = '', string $pk_name = '')
{
$this->__dbErrorReset();
// prepare and check if we can actually run it
@@ -2048,7 +2031,7 @@ class IO
/**
* executes a cursor and returns the data, if no more data 0 will be returned
* @param \PgSql\Result|false $cursor the cursor from db_exec or
* @param object|resource|bool $cursor the cursor from db_exec or
* pg_query/pg_exec/mysql_query
* if not set will use internal cursor,
* if not found, stops with 0 (error)
@@ -2056,9 +2039,9 @@ class IO
* @param bool $assoc_only false is default,
* if true only named rows,
* not numbered index rows
* @return array<mixed>|false row array or false on error
* @return array<mixed>|bool row array or false on error
*/
public function dbFetchArray(\PgSql\Result|false $cursor = false, bool $assoc_only = false): array|false
public function dbFetchArray($cursor = false, bool $assoc_only = false)
{
$this->__dbErrorReset();
// set last available cursor if none set or false
@@ -2081,9 +2064,9 @@ class IO
* returns the FIRST row of the given query
* @param string $query the query to be executed
* @param bool $assoc_only if true, only return assoc entry (default false)
* @return array<mixed>|false row array or false on error
* @return array<mixed>|bool row array or false on error
*/
public function dbReturnRow(string $query, bool $assoc_only = false): array|false
public function dbReturnRow(string $query, bool $assoc_only = false)
{
$this->__dbErrorReset();
if (!$query) {
@@ -2108,9 +2091,9 @@ class IO
* createds an array of hashes of the query (all data)
* @param string $query the query to be executed
* @param bool $assoc_only if true, only name ref are returned (default true)
* @return array<mixed>|false array of hashes (row -> fields), false on error
* @return array<mixed>|bool array of hashes (row -> fields), false on error
*/
public function dbReturnArray(string $query, bool $assoc_only = true): array|false
public function dbReturnArray(string $query, bool $assoc_only = true)
{
$this->__dbErrorReset();
if (!$query) {
@@ -2168,44 +2151,41 @@ class IO
* returns the full array for cursor ext
* or cursor for one query
* or detail data fonr one query cursor data
* @param string|null $query Query string, if not null convert to hash
* and return set cursor ext for only this
* if not found or null return null
* @param string $query_field [=''] optional query field to get
* @return array<mixed>|string|int|\PgSql\Result|null
* Cursor Extended array full if no parameter
* Key is hash string from query run
* Or cursor data entry if query field is set
* If nothing found return null
* @param string|null $query Query string, if not null convert to hash
* and return set cursor ext for only this
* if not found or null return null
* @return array<mixed>|string|int|resource|object|null
* Cursor Extended array full if no parameter
* Key is hash string from query run
* Or cursor data entry if query field is set
* If nothing found return null
*/
public function dbGetCursorExt(
$query = null,
string $query_field = ''
): array|string|int|\PgSql\Result|null {
if ($query === null) {
return $this->cursor_ext;
}
$query_hash = $this->dbGetQueryHash($query);
if (
is_array($this->cursor_ext) &&
isset($this->cursor_ext[$query_hash])
) {
if (empty($query_field)) {
return $this->cursor_ext[$query_hash];
public function dbGetCursorExt($query = null, string $query_field = '')
{
if ($query !== null) {
$query_hash = $this->dbGetQueryHash($query);
if (
is_array($this->cursor_ext) &&
isset($this->cursor_ext[$query_hash])
) {
if (empty($query_field)) {
return $this->cursor_ext[$query_hash];
} else {
return $this->cursor_ext[$query_hash][$query_field] ?? null;
}
} else {
return $this->cursor_ext[$query_hash][$query_field] ?? null;
return null;
}
} else {
return null;
}
return $this->cursor_ext;
}
/**
* returns the current position the read out
* @param string $query query to find in cursor_ext
* @return int|false query position (row pos), false on error
* @return int|bool query position (row pos), false on error
*/
public function dbGetCursorPos(string $query): int|false
public function dbGetCursorPos(string $query)
{
$this->__dbErrorReset();
if (!$query) {
@@ -2219,9 +2199,9 @@ class IO
/**
* returns the number of rows for the current select query
* @param string $query query to find in cursor_ext
* @return int|false query position (row pos), false on error
* @return int|bool query position (row pos), false on error
*/
public function dbGetCursorNumRows(string $query): int|false
public function dbGetCursorNumRows(string $query)
{
$this->__dbErrorReset();
if (!$query) {
@@ -2273,14 +2253,11 @@ class IO
* @param string $stm_name statement name
* @param string $query queryt string to run
* @param string $pk_name optional primary key
* @return \PgSql\Result|bool false on error, true on warning or
* result on full ok
* @return bool|object|resource false on error, true on warning or
* result on full ok (PgSql\Result)
*/
public function dbPrepare(
string $stm_name,
string $query,
string $pk_name = ''
): \PgSql\Result|bool {
public function dbPrepare(string $stm_name, string $query, string $pk_name = '')
{
$this->__dbErrorReset();
$matches = [];
if (!$query) {
@@ -2384,9 +2361,9 @@ class IO
* runs a prepare query
* @param string $stm_name statement name for the query to run
* @param array<mixed> $data data to run for this query, empty array for none
* @return \PgSql\Result|false false on error, or result on OK
* @return mixed false on error, or result on OK
*/
public function dbExecute(string $stm_name, array $data = []): \PgSql\Result|false
public function dbExecute(string $stm_name, array $data = [])
{
$this->__dbErrorReset();
// if no DB Handler drop out
@@ -2506,10 +2483,11 @@ class IO
/**
* checks a previous async query and returns data if finished
* NEEDS : dbExecAsync
* @return \PgSql\Result|bool cursor resource if the query is still running,
* false if an error occured or cursor of that query
* @return bool|object|resource cursor resource if the query is still running,
* false if an error occured or cursor of that query
* (PgSql\Result)
*/
public function dbCheckAsync(): \PgSql\Result|bool
public function dbCheckAsync()
{
$this->__dbErrorReset();
// if there is actually a async query there
@@ -2569,7 +2547,7 @@ class IO
* @param int $primary_key id key to decide if we write insert or update
* @param string $table name for the target table
* @param array<mixed> $data data array to override _POST data
* @return int|false primary key
* @return int|bool primary key
*/
public function dbWriteData(
array $write_array,
@@ -2577,7 +2555,13 @@ class IO
int $primary_key,
string $table,
array $data = []
): int|false {
) {
if (!is_array($write_array)) {
$write_array = [];
}
if (!is_array($not_write_array)) {
$not_write_array = [];
}
$not_write_update_array = [];
return $this->dbWriteDataExt(
$write_array,
@@ -2602,16 +2586,16 @@ class IO
* to write during update (optional)
* @param array<mixed> $data optional array with data
* if not _POST vars are used
* @return int|false primary key
* @return int|bool primary key
*/
public function dbWriteDataExt(
array $write_array,
int|string|array $primary_key,
$primary_key,
string $table,
array $not_write_array = [],
array $not_write_update_array = [],
array $data = []
): int|false {
) {
if (!is_array($primary_key)) {
$primary_key = [
'row' => $table . '_id',
@@ -2727,10 +2711,7 @@ class IO
$primary_key['value'] = $this->dbGetInsertPK();
}
// if there is not priamry key value field return false
if (!is_numeric($primary_key['value'])) {
return false;
}
return (int)$primary_key['value'];
return $primary_key['value'] ?? false;
}
// ***************************
@@ -2743,7 +2724,7 @@ class IO
* @param bool|null $debug true/false or null for just getting current set
* @return bool Current debug flag as set
*/
public function dbSetDebug(?bool $debug = null): bool
public function dbSetDebug($debug = null): bool
{
if ($debug !== null) {
$this->db_debug = $debug;
@@ -2824,7 +2805,7 @@ class IO
* @return bool False on failure to find schema value or set schema,
* True on successful set
*/
public function dbSetSchema(string $db_schema): bool
public function dbSetSchema(string $db_schema)
{
$this->__dbErrorReset();
if (empty($db_schema)) {
@@ -2953,9 +2934,9 @@ class IO
/**
* Return current database handler
* @return \PgSql\Connection|false|null
* @return object|resource|bool|int|null
*/
public function dbGetDbh(): \PgSql\Connection|false|null
public function dbGetDbh()
{
return $this->dbh;
}
@@ -3011,7 +2992,7 @@ class IO
*
* @return array<mixed>|string|int|null Current insert query primary key
*/
public function dbGetInsertPK(): array|string|int|null
public function dbGetInsertPK()
{
if (empty($this->insert_id_pk_name)) {
return null;
@@ -3035,7 +3016,7 @@ class IO
* @param integer|null $pos
* @return array<mixed>|string|int|null
*/
public function dbGetReturningExt(?string $key = null, ?int $pos = null): array|string|int|null
public function dbGetReturningExt(?string $key = null, ?int $pos = null)
{
// return as is if key is null
if ($key === null) {
@@ -3129,7 +3110,7 @@ class IO
* Not ethat returnin_id also can return false
* but will not set an error entry
*/
public function dbGetPrepareCursorValue(string $stm_name, string $key): null|string|int|bool
public function dbGetPrepareCursorValue(string $stm_name, string $key)
{
// if no statement name
if (empty($stm_name)) {
@@ -3178,8 +3159,8 @@ class IO
* Sets error number that was last
* So we always have the last error number stored even if a new
* one is created
* @param bool $transform Set to true to transform into id + error message
* @return string Last error number as string or error message
* @param boolean $transform Set to true to transform into id + error message
* @return string Last error number as string or error message
*/
public function dbGetLastError(bool $transform = false): string
{
@@ -3199,10 +3180,10 @@ class IO
/**
* Sets warning number that was last
* So we always have the last warning number stored even if a new one is created
* @param bool $transform Set to true to transform into id + warning message
* @return string Last Warning number as string or warning message
* @param boolean $transform Set to true to transform into id + warning message
* @return string Last Warning number as string or warning message
*/
public function dbGetLastWarning(bool $transform = false): string
public function dbGetLastWarning(bool $transform = false)
{
// if no warning, return empty
if (empty($this->warning_id)) {
@@ -3240,7 +3221,7 @@ class IO
* Null for error
* @deprecated Use ->dbGetInsertPK();
*/
public function dbGetReturning(): array|string|int|bool|null
public function dbGetReturning()
{
return $this->dbGetInsertPK();
}
@@ -3290,7 +3271,7 @@ class IO
* @return array<mixed>|string|int|bool|null See above
* @deprecated use getReturningExt($key = null) instead
*/
public function getInsertReturn(?string $key = null): array|string|int|bool|null
public function getInsertReturn($key = null)
{
trigger_error('Method ' . __METHOD__ . ' is deprecated, use getReturningExt($key = null)', E_USER_DEPRECATED);
return $this->dbGetReturningExt($key);
@@ -3301,7 +3282,7 @@ class IO
* @return array<mixed>|string|int|bool|null [DEPRECATED]
* @deprecated use dbGetReturning() instead
*/
public function getReturning(): array|string|int|bool|null
public function getReturning()
{
trigger_error('Method ' . __METHOD__ . ' is deprecated, use dbGetReturning()', E_USER_DEPRECATED);
return $this->dbGetInsertPK();
@@ -3312,7 +3293,7 @@ class IO
* @return array<mixed>|string|int|bool|null [DEPRECATED]
* @deprecated use dbGetInsertPK() instead
*/
public function getInsertPK(): array|string|int|bool|null
public function getInsertPK()
{
trigger_error('Method ' . __METHOD__ . ' is deprecated, use dbGetInsertPK()', E_USER_DEPRECATED);
return $this->dbGetInsertPK();
@@ -3324,7 +3305,7 @@ class IO
* @return array<mixed>|string|bool|int|null [DEPRECATED]
* @deprecated use dbGetReturningExt($key = null) instead
*/
public function getReturningExt(?string $key = null): array|string|int|bool|null
public function getReturningExt($key = null)
{
trigger_error('Method ' . __METHOD__ . ' is deprecated, use dbGetReturningExt($key = null)', E_USER_DEPRECATED);
return $this->dbGetReturningExt($key);
@@ -3333,10 +3314,10 @@ class IO
/**
* DEPRECATED: getCursorExt
* @param string|null $q [DEPRECATED]
* @return array<mixed>|string|int|\PgSql\Result|null [DEPRECATED]
* @return array<mixed>|string|int|resource|object|null [DEPRECATED]
* @deprecated use dbGetCursorExt($q = null) instead
*/
public function getCursorExt(?string $q = null): array|string|int|\PgSql\Result|null
public function getCursorExt($q = null)
{
trigger_error('Method ' . __METHOD__ . ' is deprecated, use dbGetCursorExt($q = null)', E_USER_DEPRECATED);
return $this->dbGetCursorExt($q);
@@ -3347,7 +3328,7 @@ class IO
* @return int|null [DEPRECATED]
* @deprecated use dbGetNumRows() instead
*/
public function getNumRows(): ?int
public function getNumRows()
{
trigger_error('Method ' . __METHOD__ . ' is deprecated, use dbGetNumRows()', E_USER_DEPRECATED);
return $this->dbGetNumRows();

View File

@@ -51,11 +51,12 @@ namespace CoreLibs\DB\SQL;
// as main system. Currently all @var sets are written as object
/** @#phan-file-suppress PhanUndeclaredTypeProperty,PhanUndeclaredTypeParameter,PhanUndeclaredTypeReturnType */
class PgSQL implements Interface\SqlFunctions
class PgSQL implements \CoreLibs\DB\SQL\SqlInterface\SqlFunctions
{
/** @var string */
private $last_error_query;
/** @var \PgSql\Connection|false */
// NOTE for PHP 8.1 this is no longer a resource
/** @var object|resource|bool */ // replace object with PgSql\Connection
private $dbh;
/**
@@ -76,12 +77,12 @@ class PgSQL implements Interface\SqlFunctions
* wrapper for pg_query, catches error and stores it in class var
*
* @param string $query Query string
* @return \PgSql\Result|false query result
* @return object|resource|bool query result (PgSql\Result)
*/
public function __dbQuery(string $query): \PgSql\Result|false
public function __dbQuery(string $query)
{
$this->last_error_query = '';
if (is_bool($this->dbh)) {
if ($this->dbh === false || is_bool($this->dbh)) {
return false;
}
// read out the query status and save the query if needed
@@ -99,12 +100,12 @@ class PgSQL implements Interface\SqlFunctions
*
* @param string $query Query string with placeholders $1, ..
* @param array<mixed> $params Matching parameters for each placerhold
* @return \PgSql\Result|false Query result
* @return object|resource|bool Query result (PgSql\Result)
*/
public function __dbQueryParams(string $query, array $params): \PgSql\Result|false
public function __dbQueryParams(string $query, array $params)
{
$this->last_error_query = '';
if (is_bool($this->dbh)) {
if ($this->dbh === false || is_bool($this->dbh)) {
return false;
}
// parse query and get all $n entries
@@ -125,7 +126,7 @@ class PgSQL implements Interface\SqlFunctions
*/
public function __dbSendQuery(string $query): bool
{
if (is_bool($this->dbh)) {
if ($this->dbh === false || is_bool($this->dbh)) {
return false;
}
$result = pg_send_query($this->dbh, $query);
@@ -135,12 +136,12 @@ class PgSQL implements Interface\SqlFunctions
/**
* wrapper for pg_get_result
*
* @return \PgSql\Result|false resource handler or false for error
* @return object|resource|bool resource handler or false for error (PgSql\Result)
*/
public function __dbGetResult(): \PgSql\Result|false
public function __dbGetResult()
{
$this->last_error_query = '';
if (is_bool($this->dbh)) {
if ($this->dbh === false || is_bool($this->dbh)) {
return false;
}
$result = pg_get_result($this->dbh);
@@ -160,7 +161,7 @@ class PgSQL implements Interface\SqlFunctions
*/
public function __dbClose(): void
{
if (is_bool($this->dbh)) {
if ($this->dbh === false || is_bool($this->dbh)) {
return;
}
if (pg_connection_status($this->dbh) === PGSQL_CONNECTION_OK) {
@@ -174,12 +175,12 @@ class PgSQL implements Interface\SqlFunctions
*
* @param string $name statement name
* @param string $query query string
* @return \PgSql\Result|false prepare statement handler or
* false for error
* @return object|resource|bool prepare statement handler or
* false for error (PgSql\Result)
*/
public function __dbPrepare(string $name, string $query): \PgSql\Result|false
public function __dbPrepare(string $name, string $query)
{
if (is_bool($this->dbh)) {
if ($this->dbh === false || is_bool($this->dbh)) {
return false;
}
$result = pg_prepare($this->dbh, $name, $query);
@@ -194,11 +195,11 @@ class PgSQL implements Interface\SqlFunctions
*
* @param string $name statement name
* @param array<mixed> $data data array
* @return \PgSql\Result|false returns status or false for error
* @return object|resource|bool returns status or false for error (PgSql\Result)
*/
public function __dbExecute(string $name, array $data): \PgSql\Result|false
public function __dbExecute(string $name, array $data)
{
if (is_bool($this->dbh)) {
if ($this->dbh === false || is_bool($this->dbh)) {
return false;
}
$result = pg_execute($this->dbh, $name, $data);
@@ -211,12 +212,12 @@ class PgSQL implements Interface\SqlFunctions
/**
* wrapper for pg_num_rows
*
* @param \PgSql\Result|false $cursor cursor
* @return int number of rows, -1 on error
* @param object|resource|bool $cursor cursor PgSql\Result (former resource)
* @return int number of rows, -1 on error
*/
public function __dbNumRows(\PgSql\Result|false $cursor): int
public function __dbNumRows($cursor): int
{
if (is_bool($cursor)) {
if ($cursor === false || is_bool($cursor)) {
return -1;
}
return pg_num_rows($cursor);
@@ -225,12 +226,12 @@ class PgSQL implements Interface\SqlFunctions
/**
* wrapper for pg_num_fields
*
* @param \PgSql\Result|false $cursor cursor
* @return int number for fields in result, -1 on error
* @param object|resource|bool $cursor cursor PgSql\Result (former resource)
* @return int number for fields in result, -1 on error
*/
public function __dbNumFields(\PgSql\Result|false $cursor): int
public function __dbNumFields($cursor): int
{
if (is_bool($cursor)) {
if ($cursor === false || is_bool($cursor)) {
return -1;
}
return pg_num_fields($cursor);
@@ -239,13 +240,13 @@ class PgSQL implements Interface\SqlFunctions
/**
* wrapper for pg_field_name
*
* @param \PgSql\Result|false $cursor cursor
* @param int $i field position
* @return string|false name or false on error
* @param object|resource|bool $cursor cursor PgSql\Result (former resource)
* @param int $i field position
* @return string|bool name or false on error
*/
public function __dbFieldName(\PgSql\Result|false $cursor, int $i): string|false
public function __dbFieldName($cursor, int $i)
{
if (is_bool($cursor)) {
if ($cursor === false || is_bool($cursor)) {
return false;
}
return pg_field_name($cursor, $i);
@@ -255,13 +256,13 @@ class PgSQL implements Interface\SqlFunctions
* wrapper for pg_fetch_array
* if through/true false, use __dbResultType(true)
*
* @param \PgSql\Result|false $cursor cursor
* @param int $result_type result type as int number
* @return array<mixed>|false array result data or false on end/error
* @param object|resource|bool $cursor cursor PgSql\Result (former resource)
* @param int $result_type result type as int number
* @return array<mixed>|bool array result data or false on end/error
*/
public function __dbFetchArray(\PgSql\Result|false $cursor, int $result_type = PGSQL_BOTH): array|false
public function __dbFetchArray($cursor, int $result_type = PGSQL_BOTH)
{
if (is_bool($cursor)) {
if ($cursor === false || is_bool($cursor)) {
return false;
}
// result type is passed on as is [should be checked]
@@ -286,12 +287,12 @@ class PgSQL implements Interface\SqlFunctions
/**
* wrapper for pg_fetch_all
*
* @param \PgSql\Result|false $cursor cursor
* @return array<mixed>|false data array or false for end/error
* @param object|resource|bool $cursor cursor PgSql\Result (former resource)
* @return array<mixed>|bool data array or false for end/error
*/
public function __dbFetchAll(\PgSql\Result|false $cursor): array|false
public function __dbFetchAll($cursor)
{
if (is_bool($cursor)) {
if ($cursor === false || is_bool($cursor)) {
return false;
}
return pg_fetch_all($cursor);
@@ -300,12 +301,12 @@ class PgSQL implements Interface\SqlFunctions
/**
* wrapper for pg_affected_rows
*
* @param \PgSql\Result|false $cursor cursor
* @return int affected rows, 0 for none, -1 for error
* @param object|resource|bool $cursor cursor PgSql\Result (former resource)
* @return int affected rows, 0 for none, -1 for error
*/
public function __dbAffectedRows(\PgSql\Result|false $cursor): int
public function __dbAffectedRows($cursor): int
{
if (is_bool($cursor)) {
if ($cursor === false || is_bool($cursor)) {
return -1;
}
return pg_affected_rows($cursor);
@@ -322,7 +323,7 @@ class PgSQL implements Interface\SqlFunctions
* @param string|null $pk_name primary key name, if '' then auto detect
* @return string|int|false primary key value
*/
public function __dbInsertId(string $query, ?string $pk_name): string|int|false
public function __dbInsertId(string $query, ?string $pk_name)
{
// only if an insert has been done
if (preg_match("/^insert /i", $query)) {
@@ -370,7 +371,7 @@ class PgSQL implements Interface\SqlFunctions
* @param string $schema optional schema name, '' for default
* @return string|bool primary key name or false if not found
*/
public function __dbPrimaryKey(string $table, string $schema = ''): string|bool
public function __dbPrimaryKey(string $table, string $schema = '')
{
if ($table) {
// check if schema set is different from schema given,
@@ -425,7 +426,7 @@ class PgSQL implements Interface\SqlFunctions
* @param string $db_name databse name
* @param integer $db_port port (int, 5432 is default)
* @param string $db_ssl SSL (allow is default)
* @return \PgSql\Connection|false db handler or false on error
* @return object|resource|bool db handler PgSql\Connection or false on error
*/
public function __dbConnect(
string $db_host,
@@ -434,7 +435,7 @@ class PgSQL implements Interface\SqlFunctions
string $db_name,
int $db_port,
string $db_ssl = 'allow'
): \PgSql\Connection|false {
) {
if (empty($db_name)) {
return false;
}
@@ -469,22 +470,22 @@ class PgSQL implements Interface\SqlFunctions
* reads the last error for this cursor and returns
* html formatted string with error name
*
* @param \PgSql\Result|false $cursor cursor
* @param bool|object|resource $cursor cursor PgSql\Result (former resource)
* or null
* @return string error string
*/
public function __dbPrintError(\PgSql\Result|false $cursor = false): string
public function __dbPrintError($cursor = false): string
{
if (is_bool($this->dbh)) {
if ($this->dbh === false || is_bool($this->dbh)) {
return '';
}
// run the query again for the error result here
if ((is_bool($cursor)) && $this->last_error_query) {
if (($cursor === false || is_bool($cursor)) && $this->last_error_query) {
pg_send_query($this->dbh, $this->last_error_query);
$this->last_error_query = '';
$cursor = pg_get_result($this->dbh);
}
if ($cursor && $error_str = pg_result_error($cursor)) {
if ($cursor && !is_bool($cursor) && $error_str = pg_result_error($cursor)) {
return '-PostgreSQL-Error- '
. $error_str;
} else {
@@ -499,9 +500,9 @@ class PgSQL implements Interface\SqlFunctions
* @param bool $extended show extended info (default true)
* @return array<mixed>|bool array data for the table info or false on error
*/
public function __dbMetaData(string $table, bool $extended = true): array|bool
public function __dbMetaData(string $table, $extended = true)
{
if (is_bool($this->dbh)) {
if ($this->dbh === false || is_bool($this->dbh)) {
return false;
}
// needs to prefixed with @ or it throws a warning on not existing table
@@ -514,9 +515,9 @@ class PgSQL implements Interface\SqlFunctions
* @param string|int|float|bool $string any string/int/float/bool
* @return string excaped string
*/
public function __dbEscapeString(string|int|float|bool $string): string
public function __dbEscapeString($string): string
{
if (is_bool($this->dbh)) {
if ($this->dbh === false || is_bool($this->dbh)) {
return '';
}
return pg_escape_string($this->dbh, (string)$string);
@@ -530,9 +531,9 @@ class PgSQL implements Interface\SqlFunctions
* @param string|int|float|bool $string any string/int/float/bool
* @return string excaped string including quites
*/
public function __dbEscapeLiteral(string|int|float|bool $string): string
public function __dbEscapeLiteral($string): string
{
if (is_bool($this->dbh)) {
if ($this->dbh === false || is_bool($this->dbh)) {
return (string)'';
}
// for phpstan, thinks this is string|false?
@@ -548,7 +549,7 @@ class PgSQL implements Interface\SqlFunctions
*/
public function __dbEscapeIdentifier(string $string): string
{
if (is_bool($this->dbh)) {
if ($this->dbh === false || is_bool($this->dbh)) {
return '';
}
// for phpstan, thinks this is string|false?
@@ -563,7 +564,7 @@ class PgSQL implements Interface\SqlFunctions
*/
public function __dbEscapeBytea(string $data): string
{
if (is_bool($this->dbh)) {
if ($this->dbh === false || is_bool($this->dbh)) {
return '';
}
return pg_escape_bytea($this->dbh, $data);
@@ -583,12 +584,11 @@ class PgSQL implements Interface\SqlFunctions
/**
* wrapper for pg_connection_busy
*
* @return bool True if connection is busy
* False if not or no db connection at all
* @return bool True if connection is busy, False if not or no db connection at all
*/
public function __dbConnectionBusy(): bool
{
if (is_bool($this->dbh)) {
if ($this->dbh === false || is_bool($this->dbh)) {
return false;
}
return pg_connection_busy($this->dbh);
@@ -597,13 +597,13 @@ class PgSQL implements Interface\SqlFunctions
/**
* Experimental wrapper with scoket timetout
*
* @param integer $timeout_seconds Wait how many seconds on timeout
* @return bool True if connection is busy, or false on
* not busy or no db connection at all
* @param integer $timeout_seconds Wait how many seconds on timeout
* @return boolean True if connection is busy, or false on
* not busy or no db connection at all
*/
public function __dbConnectionBusySocketWait(int $timeout_seconds = 3): bool
{
if (is_bool($this->dbh)) {
if ($this->dbh === false || is_bool($this->dbh)) {
return false;
}
$busy = pg_connection_busy($this->dbh);
@@ -626,14 +626,14 @@ class PgSQL implements Interface\SqlFunctions
* On default 'version' will be stripped of any space attached info
* eg 13.5 (other info) will return only 13.5
*
* @param string $parameter Parameter string to extract from array
* @param bool $strip If parameter is server strip out on default
* Set to false to get original string AS is
* @return string The parameter value
* @param string $parameter Parameter string to extract from array
* @param boolean $strip If parameter is server strip out on default
* Set to false to get original string AS is
* @return string The parameter value
*/
public function __dbVersionInfo(string $parameter, bool $strip = true): string
{
if (is_bool($this->dbh)) {
if ($this->dbh === false || is_bool($this->dbh)) {
return '';
}
// extract element
@@ -655,7 +655,7 @@ class PgSQL implements Interface\SqlFunctions
*/
public function __dbVersionInfoParameterList(): array
{
if (is_bool($this->dbh)) {
if ($this->dbh === false || is_bool($this->dbh)) {
return [];
}
return array_keys(pg_version($this->dbh));
@@ -670,7 +670,7 @@ class PgSQL implements Interface\SqlFunctions
*/
public function __dbVersion(): string
{
if (is_bool($this->dbh)) {
if ($this->dbh === false || is_bool($this->dbh)) {
return '';
}
// array has client, protocol, server, we just return server stripped
@@ -762,9 +762,9 @@ class PgSQL implements Interface\SqlFunctions
* @param string $parameter Parameter to query
* @return string|bool Settings value as string
*/
public function __dbParameter(string $parameter): string|bool
public function __dbParameter(string $parameter)
{
if (is_bool($this->dbh)) {
if ($this->dbh === false || is_bool($this->dbh)) {
return false;
}
if (empty($parameter)) {

View File

@@ -6,7 +6,7 @@
declare(strict_types=1);
namespace CoreLibs\DB\SQL\Interface;
namespace CoreLibs\DB\SQL\SqlInterface;
interface SqlFunctions
{
@@ -21,33 +21,33 @@ interface SqlFunctions
* Undocumented function
*
* @param string $query
* @return \PgSql\Result|false
* @return object|resource|bool
*/
public function __dbQuery(string $query): \PgSql\Result|false;
public function __dbQuery(string $query);
/**
* Undocumented function
*
* @param string $query
* @param array<mixed> $params
* @return \PgSql\Result|false
* @return object|resource|bool
*/
public function __dbQueryParams(string $query, array $params): \PgSql\Result|false;
public function __dbQueryParams(string $query, array $params);
/**
* Undocumented function
*
* @param string $query
* @return bool
* @return boolean
*/
public function __dbSendQuery(string $query): bool;
/**
* Undocumented function
*
* @return \PgSql\Result|false
* @return object|resource|bool
*/
public function __dbGetResult(): \PgSql\Result|false;
public function __dbGetResult();
/**
* Undocumented function
@@ -61,85 +61,85 @@ interface SqlFunctions
*
* @param string $name
* @param string $query
* @return \PgSql\Result|false
* @return object|resource|bool
*/
public function __dbPrepare(string $name, string $query): \PgSql\Result|false;
public function __dbPrepare(string $name, string $query);
/**
* Undocumented function
*
* @param string $name
* @param array<mixed> $data
* @return \PgSql\Result|false
* @return object|resource|bool
*/
public function __dbExecute(string $name, array $data): \PgSql\Result|false;
public function __dbExecute(string $name, array $data);
/**
* Undocumented function
*
* @param \PgSql\Result|false $cursor
* @return int
* @param object|resource|bool $cursor
* @return integer
*/
public function __dbNumRows(\PgSql\Result|false $cursor): int;
public function __dbNumRows($cursor): int;
/**
* Undocumented function
*
* @param \PgSql\Result|false $cursor
* @return int
* @param object|resource|bool $cursor
* @return integer
*/
public function __dbNumFields(\PgSql\Result|false $cursor): int;
public function __dbNumFields($cursor): int;
/**
* Undocumented function
*
* @param \PgSql\Result|false $cursor
* @param object|resource|bool $cursor
* @param int $i
* @return string|false
* @return string|bool
*/
public function __dbFieldName(\PgSql\Result|false $cursor, int $i): string|false;
public function __dbFieldName($cursor, int $i);
/**
* Undocumented function
*
* @param \PgSql\Result|false $cursor
* @param object|resource|bool $cursor
* @param int $result_type
* @return array<mixed>|bool
*/
public function __dbFetchArray(\PgSql\Result|false $cursor, int $result_type = PGSQL_BOTH);
public function __dbFetchArray($cursor, int $result_type = PGSQL_BOTH);
/**
* Undocumented function
*
* @param bool $assoc_type
* @return int
* @param boolean $assoc_type
* @return integer
*/
public function __dbResultType(bool $assoc_type = true): int;
/**
* Undocumented function
*
* @param \PgSql\Result|false $cursor
* @param object|resource|bool $cursor
* @return array<mixed>|bool
*/
public function __dbFetchAll(\PgSql\Result|false $cursor): array|bool;
public function __dbFetchAll($cursor);
/**
* Undocumented function
*
* @param \PgSql\Result|false $cursor
* @return int
* @param object|resource|bool $cursor
* @return integer
*/
public function __dbAffectedRows(\PgSql\Result|false $cursor): int;
public function __dbAffectedRows($cursor): int;
/**
* Undocumented function
*
* @param string $query
* @param string|null $pk_name
* @return string|int|false
* @return string|integer|false
*/
public function __dbInsertId(string $query, ?string $pk_name): string|int|false;
public function __dbInsertId(string $query, ?string $pk_name);
/**
* Undocumented function
@@ -148,7 +148,7 @@ interface SqlFunctions
* @param string $schema
* @return string|bool
*/
public function __dbPrimaryKey(string $table, string $schema = ''): string|bool;
public function __dbPrimaryKey(string $table, string $schema = '');
/**
* Undocumented function
@@ -157,9 +157,9 @@ interface SqlFunctions
* @param string $db_user
* @param string $db_pass
* @param string $db_name
* @param int $db_port
* @param integer $db_port
* @param string $db_ssl
* @return \PgSql\Connection|false
* @return object|resource|bool
*/
public function __dbConnect(
string $db_host,
@@ -168,24 +168,24 @@ interface SqlFunctions
string $db_name,
int $db_port,
string $db_ssl = 'allow'
): \PgSql\Connection|false;
);
/**
* Undocumented function
*
* @param \PgSql\Result|false $cursor
* @param object|resource|bool $cursor
* @return string
*/
public function __dbPrintError(\PgSql\Result|false $cursor = false): string;
public function __dbPrintError($cursor = false): string;
/**
* Undocumented function
*
* @param string $table
* @param bool $extended
* @param boolean $extended
* @return array<mixed>|bool
*/
public function __dbMetaData(string $table, bool $extended = true): array|bool;
public function __dbMetaData(string $table, $extended = true);
/**
* Undocumented function
@@ -193,7 +193,7 @@ interface SqlFunctions
* @param string|int|float|bool $string
* @return string
*/
public function __dbEscapeString(string|int|float|bool $string): string;
public function __dbEscapeString($string): string;
/**
* Undocumented function
@@ -201,7 +201,7 @@ interface SqlFunctions
* @param string|int|float|bool $string
* @return string
*/
public function __dbEscapeLiteral(string|int|float|bool $string): string;
public function __dbEscapeLiteral($string): string;
/**
* Undocumented function
@@ -230,15 +230,15 @@ interface SqlFunctions
/**
* Undocumented function
*
* @return bool
* @return boolean
*/
public function __dbConnectionBusy(): bool;
/**
* Undocumented function
*
* @param int $timeout_seconds
* @return bool
* @param integer $timeout_seconds
* @return boolean
*/
public function __dbConnectionBusySocketWait(int $timeout_seconds = 3): bool;
@@ -253,8 +253,8 @@ interface SqlFunctions
* Undocumented function
*
* @param string $array_text
* @param int $start
* @param int|null $end
* @param integer $start
* @param integer|null $end
* @return array<mixed>|null
*/
public function __dbArrayParse(
@@ -275,7 +275,7 @@ interface SqlFunctions
* Undocumented function
*
* @param string $db_schema
* @return int
* @return integer
*/
public function __dbSetSchema(string $db_schema): int;
@@ -290,7 +290,7 @@ interface SqlFunctions
* Undocumented function
*
* @param string $db_encoding
* @return int
* @return integer
*/
public function __dbSetEncoding(string $db_encoding): int;

View File

@@ -413,7 +413,7 @@ class Logging
* @param string $name what variable to return
* @return mixed can be anything, bool, string, int, array
*/
public function getSetting(string $name): mixed
public function getSetting(string $name) //:mixed DOES not work with PHP 7.4
{
// for debug purpose only
return $this->{$name};
@@ -550,9 +550,9 @@ class Logging
* @param string $flag on/off
* @param string|null $level if not null then check if this array entry is set
* else return false
* @return array<mixed>|bool if $level is null, return array, else boolean true/false
* @return bool|array<mixed> if $level is null, return array, else boolean true/false
*/
public function getLogLevel(string $type, string $flag, ?string $level = null): array|bool
public function getLogLevel(string $type, string $flag, ?string $level = null)
{
// abort if not valid type
if (!in_array($type, ['debug', 'echo', 'print'])) {

View File

@@ -122,7 +122,7 @@ class GetTextReader
* @param bool $enable_cache Enable or disable caching
* of strings (default on)
*/
public function __construct(FileReader|bool $Reader, bool $enable_cache = true)
public function __construct($Reader, bool $enable_cache = true)
{
// If there isn't a StreamReader, turn on short circuit mode.
if ((!is_object($Reader) && !$Reader) || (is_object($Reader) && $Reader->error)) {

View File

@@ -46,7 +46,7 @@ class Encoding
* @return void
* @deprecated Use \CoreLibs\Check\Encoding::setErrorChar();
*/
public static function setErrorChar(string|int|null $string): void
public static function setErrorChar($string): void
{
\CoreLibs\Check\Encoding::setErrorChar($string);
}
@@ -60,7 +60,7 @@ class Encoding
* @return string|int Set error character
* @deprecated Use \CoreLibs\Check\Encoding::getErrorChar();
*/
public static function getErrorChar(bool $return_substitute_func = false): string|int
public static function getErrorChar(bool $return_substitute_func = false)
{
return \CoreLibs\Check\Encoding::getErrorChar($return_substitute_func);
}
@@ -81,7 +81,7 @@ class Encoding
* @param string $string string to test
* @param string $from_encoding encoding of string to test
* @param string $to_encoding target encoding
* @return array<string>|false false if no error or
* @return bool|array<string> false if no error or
* array with failed characters
* @deprecated Use \CoreLibs\Check\Encoding::checkConvertEncoding();
*/
@@ -89,7 +89,7 @@ class Encoding
string $string,
string $from_encoding,
string $to_encoding
): array|false {
) {
return \CoreLibs\Check\Encoding::checkConvertEncoding($string, $from_encoding, $to_encoding);
}

View File

@@ -13,27 +13,27 @@ class Elements
/**
* print the date/time drop downs, used in any queue/send/insert at date/time place
*
* @param int|string $year year YYYY
* @param int|string $month month m
* @param int|string $day day d
* @param int|string $hour hour H
* @param int|string $min min i
* @param string $suffix additional info printed after the date time
* variable in the drop down
* also used for ID in the on change JS call
* @param int $min_steps default is 1 (minute), can set to anything,
* is used as sum up from 0
* @param bool $name_pos_back default false, if set to true,
* the name will be printend after the drop down
* and not before the drop down
* @return string HTML formated strings for drop down lists of date and time
* @param int $year year YYYY
* @param int $month month m
* @param int $day day d
* @param int $hour hour H
* @param int $min min i
* @param string $suffix additional info printed after the date time
* variable in the drop down
* also used for ID in the on change JS call
* @param int $min_steps default is 1 (minute), can set to anything,
* is used as sum up from 0
* @param bool $name_pos_back default false, if set to true,
* the name will be printend after the drop down
* and not before the drop down
* @return string HTML formated strings for drop down lists of date and time
*/
public static function printDateTime(
int|string $year,
int|string $month,
int|string $day,
int|string $hour,
int|string $min,
$year,
$month,
$day,
$hour,
$min,
string $suffix = '',
int $min_steps = 1,
bool $name_pos_back = false

View File

@@ -366,7 +366,7 @@ class Generate extends \CoreLibs\DB\Extended\ArrayIO
$config_array = $table_arrays[System::getPageName(1)];
} else {
// primary try to load the class
/** @var TableArrays\Interface\TableArraysInterface|false $content_class */
/** @var \CoreLibs\Output\Form\TableArraysInterface|false $content_class */
$content_class = $this->loadTableArray();
if (is_object($content_class)) {
$config_array = $content_class->setTableArray();
@@ -468,9 +468,9 @@ class Generate extends \CoreLibs\DB\Extended\ArrayIO
/**
* load table array class based on my page name converted to camel case
* class files are in \TableArrays folder in \Output\Form
* @return TableArrays\Interface\TableArraysInterface|false Return class object or false on failure
* @return object|bool Return class object or false on failure
*/
private function loadTableArray(): TableArrays\Interface\TableArraysInterface|false
private function loadTableArray()
{
// note: it schould be Schemas but an original type made it to this
// this file is kept for the old usage, new one should be EditSchemas
@@ -489,7 +489,7 @@ class Generate extends \CoreLibs\DB\Extended\ArrayIO
$page_name_camel_case
);
try {
/** @var TableArrays\Interface\TableArraysInterface|false $class */
/** @var \CoreLibs\Output\Form\TableArraysInterface|false $class */
$class = new $class_string($this);
} catch (\Throwable $t) {
$this->log->debug('CLASS LOAD', 'Failed loading: ' . $class_string . ' => ' . $t->getMessage());
@@ -651,7 +651,7 @@ class Generate extends \CoreLibs\DB\Extended\ArrayIO
$this->base_acl_level >= $this->security_level['new']
) {
if ($this->really_new == 'yes') {
$this->formUnsetTableArray();
$this->formUnsetTablearray();
} else {
$this->msg .= $this->l->__('You have to select the <b>Checkbox for New</b>!<br>');
$this->error = 2;
@@ -731,6 +731,9 @@ class Generate extends \CoreLibs\DB\Extended\ArrayIO
empty($this->table_array['protected']['value']) &&
!$this->error
) {
if (!is_array($element_list)) {
$element_list = [];
}
for ($i = 0, $i_max = count($element_list); $i < $i_max; $i++) {
// $this->log->debug('form_error', 'Array: '
// . is_array($this->element_list[$element_list[$i]]['read_data']) . ' | '
@@ -2291,9 +2294,11 @@ class Generate extends \CoreLibs\DB\Extended\ArrayIO
}
}
}
reset($hidden_array);
foreach ($hidden_array as $key => $value) {
$hidden[] = ['key' => $key, 'value' => $value];
if (is_array($hidden_array)) {
reset($hidden_array);
foreach ($hidden_array as $key => $value) {
$hidden[] = ['key' => $key, 'value' => $value];
}
}
return $hidden;
}

View File

@@ -87,9 +87,7 @@ class EditAccess implements Interface\TableArraysInterface
],
],
'table_name' => 'edit_access',
"load_query" => "SELECT edit_access_id, name "
. "FROM edit_access "
. "ORDER BY name",
"load_query" => "SELECT edit_access_id, name FROM edit_access ORDER BY name",
'show_fields' => [
[
'name' => 'name'

View File

@@ -55,19 +55,14 @@ class EditGroups implements Interface\TableArraysInterface
'mandatory' => 1,
'int' => 1,
'type' => 'drop_down_db',
'query' => "SELECT edit_access_right_id, name "
. "FROM edit_access_right "
. "ORDER BY level"
'query' => "SELECT edit_access_right_id, name FROM edit_access_right ORDER BY level"
],
'edit_scheme_id' => [
'value' => $_POST['edit_scheme_id'] ?? '',
'output_name' => 'Group Scheme',
'int_null' => 1,
'type' => 'drop_down_db',
'query' => "SELECT edit_scheme_id, name "
. "FROM edit_scheme "
. "WHERE enabled = 1 "
. "ORDER BY name"
'query' => "SELECT edit_scheme_id, name FROM edit_scheme WHERE enabled = 1 ORDER BY name"
],
'additional_acl' => [
'value' => $_POST['additional_acl'] ?? '',
@@ -78,9 +73,7 @@ class EditGroups implements Interface\TableArraysInterface
'cols' => 60
],
],
'load_query' => "SELECT edit_group_id, name, enabled "
. "FROM edit_group "
. "ORDER BY name",
'load_query' => "SELECT edit_group_id, name, enabled FROM edit_group ORDER BY name",
'table_name' => 'edit_group',
'show_fields' => [
[
@@ -122,9 +115,7 @@ class EditGroups implements Interface\TableArraysInterface
'output_name' => 'Access Level',
'int' => 1,
'preset' => 1, // first of the select
'query' => "SELECT edit_access_right_id, name "
. "FROM edit_access_right "
. "ORDER BY level"
'query' => "SELECT edit_access_right_id, name FROM edit_access_right ORDER BY level"
],
'edit_page_id' => [
'int' => 1,

View File

@@ -55,9 +55,7 @@ class EditMenuGroup implements Interface\TableArraysInterface
],
],
'table_name' => 'edit_menu_group',
'load_query' => "SELECT edit_menu_group_id, name "
. "FROM edit_menu_group "
. "ORDER BY name",
'load_query' => "SELECT edit_menu_group_id, name FROM edit_menu_group ORDER BY name",
'show_fields' => [
[
'name' => 'name'

View File

@@ -140,10 +140,7 @@ class EditPages implements Interface\TableArraysInterface
],
],
'load_query' => "SELECT edit_page_id, "
. "CASE "
. "WHEN hostname IS NOT NULL THEN hostname "
. "ELSE ''::VARCHAR "
. "END || filename AS filename, "
. "CASE WHEN hostname IS NOT NULL THEN hostname ELSE ''::VARCHAR END || filename AS filename, "
. "name, online, menu, popup "
. "FROM edit_page "
. "ORDER BY order_number",
@@ -181,8 +178,7 @@ class EditPages implements Interface\TableArraysInterface
'select_size' => 10,
'selected' => $_POST['edit_visible_group_id'] ?? '',
'query' => "SELECT edit_visible_group_id, 'Name: ' || name || ', ' || 'Flag: ' || flag "
. "FROM edit_visible_group "
. "ORDER BY name"
. "FROM edit_visible_group ORDER BY name"
],
'edit_menu_group' => [
'table_name' => 'edit_page_menu_group',
@@ -192,8 +188,7 @@ class EditPages implements Interface\TableArraysInterface
'select_size' => 10,
'selected' => $_POST['edit_menu_group_id'] ?? '',
'query' => "SELECT edit_menu_group_id, 'Name: ' || name || ', ' || 'Flag: ' || flag "
. "FROM edit_menu_group "
. "ORDER BY order_number"
. "FROM edit_menu_group ORDER BY order_number"
],
],
'element_list' => [
@@ -264,9 +259,7 @@ class EditPages implements Interface\TableArraysInterface
'output_name' => 'Access Level',
'int' => 1,
'preset' => 1, // first of the select
'query' => "SELECT edit_access_right_id, name "
. "FROM edit_access_right "
. "ORDER BY level"
'query' => "SELECT edit_access_right_id, name FROM edit_access_right ORDER BY level"
],
'edit_page_content_id' => [
'type' => 'hidden',

View File

@@ -68,9 +68,7 @@ class EditSchemas implements Interface\TableArraysInterface
],
],
'table_name' => 'edit_scheme',
'load_query' => "SELECT edit_scheme_id, name, enabled "
. "FROM edit_scheme "
. "ORDER BY name",
'load_query' => "SELECT edit_scheme_id, name, enabled FROM edit_scheme ORDER BY name",
'show_fields' => [
[
'name' => 'name'

View File

@@ -274,7 +274,7 @@ class EditUsers implements Interface\TableArraysInterface
'type' => 'drop_down_db',
'query' => "SELECT edit_language_id, long_name "
. "FROM edit_language "
. "WHERE enabled = 1 "
. "WHERE enabled = 1"
. "ORDER BY order_number",
'min_edit_acl' => '100',
'min_show_acl' => '100',
@@ -284,10 +284,7 @@ class EditUsers implements Interface\TableArraysInterface
'output_name' => 'Scheme',
'int_null' => 1,
'type' => 'drop_down_db',
'query' => "SELECT edit_scheme_id, name "
. "FROM edit_scheme "
. "WHERE enabled = 1 "
. "ORDER BY name",
'query' => "SELECT edit_scheme_id, name FROM edit_scheme WHERE enabled = 1 ORDER BY name",
'min_edit_acl' => '100',
'min_show_acl' => '100',
],
@@ -296,10 +293,7 @@ class EditUsers implements Interface\TableArraysInterface
'output_name' => 'Group',
'int' => 1,
'type' => 'drop_down_db',
'query' => "SELECT edit_group_id, name "
. "FROM edit_group "
. "WHERE enabled = 1 "
. "ORDER BY name",
'query' => "SELECT edit_group_id, name FROM edit_group WHERE enabled = 1 ORDER BY name",
'mandatory' => 1,
'min_edit_acl' => '100',
'min_show_acl' => '100',
@@ -310,9 +304,7 @@ class EditUsers implements Interface\TableArraysInterface
'mandatory' => 1,
'int' => 1,
'type' => 'drop_down_db',
'query' => "SELECT edit_access_right_id, name "
. "FROM edit_access_right "
. "ORDER BY level",
'query' => "SELECT edit_access_right_id, name FROM edit_access_right ORDER BY level",
'min_edit_acl' => '100',
'min_show_acl' => '100',
],
@@ -442,9 +434,7 @@ class EditUsers implements Interface\TableArraysInterface
'output_name' => 'Access Level',
'preset' => 1, // first of the select
'int' => 1,
'query' => "SELECT edit_access_right_id, name "
. "FROM edit_access_right "
. "ORDER BY level"
'query' => "SELECT edit_access_right_id, name FROM edit_access_right ORDER BY level"
],
'edit_default' => [
'type' => 'radio_group',

View File

@@ -48,9 +48,7 @@ class EditVisibleGroup implements Interface\TableArraysInterface
],
],
'table_name' => 'edit_visible_group',
'load_query' => "SELECT edit_visible_group_id, name "
. "FROM edit_visible_group "
. "ORDER BY name",
'load_query' => "SELECT edit_visible_group_id, name FROM edit_visible_group ORDER BY name",
'show_fields' => [
[
'name' => 'name'

Some files were not shown because too many files have changed in this diff Show More