diff --git a/.gitmodules b/.gitmodules index 6696eb5bc9..b7ed9bf641 100644 --- a/.gitmodules +++ b/.gitmodules @@ -7,9 +7,9 @@ [submodule "tests/plugins/PocketMine-DevTools"] path = tests/plugins/PocketMine-DevTools url = https://github.com/pmmp/PocketMine-DevTools.git -[submodule "src/pocketmine/resources/vanilla"] - path = src/pocketmine/resources/vanilla - url = https://github.com/pmmp/BedrockData.git [submodule "build/php"] path = build/php url = https://github.com/pmmp/php-build-scripts.git +[submodule "src/pocketmine/resources/vanilla"] + path = src/pocketmine/resources/vanilla + url = https://github.com/pmmp/BedrockData.git diff --git a/.travis.yml b/.travis.yml index dcc2e12988..2fc68b387d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,6 +5,7 @@ php: - 7.3 before_script: + - phpenv config-rm xdebug.ini # - pecl install channel://pecl.php.net/pthreads-3.1.6 - echo | pecl install channel://pecl.php.net/yaml-2.0.4 - git clone https://github.com/pmmp/pthreads.git @@ -16,10 +17,18 @@ before_script: - make install - cd .. - echo "extension=pthreads.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini - - composer install script: + - composer install --prefer-dist + - ./vendor/bin/phpstan analyze --no-progress --memory-limit=2G + - ./vendor/bin/phpunit --bootstrap vendor/autoload.php --fail-on-warning tests/phpunit + - composer install --no-dev --prefer-dist - ./tests/travis.sh -t4 +cache: + directories: + - $HOME/.composer/cache/files + - $HOME/.composer/cache/vcs + notifications: email: false diff --git a/BUILDING.md b/BUILDING.md new file mode 100644 index 0000000000..a4e0d85953 --- /dev/null +++ b/BUILDING.md @@ -0,0 +1,38 @@ +# Building +## Pre-requisites +- A bash shell (git bash is sufficient for Windows) +- [`git`](https://git-scm.com) available in your shell +- PHP 7.2 or newer available in your shell +- [`composer`](https://getcomposer.org) available in your shell + +## Custom PHP binaries +Because PocketMine-MP requires several non-standard PHP extensions and configuration, PMMP provides scripts to build custom binaries for running PocketMine-MP, as well as prebuilt binaries. + +- [Prebuilt binaries](https://jenkins.pmmp.io/job/PHP-7.3-Aggregate) +- [Compile scripts](https://github.com/pmmp/php-build-scripts) are provided as a submodule in the path `build/php` + +If you use a custom binary, you'll need to replace `composer` usages in this guide with `path/to/your/php path/to/your/composer.phar`. + +## Setting up environment +1. `git clone --recursive https://github.com/pmmp/PocketMine-MP.git` +2. `composer install` + +## Checking out a different branch to build +1. `git checkout ` +2. `git submodule update --init` +3. Re-run `composer install` to synchronize dependencies. + +## Optimizing for release builds +1. Add the flags `--no-dev --classmap-authoritative` to your `composer install` command. This will reduce build size and improve autoloading speed. +2. Preprocess the source code by running `build/preprocessor/PreProcessor.php`. Usage instructions are provided in `build/preprocessor/README.md`. + +### Note +Preprocessor requires that the `cpp` (c preprocessor) is available in your PATH. + +## Building `PocketMine-MP.phar` +Run `build/server.phar` using your preferred PHP binary. It'll drop a `PocketMine-MP.phar` into the current working directory. + +You can also use the `--out` option to change the output filename. + +## Running PocketMine-MP from source code +Run `src/pocketmine/PocketMine.php` using your preferred PHP binary. \ No newline at end of file diff --git a/README.md b/README.md index ec613ee56a..519926655e 100644 --- a/README.md +++ b/README.md @@ -13,10 +13,11 @@ ## Discussion/Help - [Forums](https://forums.pmmp.io/) -- [Community Discord](https://discord.gg/bmSAZBG) +- [Discord](https://discord.gg/bmSAZBG) - [StackOverflow](https://stackoverflow.com/tags/pocketmine) ## For developers + * [Building and running from source](BUILDING.md) * [Latest API documentation](https://jenkins.pmmp.io/job/PocketMine-MP-doc/doxygen/) - Doxygen documentation generated from development * [DevTools](https://github.com/pmmp/PocketMine-DevTools/) - Development tools plugin for creating plugins * [ExamplePlugin](https://github.com/pmmp/ExamplePlugin/) - Example plugin demonstrating some basic API features diff --git a/build/make-release.php b/build/make-release.php index c8a475e57d..d78f9adcc2 100644 --- a/build/make-release.php +++ b/build/make-release.php @@ -21,14 +21,13 @@ declare(strict_types=1); -namespace pocketmine\build_script; +namespace pocketmine\build\make_release; use pocketmine\utils\VersionString; use function dirname; use function fgets; use function file_get_contents; use function file_put_contents; -use function preg_quote; use function preg_replace; use function sleep; use function sprintf; @@ -36,20 +35,8 @@ use function system; use const pocketmine\BASE_VERSION; use const STDIN; -require_once dirname(__DIR__) . '/src/pocketmine/VersionInfo.php'; require_once dirname(__DIR__) . '/vendor/autoload.php'; -if(isset($argv[1])){ - $currentVer = new VersionString($argv[1]); -}else{ - $currentVer = new VersionString(BASE_VERSION); -} -$nextVer = new VersionString(sprintf( - "%u.%u.%u", - $currentVer->getMajor(), - $currentVer->getMinor(), - $currentVer->getPatch() + 1 -)); function replaceVersion(string $versionInfoPath, string $newVersion, bool $isDev) : void{ $versionInfo = file_get_contents($versionInfoPath); @@ -60,22 +47,45 @@ function replaceVersion(string $versionInfoPath, string $newVersion, bool $isDev ); $versionInfo = preg_replace( '/^const IS_DEVELOPMENT_BUILD = (?:true|false);$/m', - 'const IS_DEVELOPMENT_BUILD = ' . ($isDev ? 'true' : 'false'). ';', + 'const IS_DEVELOPMENT_BUILD = ' . ($isDev ? 'true' : 'false') . ';', $versionInfo ); file_put_contents($versionInfoPath, $versionInfo); } -$versionInfoPath = dirname(__DIR__) . '/src/pocketmine/VersionInfo.php'; -replaceVersion($versionInfoPath, $currentVer->getBaseVersion(), false); -echo "please add appropriate notes to the changelog and press enter..."; -fgets(STDIN); -system('git add "' . dirname(__DIR__) . '/changelogs"'); -system('git commit -m "Release ' . $currentVer->getBaseVersion() . '" --include "' . $versionInfoPath . '"'); -system('git tag ' . $currentVer->getBaseVersion()); -replaceVersion($versionInfoPath, $nextVer->getBaseVersion(), true); -system('git add "' . $versionInfoPath . '"'); -system('git commit -m "' . $nextVer->getBaseVersion() . ' is next" --include "' . $versionInfoPath . '"'); -echo "pushing changes in 5 seconds\n"; -sleep(5); -system('git push origin HEAD ' . $currentVer->getBaseVersion()); +/** + * @param string[] $argv + * @phpstan-param list $argv + */ +function main(array $argv) : void{ + if(isset($argv[1])){ + $currentVer = new VersionString($argv[1]); + }else{ + $currentVer = new VersionString(BASE_VERSION); + } + $nextVer = new VersionString(sprintf( + "%u.%u.%u", + $currentVer->getMajor(), + $currentVer->getMinor(), + $currentVer->getPatch() + 1 + )); + + $versionInfoPath = dirname(__DIR__) . '/src/pocketmine/VersionInfo.php'; + replaceVersion($versionInfoPath, $currentVer->getBaseVersion(), false); + + echo "please add appropriate notes to the changelog and press enter..."; + fgets(STDIN); + system('git add "' . dirname(__DIR__) . '/changelogs"'); + system('git commit -m "Release ' . $currentVer->getBaseVersion() . '" --include "' . $versionInfoPath . '"'); + system('git tag ' . $currentVer->getBaseVersion()); + replaceVersion($versionInfoPath, $nextVer->getBaseVersion(), true); + system('git add "' . $versionInfoPath . '"'); + system('git commit -m "' . $nextVer->getBaseVersion() . ' is next" --include "' . $versionInfoPath . '"'); + echo "pushing changes in 5 seconds\n"; + sleep(5); + system('git push origin HEAD ' . $currentVer->getBaseVersion()); +} + +if(!defined('pocketmine\_PHPSTAN_ANALYSIS')){ + main($argv); +} diff --git a/build/server-phar.php b/build/server-phar.php new file mode 100644 index 0000000000..d99bf9943d --- /dev/null +++ b/build/server-phar.php @@ -0,0 +1,170 @@ + $metadata + * + * @return \Generator|string[] + */ +function buildPhar(string $pharPath, string $basePath, array $includedPaths, array $metadata, string $stub, int $signatureAlgo = \Phar::SHA1, ?int $compression = null){ + $basePath = rtrim(str_replace("/", DIRECTORY_SEPARATOR, $basePath), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; + $includedPaths = array_map(function(string $path) : string{ + return rtrim(str_replace("/", DIRECTORY_SEPARATOR, $path), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; + }, $includedPaths); + yield "Creating output file $pharPath"; + if(file_exists($pharPath)){ + yield "Phar file already exists, overwriting..."; + try{ + \Phar::unlinkArchive($pharPath); + }catch(\PharException $e){ + //unlinkArchive() doesn't like dodgy phars + unlink($pharPath); + } + } + + yield "Adding files..."; + + $start = microtime(true); + $phar = new \Phar($pharPath); + $phar->setMetadata($metadata); + $phar->setStub($stub); + $phar->setSignatureAlgorithm($signatureAlgo); + $phar->startBuffering(); + + //If paths contain any of these, they will be excluded + $excludedSubstrings = preg_quote_array([ + realpath($pharPath), //don't add the phar to itself + ], '/'); + + $folderPatterns = preg_quote_array([ + DIRECTORY_SEPARATOR . 'tests' . DIRECTORY_SEPARATOR, + DIRECTORY_SEPARATOR . '.' //"Hidden" files, git dirs etc + ], '/'); + + //Only exclude these within the basedir, otherwise the project won't get built if it itself is in a directory that matches these patterns + $basePattern = preg_quote(rtrim($basePath, DIRECTORY_SEPARATOR), '/'); + foreach($folderPatterns as $p){ + $excludedSubstrings[] = $basePattern . '.*' . $p; + } + + $regex = sprintf('/^(?!.*(%s))^%s(%s).*/i', + implode('|', $excludedSubstrings), //String may not contain any of these substrings + preg_quote($basePath, '/'), //String must start with this path... + implode('|', preg_quote_array($includedPaths, '/')) //... and must be followed by one of these relative paths, if any were specified. If none, this will produce a null capturing group which will allow anything. + ); + + $directory = new \RecursiveDirectoryIterator($basePath, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS | \FilesystemIterator::CURRENT_AS_PATHNAME); //can't use fileinfo because of symlinks + $iterator = new \RecursiveIteratorIterator($directory); + $regexIterator = new \RegexIterator($iterator, $regex); + + $count = count($phar->buildFromIterator($regexIterator, $basePath)); + yield "Added $count files"; + + if($compression !== null){ + yield "Compressing files..."; + $phar->compressFiles($compression); + yield "Finished compression"; + } + $phar->stopBuffering(); + + yield "Done in " . round(microtime(true) - $start, 3) . "s"; +} + +function main() : void{ + if(ini_get("phar.readonly") == 1){ + echo "Set phar.readonly to 0 with -dphar.readonly=0" . PHP_EOL; + exit(1); + } + + $opts = getopt("", ["out:"]); + $gitHash = Git::getRepositoryStatePretty(dirname(__DIR__)); + echo "Git hash detected as $gitHash" . PHP_EOL; + foreach(buildPhar( + $opts["out"] ?? getcwd() . DIRECTORY_SEPARATOR . "PocketMine-MP.phar", + dirname(__DIR__) . DIRECTORY_SEPARATOR, + [ + 'src', + 'vendor' + ], + [ + 'git' => $gitHash + ], + <<<'STUB' +=2.0.0", "ext-zip": "*", "ext-zlib": ">=1.2.11", - "pocketmine/raklib": "^0.12.5", - "pocketmine/spl": "^0.3.0", + "pocketmine/raklib": "^0.12.7", + "pocketmine/spl": "^0.4.0", "pocketmine/binaryutils": "^0.1.9", "pocketmine/nbt": "^0.2.10", "pocketmine/math": "^0.2.0", "pocketmine/snooze": "^0.1.0", + "pocketmine/classloader": "^0.1.0", + "pocketmine/log": "^0.1.0", "daverandom/callback-validator": "dev-master", - "adhocore/json-comment": "^0.0.7" + "adhocore/json-comment": "^0.1.0" + }, + "require-dev": { + "phpstan/phpstan": "^0.12.9", + "irstea/phpunit-shim": "^8.5", + "phpstan/phpstan-phpunit": "^0.12.6", + "phpstan/phpstan-strict-rules": "^0.12.2" }, "autoload": { "psr-4": { "": ["src"] }, "files": [ + "src/pocketmine/CoreConstants.php", "src/pocketmine/GlobalConstants.php", "src/pocketmine/VersionInfo.php" ] @@ -46,31 +55,5 @@ "psr-4": { "pocketmine\\": "tests/phpunit/" } - }, - "repositories": [ - { - "type": "vcs", - "url": "https://github.com/pmmp/RakLib" - }, - { - "type": "vcs", - "url": "https://github.com/pmmp/SPL" - }, - { - "type": "vcs", - "url": "https://github.com/pmmp/BinaryUtils" - }, - { - "type": "vcs", - "url": "https://github.com/pmmp/NBT" - }, - { - "type": "vcs", - "url": "https://github.com/pmmp/Math" - }, - { - "type": "vcs", - "url": "https://github.com/pmmp/Snooze" - } - ] + } } diff --git a/composer.lock b/composer.lock index 5f3a84bafb..41e2834c30 100644 --- a/composer.lock +++ b/composer.lock @@ -4,27 +4,27 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "377d9e0ab5f1a9a4ef9b664706d26f5b", + "content-hash": "e22866a7924c444da73ff31b831b30cb", "packages": [ { "name": "adhocore/json-comment", - "version": "v0.0.7", + "version": "0.1.0", "source": { "type": "git", "url": "https://github.com/adhocore/php-json-comment.git", - "reference": "135356c7e7336ef59924f1d921c770045f937a76" + "reference": "8448076039389f558f39ad0553aab87db3f81614" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/adhocore/php-json-comment/zipball/135356c7e7336ef59924f1d921c770045f937a76", - "reference": "135356c7e7336ef59924f1d921c770045f937a76", + "url": "https://api.github.com/repos/adhocore/php-json-comment/zipball/8448076039389f558f39ad0553aab87db3f81614", + "reference": "8448076039389f558f39ad0553aab87db3f81614", "shasum": "" }, "require": { "php": ">=5.4" }, "require-dev": { - "phpunit/phpunit": "^4.8 || ^5.7 || ^6.5" + "phpunit/phpunit": "^6.5 || ^7.5" }, "type": "library", "autoload": { @@ -48,7 +48,7 @@ "json", "strip-comment" ], - "time": "2018-08-01T12:27:26+00:00" + "time": "2020-01-03T13:51:23+00:00" }, { "name": "daverandom/callback-validator", @@ -92,84 +92,159 @@ }, { "name": "pocketmine/binaryutils", - "version": "0.1.10", + "version": "0.1.11", "source": { "type": "git", "url": "https://github.com/pmmp/BinaryUtils.git", - "reference": "435f2ee265bce75ef1aa9563f9b60ff36d705e80" + "reference": "e8cb65db1b7998eebb739b124f2a989fe87366eb" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/pmmp/BinaryUtils/zipball/435f2ee265bce75ef1aa9563f9b60ff36d705e80", - "reference": "435f2ee265bce75ef1aa9563f9b60ff36d705e80", + "url": "https://api.github.com/repos/pmmp/BinaryUtils/zipball/e8cb65db1b7998eebb739b124f2a989fe87366eb", + "reference": "e8cb65db1b7998eebb739b124f2a989fe87366eb", "shasum": "" }, "require": { "php": ">=7.2", "php-64bit": "*" }, + "require-dev": { + "phpstan/phpstan": "^0.12.8" + }, "type": "library", "autoload": { "psr-4": { "pocketmine\\utils\\": "src/" } }, + "notification-url": "https://packagist.org/downloads/", "license": [ "LGPL-3.0" ], "description": "Classes and methods for conveniently handling binary data", - "support": { - "source": "https://github.com/pmmp/BinaryUtils/tree/0.1.10", - "issues": "https://github.com/pmmp/BinaryUtils/issues" - }, - "time": "2019-10-21T14:40:32+00:00" + "time": "2020-01-28T12:09:56+00:00" }, { - "name": "pocketmine/math", - "version": "0.2.3", + "name": "pocketmine/classloader", + "version": "0.1.0", "source": { "type": "git", - "url": "https://github.com/pmmp/Math.git", - "reference": "68be8a79fd0169043ef514797c304517cb8a6071" + "url": "https://github.com/pmmp/ClassLoader.git", + "reference": "4ccdb30e48f030bfcad04bb0a208d198ec631993" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/pmmp/Math/zipball/68be8a79fd0169043ef514797c304517cb8a6071", - "reference": "68be8a79fd0169043ef514797c304517cb8a6071", + "url": "https://api.github.com/repos/pmmp/ClassLoader/zipball/4ccdb30e48f030bfcad04bb0a208d198ec631993", + "reference": "4ccdb30e48f030bfcad04bb0a208d198ec631993", + "shasum": "" + }, + "require": { + "ext-pthreads": "~3.2.0", + "ext-reflection": "*", + "php": ">=7.2.0" + }, + "conflict": { + "pocketmine/spl": "<0.4" + }, + "require-dev": { + "phpstan/phpstan": "^0.12.8" + }, + "type": "library", + "autoload": { + "classmap": [ + "./src" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-3.0" + ], + "description": "Ad-hoc autoloading components used by PocketMine-MP", + "time": "2020-01-31T14:25:52+00:00" + }, + { + "name": "pocketmine/log", + "version": "0.1.0", + "source": { + "type": "git", + "url": "https://github.com/pmmp/Log.git", + "reference": "62c1f0ea5a5c0ae4b308f9bd231fb11638ff866e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/pmmp/Log/zipball/62c1f0ea5a5c0ae4b308f9bd231fb11638ff866e", + "reference": "62c1f0ea5a5c0ae4b308f9bd231fb11638ff866e", + "shasum": "" + }, + "require": { + "ext-pthreads": "~3.2.0", + "php": ">=7.2" + }, + "conflict": { + "pocketmine/spl": "<0.4" + }, + "require-dev": { + "phpstan/phpstan": "^0.12.8" + }, + "type": "library", + "autoload": { + "classmap": [ + "./src" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-3.0" + ], + "description": "Logging components used by PocketMine-MP and related projects", + "time": "2020-01-31T14:31:47+00:00" + }, + { + "name": "pocketmine/math", + "version": "0.2.4", + "source": { + "type": "git", + "url": "https://github.com/pmmp/Math.git", + "reference": "b1c28b236df8b795d7b06cf8421f9962b12ac410" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/pmmp/Math/zipball/b1c28b236df8b795d7b06cf8421f9962b12ac410", + "reference": "b1c28b236df8b795d7b06cf8421f9962b12ac410", "shasum": "" }, "require": { "php": ">=7.2.0", "php-64bit": "*" }, + "require-dev": { + "phpstan/phpstan": "^0.12.8" + }, "type": "library", "autoload": { "psr-4": { "pocketmine\\math\\": "src/" } }, + "notification-url": "https://packagist.org/downloads/", "license": [ "LGPL-3.0" ], "description": "PHP library containing math related code used in PocketMine-MP", - "support": { - "source": "https://github.com/pmmp/Math/tree/0.2.3", - "issues": "https://github.com/pmmp/Math/issues" - }, - "time": "2019-10-21T14:35:10+00:00" + "time": "2020-01-28T14:11:54+00:00" }, { "name": "pocketmine/nbt", - "version": "0.2.12", + "version": "0.2.13", "source": { "type": "git", "url": "https://github.com/pmmp/NBT.git", - "reference": "b5777265329753b74dd40bb105eedabeefb98724" + "reference": "6fc56f864a5375471f6e2d0f9f89f2462a1d8433" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/pmmp/NBT/zipball/b5777265329753b74dd40bb105eedabeefb98724", - "reference": "b5777265329753b74dd40bb105eedabeefb98724", + "url": "https://api.github.com/repos/pmmp/NBT/zipball/6fc56f864a5375471f6e2d0f9f89f2462a1d8433", + "reference": "6fc56f864a5375471f6e2d0f9f89f2462a1d8433", "shasum": "" }, "require": { @@ -178,39 +253,35 @@ "php-64bit": "*", "pocketmine/binaryutils": "^0.1.9" }, + "require-dev": { + "irstea/phpunit-shim": "^7.5", + "phpstan/phpstan": "^0.12.8" + }, "type": "library", "autoload": { "psr-4": { "pocketmine\\nbt\\": "src/" } }, - "autoload-dev": { - "psr-4": { - "pocketmine\\nbt\\": "tests/phpunit/" - } - }, + "notification-url": "https://packagist.org/downloads/", "license": [ "LGPL-3.0" ], "description": "PHP library for working with Named Binary Tags", - "support": { - "source": "https://github.com/pmmp/NBT/tree/0.2", - "issues": "https://github.com/pmmp/NBT/issues" - }, - "time": "2019-12-01T08:20:26+00:00" + "time": "2020-01-28T17:03:46+00:00" }, { "name": "pocketmine/raklib", - "version": "0.12.6", + "version": "0.12.7", "source": { "type": "git", "url": "https://github.com/pmmp/RakLib.git", - "reference": "18450e01185e6064790bda563ac672e7141c6992" + "reference": "01abb4e78e2ef69a83d50037d558e0b274f8245b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/pmmp/RakLib/zipball/18450e01185e6064790bda563ac672e7141c6992", - "reference": "18450e01185e6064790bda563ac672e7141c6992", + "url": "https://api.github.com/repos/pmmp/RakLib/zipball/01abb4e78e2ef69a83d50037d558e0b274f8245b", + "reference": "01abb4e78e2ef69a83d50037d558e0b274f8245b", "shasum": "" }, "require": { @@ -221,8 +292,11 @@ "php-64bit": "*", "php-ipv6": "*", "pocketmine/binaryutils": "^0.1.9", - "pocketmine/snooze": "^0.1.0", - "pocketmine/spl": "^0.3.0" + "pocketmine/log": "^0.1.0", + "pocketmine/snooze": "^0.1.0" + }, + "require-dev": { + "phpstan/phpstan": "^0.12.8" }, "type": "library", "autoload": { @@ -230,82 +304,278 @@ "raklib\\": "src/" } }, + "notification-url": "https://packagist.org/downloads/", "license": [ "GPL-3.0" ], "description": "A RakNet server implementation written in PHP", - "support": { - "source": "https://github.com/pmmp/RakLib/tree/0.12.6", - "issues": "https://github.com/pmmp/RakLib/issues" - }, - "time": "2019-12-07T13:43:34+00:00" + "time": "2020-01-31T15:33:05+00:00" }, { "name": "pocketmine/snooze", - "version": "0.1.1", + "version": "0.1.2", "source": { "type": "git", "url": "https://github.com/pmmp/Snooze.git", - "reference": "b7bd231bdb75e69300cac89ccd515fc731c38c40" + "reference": "88420da3d9335dbcb3ee2decfd5e5453d057dcdf" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/pmmp/Snooze/zipball/b7bd231bdb75e69300cac89ccd515fc731c38c40", - "reference": "b7bd231bdb75e69300cac89ccd515fc731c38c40", + "url": "https://api.github.com/repos/pmmp/Snooze/zipball/88420da3d9335dbcb3ee2decfd5e5453d057dcdf", + "reference": "88420da3d9335dbcb3ee2decfd5e5453d057dcdf", "shasum": "" }, "require": { "ext-pthreads": ">=3.1.7dev", "php-64bit": ">=7.2.0" }, + "require-dev": { + "phpstan/phpstan": "^0.12.8" + }, "type": "library", "autoload": { "psr-4": { "pocketmine\\snooze\\": "src/" } }, + "notification-url": "https://packagist.org/downloads/", "license": [ "LGPL-3.0" ], "description": "Thread notification management library for code using the pthreads extension", - "support": { - "source": "https://github.com/pmmp/Snooze/tree/0.1.1", - "issues": "https://github.com/pmmp/Snooze/issues" - }, - "time": "2019-01-04T15:54:45+00:00" + "time": "2020-01-28T19:08:10+00:00" }, { "name": "pocketmine/spl", - "version": "0.3.3", + "version": "0.4.1", "source": { "type": "git", "url": "https://github.com/pmmp/SPL.git", - "reference": "94d4df142fe837ba836e9348dd00209e4bdcc307" + "reference": "ff0579a0be41bbe65d3637607715c0f87728a838" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/pmmp/SPL/zipball/94d4df142fe837ba836e9348dd00209e4bdcc307", - "reference": "94d4df142fe837ba836e9348dd00209e4bdcc307", + "url": "https://api.github.com/repos/pmmp/SPL/zipball/ff0579a0be41bbe65d3637607715c0f87728a838", + "reference": "ff0579a0be41bbe65d3637607715c0f87728a838", "shasum": "" }, + "require": { + "php": ">=7.2" + }, + "require-dev": { + "phpstan/phpstan": "^0.12.8" + }, "type": "library", "autoload": { "classmap": [ - "./" + "./src" ] }, + "notification-url": "https://packagist.org/downloads/", "license": [ "LGPL-3.0" ], "description": "Standard library files required by PocketMine-MP and related projects", - "support": { - "source": "https://github.com/pmmp/SPL/tree/0.3.3", - "issues": "https://github.com/pmmp/SPL/issues" - }, - "time": "2019-10-28T11:41:20+00:00" + "time": "2020-01-31T16:18:03+00:00" + } + ], + "packages-dev": [ + { + "name": "irstea/phpunit-shim", + "version": "8.5.2", + "source": { + "type": "git", + "url": "https://gitlab.irstea.fr/pole-is/tools/phpunit-shim.git", + "reference": "39b6155954d6caec1110a9e78582c4816ab247bc" + }, + "require": { + "ext-dom": "*", + "ext-json": "*", + "ext-libxml": "*", + "ext-mbstring": "*", + "ext-xml": "*", + "ext-xmlwriter": "*", + "php": "^7.2" + }, + "replace": { + "phpunit/phpunit": "self.version" + }, + "suggest": { + "ext-soap": "*", + "ext-xdebug": "*" + }, + "bin": [ + "phpunit" + ], + "type": "library", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Shim repository for phpunit/phpunit", + "homepage": "https://phpunit.de/", + "keywords": [ + "phpunit", + "shim", + "testing", + "xunit" + ], + "time": "2020-01-09T03:20:20+00:00" + }, + { + "name": "phpstan/phpstan", + "version": "0.12.9", + "source": { + "type": "git", + "url": "https://github.com/phpstan/phpstan.git", + "reference": "297cb2458a96ea96d5e9d6ef38f1b7305c071f32" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/297cb2458a96ea96d5e9d6ef38f1b7305c071f32", + "reference": "297cb2458a96ea96d5e9d6ef38f1b7305c071f32", + "shasum": "" + }, + "require": { + "php": "^7.1" + }, + "bin": [ + "phpstan", + "phpstan.phar" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "0.12-dev" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHPStan - PHP Static Analysis Tool", + "time": "2020-02-04T22:30:27+00:00" + }, + { + "name": "phpstan/phpstan-phpunit", + "version": "0.12.6", + "source": { + "type": "git", + "url": "https://github.com/phpstan/phpstan-phpunit.git", + "reference": "26394996368b6d033d012547d3197f4e07e23021" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/phpstan-phpunit/zipball/26394996368b6d033d012547d3197f4e07e23021", + "reference": "26394996368b6d033d012547d3197f4e07e23021", + "shasum": "" + }, + "require": { + "php": "~7.1", + "phpstan/phpstan": "^0.12.4" + }, + "conflict": { + "phpunit/phpunit": "<7.0" + }, + "require-dev": { + "consistence/coding-standard": "^3.5", + "dealerdirect/phpcodesniffer-composer-installer": "^0.4.4", + "ergebnis/composer-normalize": "^2.0.2", + "jakub-onderka/php-parallel-lint": "^1.0", + "phing/phing": "^2.16.0", + "phpstan/phpstan-strict-rules": "^0.12", + "phpunit/phpunit": "^7.0", + "satooshi/php-coveralls": "^1.0", + "slevomat/coding-standard": "^4.7.2" + }, + "type": "phpstan-extension", + "extra": { + "branch-alias": { + "dev-master": "0.12-dev" + }, + "phpstan": { + "includes": [ + "extension.neon", + "rules.neon" + ] + } + }, + "autoload": { + "psr-4": { + "PHPStan\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHPUnit extensions and rules for PHPStan", + "time": "2020-01-10T12:07:21+00:00" + }, + { + "name": "phpstan/phpstan-strict-rules", + "version": "0.12.2", + "source": { + "type": "git", + "url": "https://github.com/phpstan/phpstan-strict-rules.git", + "reference": "a670a59aff7cf96f75d21b974860ada10e25b2ee" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/phpstan-strict-rules/zipball/a670a59aff7cf96f75d21b974860ada10e25b2ee", + "reference": "a670a59aff7cf96f75d21b974860ada10e25b2ee", + "shasum": "" + }, + "require": { + "php": "~7.1", + "phpstan/phpstan": "^0.12.6" + }, + "require-dev": { + "consistence/coding-standard": "^3.0.1", + "dealerdirect/phpcodesniffer-composer-installer": "^0.4.4", + "ergebnis/composer-normalize": "^2.0.2", + "jakub-onderka/php-parallel-lint": "^1.0", + "phing/phing": "^2.16.0", + "phpstan/phpstan-phpunit": "^0.12", + "phpunit/phpunit": "^7.0", + "slevomat/coding-standard": "^4.5.2" + }, + "type": "phpstan-extension", + "extra": { + "branch-alias": { + "dev-master": "0.12-dev" + }, + "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", + "time": "2020-01-20T13:08:52+00:00" } ], - "packages-dev": [], "aliases": [], "minimum-stability": "stable", "stability-flags": { diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 3880ad102f..8bfdcfc297 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -1,42 +1,87 @@ includes: - - tests/phpstan/configs/debug-const-checks.neon + - tests/phpstan/configs/com-dotnet-magic.neon + - tests/phpstan/configs/custom-leveldb.neon - tests/phpstan/configs/gc-hacks.neon - - tests/phpstan/configs/optional-com-dotnet.neon - - tests/phpstan/configs/optional-leveldb.neon + - tests/phpstan/configs/php-bugs.neon - tests/phpstan/configs/phpstan-bugs.neon + - tests/phpstan/configs/phpunit-wiring-tests.neon - tests/phpstan/configs/pthreads-bugs.neon - tests/phpstan/configs/runtime-type-checks.neon + - vendor/phpstan/phpstan-phpunit/extension.neon + - vendor/phpstan/phpstan-phpunit/rules.neon + - vendor/phpstan/phpstan-strict-rules/rules.neon parameters: - level: 5 + level: 6 autoload_files: - tests/phpstan/bootstrap.php - src/pocketmine/PocketMine.php + - build/make-release.php + - build/server-phar.php + - vendor/irstea/phpunit-shim/phpunit paths: - src + - build/make-release.php + - build/server-phar.php + - tests/phpunit + dynamicConstantNames: + - pocketmine\IS_DEVELOPMENT_BUILD + - pocketmine\DEBUG + stubFiles: + - tests/phpstan/stubs/pthreads.stub + - tests/phpstan/stubs/chunkutils.stub reportUnmatchedIgnoredErrors: false #no other way to silence platform-specific non-warnings ignoreErrors: + - + message: "#^Instanceof between pocketmine\\\\plugin\\\\PluginManager and pocketmine\\\\plugin\\\\PluginManager will always evaluate to true\\.$#" + count: 1 + path: src/pocketmine/CrashDump.php + + - + message: "#^pocketmine\\\\Player\\:\\:__construct\\(\\) does not call parent constructor from pocketmine\\\\entity\\\\Human\\.$#" + count: 1 + path: src/pocketmine/Player.php + - message: "#^Cannot instantiate interface pocketmine\\\\level\\\\format\\\\io\\\\LevelProvider\\.$#" count: 1 path: src/pocketmine/Server.php + - + message: "#^Instanceof between pocketmine\\\\plugin\\\\PluginManager and pocketmine\\\\plugin\\\\PluginManager will always evaluate to true\\.$#" + count: 1 + path: src/pocketmine/Server.php + + - + message: "#^Instanceof between pocketmine\\\\scheduler\\\\AsyncPool and pocketmine\\\\scheduler\\\\AsyncPool will always evaluate to true\\.$#" + count: 1 + path: src/pocketmine/Server.php + + - + message: "#^Instanceof between pocketmine\\\\command\\\\CommandReader and pocketmine\\\\command\\\\CommandReader will always evaluate to true\\.$#" + count: 1 + path: src/pocketmine/Server.php + + - + message: "#^Instanceof between pocketmine\\\\network\\\\Network and pocketmine\\\\network\\\\Network will always evaluate to true\\.$#" + count: 1 + path: src/pocketmine/Server.php + + - + message: "#^pocketmine\\\\block\\\\[A-Za-z\\d]+\\:\\:__construct\\(\\) does not call parent constructor from pocketmine\\\\block\\\\Block\\.$#" + path: src/pocketmine/block + + - + message: "#^pocketmine\\\\block\\\\Block\\:\\:__construct\\(\\) does not call parent constructor from pocketmine\\\\level\\\\Position\\.$#" + count: 1 + path: src/pocketmine/block/Block.php + - message: "#^Call to an undefined method pocketmine\\\\command\\\\CommandSender\\:\\:teleport\\(\\)\\.$#" count: 1 path: src/pocketmine/command/defaults/TeleportCommand.php # comment: "not actually possible, but high cost to fix warning" - - - message: "#^Array \\(array\\\\) does not accept pocketmine\\\\entity\\\\Entity\\.$#" - count: 2 - path: src/pocketmine/entity/Entity.php - - - - message: "#^Invalid array key type pocketmine\\\\entity\\\\Entity\\.$#" - count: 1 - path: src/pocketmine/entity/Entity.php - - message: "#^Method pocketmine\\\\event\\\\entity\\\\EntityDeathEvent\\:\\:getEntity\\(\\) should return pocketmine\\\\entity\\\\Living but returns pocketmine\\\\entity\\\\Entity\\.$#" count: 1 @@ -72,6 +117,31 @@ parameters: count: 1 path: src/pocketmine/event/entity/ProjectileLaunchEvent.php + - + message: "#^pocketmine\\\\inventory\\\\DoubleChestInventory\\:\\:__construct\\(\\) does not call parent constructor from pocketmine\\\\inventory\\\\ChestInventory\\.$#" + count: 1 + path: src/pocketmine/inventory/DoubleChestInventory.php + + - + message: "#^pocketmine\\\\inventory\\\\EnderChestInventory\\:\\:__construct\\(\\) does not call parent constructor from pocketmine\\\\inventory\\\\ChestInventory\\.$#" + count: 1 + path: src/pocketmine/inventory/EnderChestInventory.php + + - + message: "#^pocketmine\\\\item\\\\GoldenAppleEnchanted\\:\\:__construct\\(\\) does not call parent constructor from pocketmine\\\\item\\\\GoldenApple\\.$#" + count: 1 + path: src/pocketmine/item/GoldenAppleEnchanted.php + + - + message: "#^pocketmine\\\\item\\\\WrittenBook\\:\\:__construct\\(\\) does not call parent constructor from pocketmine\\\\item\\\\WritableBook\\.$#" + count: 1 + path: src/pocketmine/item/WrittenBook.php + + - + message: "#^Variable property access on \\$this\\(pocketmine\\\\level\\\\generator\\\\PopulationTask\\)\\.$#" + count: 4 + path: src/pocketmine/level/generator/PopulationTask.php + - message: "#^Constructor of class pocketmine\\\\level\\\\generator\\\\hell\\\\Nether has an unused parameter \\$options\\.$#" count: 1 @@ -83,9 +153,9 @@ parameters: path: src/pocketmine/level/generator/normal/Normal.php - - message: "#^Used constant pocketmine\\\\RESOURCE_PATH not found\\.$#" + message: "#^Variable method call on pocketmine\\\\event\\\\Listener\\.$#" count: 1 - path: src/pocketmine/network/mcpe/protocol/StartGamePacket.php + path: src/pocketmine/plugin/MethodEventExecutor.php - message: "#^Constructor of class pocketmine\\\\scheduler\\\\TaskScheduler has an unused parameter \\$logger\\.$#" @@ -104,18 +174,10 @@ parameters: message: "#^Constant pocketmine\\\\GIT_COMMIT not found\\.$#" path: src - - - message: "#^Constant pocketmine\\\\PATH not found\\.$#" - path: src - - message: "#^Constant pocketmine\\\\PLUGIN_PATH not found\\.$#" path: src - - - message: "#^Constant pocketmine\\\\RESOURCE_PATH not found\\.$#" - path: src - - message: "#^Constant pocketmine\\\\START_TIME not found\\.$#" path: src diff --git a/src/pocketmine/Achievement.php b/src/pocketmine/Achievement.php index 41049f4c59..0e732879a4 100644 --- a/src/pocketmine/Achievement.php +++ b/src/pocketmine/Achievement.php @@ -30,9 +30,7 @@ use pocketmine\utils\TextFormat; * Handles the achievement list and a bit more */ abstract class Achievement{ - /** - * @var array[] - */ + /** @var array[] */ public static $list = [ /*"openInventory" => array( "name" => "Taking Inventory", @@ -106,13 +104,6 @@ abstract class Achievement{ ]; - - /** - * @param Player $player - * @param string $achievementId - * - * @return bool - */ public static function broadcast(Player $player, string $achievementId) : bool{ if(isset(Achievement::$list[$achievementId])){ $translation = new TranslationContainer("chat.type.achievement", [$player->getDisplayName(), TextFormat::GREEN . Achievement::$list[$achievementId]["name"] . TextFormat::RESET]); @@ -129,11 +120,7 @@ abstract class Achievement{ } /** - * @param string $achievementId - * @param string $achievementName - * @param array $requires - * - * @return bool + * @param string[] $requires */ public static function add(string $achievementId, string $achievementName, array $requires = []) : bool{ if(!isset(Achievement::$list[$achievementId])){ diff --git a/src/pocketmine/Collectable.php b/src/pocketmine/Collectable.php index 4dde44cb50..238cfcfe6e 100644 --- a/src/pocketmine/Collectable.php +++ b/src/pocketmine/Collectable.php @@ -25,12 +25,16 @@ namespace pocketmine; abstract class Collectable extends \Threaded{ + /** @var bool */ private $isGarbage = false; public function isGarbage() : bool{ return $this->isGarbage; } + /** + * @return void + */ public function setGarbage(){ $this->isGarbage = true; } diff --git a/src/pocketmine/CoreConstants.php b/src/pocketmine/CoreConstants.php new file mode 100644 index 0000000000..7dd0e50a47 --- /dev/null +++ b/src/pocketmine/CoreConstants.php @@ -0,0 +1,33 @@ + + */ private $data = []; /** @var string */ private $encodedData = ""; @@ -134,15 +140,22 @@ class CrashDump{ return $this->path; } + /** + * @return string + */ public function getEncodedData(){ return $this->encodedData; } + /** + * @return mixed[] + * @phpstan-return array + */ public function getData() : array{ return $this->data; } - private function encodeData(){ + private function encodeData() : void{ $this->addLine(); $this->addLine("----------------------REPORT THE DATA BELOW THIS LINE-----------------------"); $this->addLine(); @@ -158,7 +171,7 @@ class CrashDump{ $this->addLine("===END CRASH DUMP==="); } - private function pluginsData(){ + private function pluginsData() : void{ if($this->server->getPluginManager() instanceof PluginManager){ $this->addLine(); $this->addLine("Loaded plugins:"); @@ -182,7 +195,7 @@ class CrashDump{ } } - private function extraData(){ + private function extraData() : void{ global $argv; if($this->server->getProperty("auto-report.send-settings", true) !== false){ @@ -209,7 +222,7 @@ class CrashDump{ } } - private function baseCrash(){ + private function baseCrash() : void{ global $lastExceptionError, $lastError; if(isset($lastExceptionError)){ @@ -317,7 +330,7 @@ class CrashDump{ return false; } - private function generalData(){ + private function generalData() : void{ $version = new VersionString(\pocketmine\BASE_VERSION, \pocketmine\IS_DEVELOPMENT_BUILD, \pocketmine\BUILD_NUMBER); $this->data["general"] = []; $this->data["general"]["name"] = $this->server->getName(); @@ -340,10 +353,20 @@ class CrashDump{ $this->addLine("OS : " . PHP_OS . ", " . Utils::getOS()); } + /** + * @param string $line + * + * @return void + */ public function addLine($line = ""){ fwrite($this->fp, $line . PHP_EOL); } + /** + * @param string $str + * + * @return void + */ public function add($str){ fwrite($this->fp, $str); } diff --git a/src/pocketmine/IPlayer.php b/src/pocketmine/IPlayer.php index bc0e8bc9dc..705c5471d0 100644 --- a/src/pocketmine/IPlayer.php +++ b/src/pocketmine/IPlayer.php @@ -27,33 +27,21 @@ use pocketmine\permission\ServerOperator; interface IPlayer extends ServerOperator{ - /** - * @return bool - */ public function isOnline() : bool; - /** - * @return string - */ public function getName() : string; - /** - * @return bool - */ public function isBanned() : bool; /** - * @param bool $banned + * @return void */ public function setBanned(bool $banned); - /** - * @return bool - */ public function isWhitelisted() : bool; /** - * @param bool $value + * @return void */ public function setWhitelisted(bool $value); @@ -72,9 +60,6 @@ interface IPlayer extends ServerOperator{ */ public function getLastPlayed(); - /** - * @return bool - */ public function hasPlayedBefore() : bool; } diff --git a/src/pocketmine/MemoryManager.php b/src/pocketmine/MemoryManager.php index 77ecca9d4e..6d2206063e 100644 --- a/src/pocketmine/MemoryManager.php +++ b/src/pocketmine/MemoryManager.php @@ -116,7 +116,7 @@ class MemoryManager{ $this->init(); } - private function init(){ + private function init() : void{ $this->memoryLimit = ((int) $this->server->getProperty("memory.main-limit", 0)) * 1024 * 1024; $defaultMemory = 1024; @@ -170,38 +170,25 @@ class MemoryManager{ gc_enable(); } - /** - * @return bool - */ public function isLowMemory() : bool{ return $this->lowMemory; } - /** - * @return bool - */ public function canUseChunkCache() : bool{ return !$this->lowMemory or !$this->lowMemDisableChunkCache; } /** * Returns the allowed chunk radius based on the current memory usage. - * - * @param int $distance - * - * @return int */ public function getViewDistance(int $distance) : int{ - return ($this->lowMemory and $this->lowMemChunkRadiusOverride > 0) ? (int) min($this->lowMemChunkRadiusOverride, $distance) : $distance; + return ($this->lowMemory and $this->lowMemChunkRadiusOverride > 0) ? min($this->lowMemChunkRadiusOverride, $distance) : $distance; } /** * Triggers garbage collection and cache cleanup to try and free memory. * - * @param int $memory - * @param int $limit - * @param bool $global - * @param int $triggerCount + * @return void */ public function trigger(int $memory, int $limit, bool $global = false, int $triggerCount = 0){ $this->server->getLogger()->debug(sprintf("[Memory Manager] %sLow memory triggered, limit %gMB, using %gMB", @@ -231,6 +218,8 @@ class MemoryManager{ /** * Called every tick to update the memory manager state. + * + * @return void */ public function check(){ Timings::$memoryManagerTimer->startTiming(); @@ -269,9 +258,6 @@ class MemoryManager{ Timings::$memoryManagerTimer->stopTiming(); } - /** - * @return int - */ public function triggerGarbageCollector() : int{ Timings::$garbageCollectorTimer->startTiming(); @@ -295,9 +281,7 @@ class MemoryManager{ /** * Dumps the server memory into the specified output folder. * - * @param string $outputFolder - * @param int $maxNesting - * @param int $maxStringSize + * @return void */ public function dumpServerMemory(string $outputFolder, int $maxNesting, int $maxStringSize){ $this->server->getLogger()->notice("[Dump] After the memory dump is done, the server might crash"); @@ -315,11 +299,8 @@ class MemoryManager{ * Static memory dumper accessible from any thread. * * @param mixed $startingObject - * @param string $outputFolder - * @param int $maxNesting - * @param int $maxStringSize - * @param \Logger $logger * + * @return void * @throws \ReflectionException */ public static function dumpMemory($startingObject, string $outputFolder, int $maxNesting, int $maxStringSize, \Logger $logger){ @@ -357,7 +338,7 @@ class MemoryManager{ } $staticCount++; - self::continueDump($property->getValue(), $staticProperties[$className][$property->getName()], $objects, $refCounts, 0, $maxNesting, $maxStringSize); + $staticProperties[$className][$property->getName()] = self::continueDump($property->getValue(), $objects, $refCounts, 0, $maxNesting, $maxStringSize); } if(count($staticProperties[$className]) === 0){ @@ -390,14 +371,14 @@ class MemoryManager{ } $globalCount++; - self::continueDump($value, $globalVariables[$varName], $objects, $refCounts, 0, $maxNesting, $maxStringSize); + $globalVariables[$varName] = self::continueDump($value, $objects, $refCounts, 0, $maxNesting, $maxStringSize); } file_put_contents($outputFolder . "/globalVariables.js", json_encode($globalVariables, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)); $logger->info("[Dump] Wrote $globalCount global variables"); } - self::continueDump($startingObject, $data, $objects, $refCounts, 0, $maxNesting, $maxStringSize); + $data = self::continueDump($startingObject, $objects, $refCounts, 0, $maxNesting, $maxStringSize); do{ $continue = false; @@ -445,14 +426,13 @@ class MemoryManager{ $property->setAccessible(true); } - self::continueDump($property->getValue($object), $info["properties"][$name], $objects, $refCounts, 0, $maxNesting, $maxStringSize); + $info["properties"][$name] = self::continueDump($property->getValue($object), $objects, $refCounts, 0, $maxNesting, $maxStringSize); } } fwrite($obData, "$hash@$className: " . json_encode($info, JSON_UNESCAPED_SLASHES) . "\n"); } - }while($continue); $logger->info("[Dump] Wrote " . count($objects) . " objects"); @@ -473,17 +453,14 @@ class MemoryManager{ /** * @param mixed $from - * @param mixed &$data - * @param object[] &$objects - * @param int[] &$refCounts - * @param int $recursion - * @param int $maxNesting - * @param int $maxStringSize + * @param object[] $objects reference parameter + * @param int[] $refCounts reference parameter + * + * @return mixed */ - private static function continueDump($from, &$data, array &$objects, array &$refCounts, int $recursion, int $maxNesting, int $maxStringSize){ + private static function continueDump($from, array &$objects, array &$refCounts, int $recursion, int $maxNesting, int $maxStringSize){ if($maxNesting <= 0){ - $data = "(error) NESTING LIMIT REACHED"; - return; + return "(error) NESTING LIMIT REACHED"; } --$maxNesting; @@ -499,12 +476,11 @@ class MemoryManager{ $data = "(object) $hash@" . get_class($from); }elseif(is_array($from)){ if($recursion >= 5){ - $data = "(error) ARRAY RECURSION LIMIT REACHED"; - return; + return "(error) ARRAY RECURSION LIMIT REACHED"; } $data = []; foreach($from as $key => $value){ - self::continueDump($value, $data[$key], $objects, $refCounts, $recursion + 1, $maxNesting, $maxStringSize); + $data[$key] = self::continueDump($value, $objects, $refCounts, $recursion + 1, $maxNesting, $maxStringSize); } }elseif(is_string($from)){ $data = "(string) len(" . strlen($from) . ") " . substr(Utils::printable($from), 0, $maxStringSize); @@ -513,5 +489,7 @@ class MemoryManager{ }else{ $data = $from; } + + return $data; } } diff --git a/src/pocketmine/OfflinePlayer.php b/src/pocketmine/OfflinePlayer.php index 0e631ee626..d8dbe23061 100644 --- a/src/pocketmine/OfflinePlayer.php +++ b/src/pocketmine/OfflinePlayer.php @@ -37,10 +37,6 @@ class OfflinePlayer implements IPlayer, Metadatable{ /** @var CompoundTag|null */ private $namedtag = null; - /** - * @param Server $server - * @param string $name - */ public function __construct(Server $server, string $name){ $this->server = $server; $this->name = $name; @@ -57,6 +53,9 @@ class OfflinePlayer implements IPlayer, Metadatable{ return $this->name; } + /** + * @return Server + */ public function getServer(){ return $this->server; } diff --git a/src/pocketmine/Player.php b/src/pocketmine/Player.php index 3329720ad7..c6672be004 100644 --- a/src/pocketmine/Player.php +++ b/src/pocketmine/Player.php @@ -202,7 +202,6 @@ use const M_PI; use const M_SQRT3; use const PHP_INT_MAX; - /** * Main class that handles networking, recovery, and packet sending to the server part */ @@ -216,10 +215,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Validates the given username. - * - * @param string $name - * - * @return bool */ public static function isValidUserName(?string $name) : bool{ if($name === null){ @@ -231,7 +226,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ return $lname !== "rcon" and $lname !== "console" and $len >= 1 and $len <= 16 and preg_match("/[^A-Za-z0-9_ ]/", $name) === 0; } - /** @var SourceInterface */ protected $interface; @@ -258,7 +252,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ */ protected $lastPingMeasure = 1; - /** @var float */ public $creationTime = 0; @@ -282,6 +275,7 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** @var string */ protected $xuid = ""; + /** @var int */ protected $windowCnt = 2; /** @var int[] */ protected $windows = []; @@ -292,7 +286,7 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** @var PlayerCursorInventory */ protected $cursorInventory; /** @var CraftingGrid */ - protected $craftingGrid = null; + protected $craftingGrid; /** @var CraftingTransaction|null */ protected $craftingTransaction = null; @@ -354,7 +348,7 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ protected $flying = false; /** @var PermissibleBase */ - private $perm = null; + private $perm; /** @var int|null */ protected $lineHeight = null; @@ -431,8 +425,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * If the player is logged into Xbox Live, returns their Xbox user ID (XUID) as a string. Returns an empty string if * the player is not logged into Xbox Live. - * - * @return string */ public function getXuid() : string{ return $this->xuid; @@ -452,8 +444,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ * (In the olden days this method used to return a fake UUID computed by the server, which was used by plugins such * as SimpleAuth for authentication. This is NOT SAFE anymore as this UUID is now what was given by the client, NOT * a server-computed UUID.) - * - * @return UUID|null */ public function getUniqueId() : ?UUID{ return parent::getUniqueId(); @@ -475,6 +465,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ return $this->playedBefore; } + /** + * @return void + */ public function setAllowFlight(bool $value){ $this->allowFlight = $value; $this->sendSettings(); @@ -484,6 +477,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ return $this->allowFlight; } + /** + * @return void + */ public function setFlying(bool $value){ if($this->flying !== $value){ $this->flying = $value; @@ -496,6 +492,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ return $this->flying; } + /** + * @return void + */ public function setAutoJump(bool $value){ $this->autoJump = $value; $this->sendSettings(); @@ -509,13 +508,13 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ return $this->allowMovementCheats; } + /** + * @return void + */ public function setAllowMovementCheats(bool $value = true){ $this->allowMovementCheats = $value; } - /** - * @param Player $player - */ public function spawnTo(Player $player) : void{ if($this->spawned and $player->spawned and $this->isAlive() and $player->isAlive() and $player->getLevel() === $this->level and $player->canSee($this) and !$this->isSpectator()){ parent::spawnTo($player); @@ -529,15 +528,12 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ return $this->server; } - /** - * @return bool - */ public function getRemoveFormat() : bool{ return $this->removeFormat; } /** - * @param bool $remove + * @return void */ public function setRemoveFormat(bool $remove = true){ $this->removeFormat = $remove; @@ -554,17 +550,12 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ $this->lineHeight = $height; } - /** - * @param Player $player - * - * @return bool - */ public function canSee(Player $player) : bool{ return !isset($this->hiddenPlayers[$player->getRawUniqueId()]); } /** - * @param Player $player + * @return void */ public function hidePlayer(Player $player){ if($player === $this){ @@ -575,7 +566,7 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ } /** - * @param Player $player + * @return void */ public function showPlayer(Player $player){ if($player === $this){ @@ -604,6 +595,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ return $this->viewDistance; } + /** + * @return void + */ public function setViewDistance(int $distance){ $this->viewDistance = $this->server->getAllowedViewDistance($distance); @@ -618,22 +612,16 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ $this->server->getLogger()->debug("Setting view distance for " . $this->getName() . " to " . $this->viewDistance . " (requested " . $distance . ")"); } - /** - * @return bool - */ public function isOnline() : bool{ return $this->isConnected() and $this->loggedIn; } - /** - * @return bool - */ public function isOp() : bool{ return $this->server->isOp($this->getName()); } /** - * @param bool $value + * @return void */ public function setOp(bool $value){ if($value === $this->isOp()){ @@ -651,8 +639,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * @param permission\Permission|string $name - * - * @return bool */ public function isPermissionSet($name) : bool{ return $this->perm->isPermissionSet($name); @@ -661,8 +647,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * @param permission\Permission|string $name * - * @return bool - * * @throws \InvalidStateException if the player is closed */ public function hasPermission($name) : bool{ @@ -672,19 +656,12 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ return $this->perm->hasPermission($name); } - /** - * @param Plugin $plugin - * @param string $name - * @param bool $value - * - * @return PermissionAttachment - */ public function addAttachment(Plugin $plugin, string $name = null, bool $value = null) : PermissionAttachment{ return $this->perm->addAttachment($plugin, $name, $value); } /** - * @param PermissionAttachment $attachment + * @return void */ public function removeAttachment(PermissionAttachment $attachment){ $this->perm->removeAttachment($attachment); @@ -720,6 +697,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ return $this->perm->getEffectivePermissions(); } + /** + * @return void + */ public function sendCommandData(){ $pk = new AvailableCommandsPacket(); foreach($this->server->getCommandMap()->getCommands() as $name => $command){ @@ -741,7 +721,7 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ $data->overloads[0][0] = $parameter; $aliases = $command->getAliases(); - if(!empty($aliases)){ + if(count($aliases) > 0){ if(!in_array($data->commandName, $aliases, true)){ //work around a client bug which makes the original name not show when aliases are used $aliases[] = $data->commandName; @@ -758,11 +738,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ } - /** - * @param SourceInterface $interface - * @param string $ip - * @param int $port - */ public function __construct(SourceInterface $interface, string $ip, int $port){ $this->interface = $interface; $this->perm = new PermissibleBase($this); @@ -784,39 +759,30 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ $this->sessionAdapter = new PlayerNetworkSessionAdapter($this->server, $this); } - /** - * @return bool - */ public function isConnected() : bool{ return $this->sessionAdapter !== null; } /** * Gets the username - * @return string */ public function getName() : string{ return $this->username; } - /** - * @return string - */ public function getLowerCaseName() : string{ return $this->iusername; } /** * Returns the "friendly" display name of this player to use in the chat. - * - * @return string */ public function getDisplayName() : string{ return $this->displayName; } /** - * @param string $name + * @return void */ public function setDisplayName(string $name){ $this->displayName = $name; @@ -827,7 +793,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Returns the player's locale, e.g. en_US. - * @return string */ public function getLocale() : string{ return $this->locale; @@ -836,12 +801,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Called when a player changes their skin. * Plugin developers should not use this, use setSkin() and sendSkin() instead. - * - * @param Skin $skin - * @param string $newSkinName - * @param string $oldSkinName - * - * @return bool */ public function changeSkin(Skin $skin, string $newSkinName, string $oldSkinName) : bool{ if(!$skin->isValid()){ @@ -872,16 +831,11 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Gets the player IP address - * - * @return string */ public function getAddress() : string{ return $this->ip; } - /** - * @return int - */ public function getPort() : int{ return $this->port; } @@ -889,8 +843,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Returns the last measured latency for this player, in milliseconds. This is measured automatically and reported * back by the network interface. - * - * @return int */ public function getPing() : int{ return $this->lastPingMeasure; @@ -901,15 +853,12 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ * * @internal Plugins should not use this method. * - * @param int $pingMS + * @return void */ public function updatePing(int $pingMS){ $this->lastPingMeasure = $pingMS; } - /** - * @return Position - */ public function getNextPosition() : Position{ return $this->newPosition !== null ? Position::fromObject($this->newPosition, $this->level) : $this->getPosition(); } @@ -920,12 +869,14 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Returns whether the player is currently using an item (right-click and hold). - * @return bool */ public function isUsingItem() : bool{ return $this->getGenericFlag(self::DATA_FLAG_ACTION) and $this->startAction > -1; } + /** + * @return void + */ public function setUsingItem(bool $value){ $this->startAction = $value ? $this->server->getTick() : -1; $this->setGenericFlag(self::DATA_FLAG_ACTION, $value); @@ -934,8 +885,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Returns how long the player has been using their currently-held item for. Used for determining arrow shoot force * for bows. - * - * @return int */ public function getItemUseDuration() : int{ return $this->startAction === -1 ? -1 : ($this->server->getTick() - $this->startAction); @@ -943,10 +892,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Returns whether the player has a cooldown period left before it can use the given item again. - * - * @param Item $item - * - * @return bool */ public function hasItemCooldown(Item $item) : bool{ $this->checkItemCooldowns(); @@ -955,8 +900,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Resets the player's cooldown time for the given item back to the maximum. - * - * @param Item $item */ public function resetItemCooldown(Item $item) : void{ $ticks = $item->getCooldownTicks(); @@ -995,6 +938,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ return false; } + /** + * @return void + */ protected function unloadChunk(int $x, int $z, Level $level = null){ $level = $level ?? $this->level; $index = Level::chunkHash($x, $z); @@ -1011,6 +957,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ unset($this->loadQueue[$index]); } + /** + * @return void + */ public function sendChunk(int $x, int $z, BatchPacket $payload){ if(!$this->isConnected()){ return; @@ -1033,6 +982,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ } } + /** + * @return void + */ protected function sendNextChunk(){ if(!$this->isConnected()){ return; @@ -1067,6 +1019,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ Timings::$playerChunkSendTimer->stopTiming(); } + /** + * @return void + */ public function doFirstSpawn(){ if($this->spawned){ return; //avoid player spawning twice (this can only happen on 3.x with a custom malicious client) @@ -1116,6 +1071,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ } } + /** + * @return void + */ protected function sendRespawnPacket(Vector3 $pos, int $respawnState = RespawnPacket::SEARCHING_FOR_SPAWN){ $pk = new RespawnPacket(); $pk->position = $pos->add(0, $this->baseOffset, 0); @@ -1167,7 +1125,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ } unset($unloadChunks[$index]); - /* Bottom left quadrant */ if(!isset($this->usedChunks[$index = Level::chunkHash($centerX - $x - 1, $centerZ - $z - 1)]) or $this->usedChunks[$index] === false){ $newOrder[$index] = true; @@ -1208,7 +1165,7 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ } $this->loadQueue = $newOrder; - if(!empty($this->loadQueue) or !empty($unloadChunks)){ + if(count($this->loadQueue) > 0 or count($unloadChunks) > 0){ $pk = new NetworkChunkPublisherUpdatePacket(); $pk->x = $this->getFloorX(); $pk->y = $this->getFloorY(); @@ -1233,9 +1190,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ } } - /** - * @return bool - */ public function hasValidSpawnPosition() : bool{ return $this->spawnPosition !== null and $this->spawnPosition->isValid(); } @@ -1245,6 +1199,8 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ * Position object * * @param Vector3|Position $pos + * + * @return void */ public function setSpawn(Vector3 $pos){ if(!($pos instanceof Position)){ @@ -1262,18 +1218,10 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ $this->dataPacket($pk); } - /** - * @return bool - */ public function isSleeping() : bool{ return $this->sleeping !== null; } - /** - * @param Vector3 $pos - * - * @return bool - */ public function sleepOn(Vector3 $pos) : bool{ if(!$this->isOnline()){ return false; @@ -1304,6 +1252,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ return true; } + /** + * @return void + */ public function stopSleep(){ if($this->sleeping instanceof Vector3){ $b = $this->level->getBlock($this->sleeping); @@ -1325,11 +1276,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ } } - /** - * @param string $achievementId - * - * @return bool - */ public function hasAchievement(string $achievementId) : bool{ if(!isset(Achievement::$list[$achievementId])){ return false; @@ -1338,11 +1284,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ return $this->achievements[$achievementId] ?? false; } - /** - * @param string $achievementId - * - * @return bool - */ public function awardAchievement(string $achievementId) : bool{ if(isset(Achievement::$list[$achievementId]) and !$this->hasAchievement($achievementId)){ foreach(Achievement::$list[$achievementId]["requires"] as $requirementId){ @@ -1366,7 +1307,7 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ } /** - * @param string $achievementId + * @return void */ public function removeAchievement(string $achievementId){ if($this->hasAchievement($achievementId)){ @@ -1374,9 +1315,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ } } - /** - * @return int - */ public function getGamemode() : int{ return $this->gamemode; } @@ -1388,10 +1326,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ * This function takes care of handling gamemodes known to MCPE (as of 1.1.0.3, that includes Survival, Creative and Adventure) * * TODO: remove this when Spectator Mode gets added properly to MCPE - * - * @param int $gamemode - * - * @return int */ public static function getClientFriendlyGamemode(int $gamemode) : int{ $gamemode &= 0x03; @@ -1405,10 +1339,7 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Sets the gamemode, and if needed, kicks the Player. * - * @param int $gm * @param bool $client if the client made this change in their GUI - * - * @return bool */ public function setGamemode(int $gm, bool $client = false) : bool{ if($gm < 0 or $gm > 3 or $this->gamemode === $gm){ @@ -1455,6 +1386,8 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * @internal * Sends the player's gamemode to the client. + * + * @return void */ public function sendGamemode(){ $pk = new SetPlayerGameTypePacket(); @@ -1464,6 +1397,8 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Sends all the option flags + * + * @return void */ public function sendSettings(){ $pk = new AdventureSettingsPacket(); @@ -1487,8 +1422,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ * in Adventure Mode. Supply the $literal parameter as true to force a literal Survival Mode check. * * @param bool $literal whether a literal check should be performed - * - * @return bool */ public function isSurvival(bool $literal = false) : bool{ if($literal){ @@ -1503,8 +1436,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ * in Spectator Mode. Supply the $literal parameter as true to force a literal Creative Mode check. * * @param bool $literal whether a literal check should be performed - * - * @return bool */ public function isCreative(bool $literal = false) : bool{ if($literal){ @@ -1519,8 +1450,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ * in Spectator Mode. Supply the $literal parameter as true to force a literal Adventure Mode check. * * @param bool $literal whether a literal check should be performed - * - * @return bool */ public function isAdventure(bool $literal = false) : bool{ if($literal){ @@ -1530,9 +1459,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ } } - /** - * @return bool - */ public function isSpectator() : bool{ return $this->gamemode === Player::SPECTATOR; } @@ -1569,6 +1495,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ return false; //currently has no server-side movement } + /** + * @return void + */ protected function checkNearEntities(){ foreach($this->level->getNearbyEntities($this->boundingBox->expandedCopy(1, 0.5, 1), $this) as $entity){ $entity->scheduleUpdate(); @@ -1581,6 +1510,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ } } + /** + * @return void + */ protected function processMovement(int $tickDiff){ if(!$this->isAlive() or !$this->spawned or $this->newPosition === null or $this->isSleeping()){ return; @@ -1723,6 +1655,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ } + /** + * @return void + */ public function sendAttributes(bool $sendAll = false){ $entries = $sendAll ? $this->attributeMap->getAll() : $this->attributeMap->needSend(); if(count($entries) > 0){ @@ -1828,6 +1763,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ $this->dataPacket($pk); } + /** + * @return void + */ public function checkNetwork(){ if(!$this->isOnline()){ return; @@ -1851,11 +1789,7 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Returns whether the player can interact with the specified position. This checks distance and direction. * - * @param Vector3 $pos - * @param float $maxDistance * @param float $maxDiff defaults to half of the 3D diagonal width of a block - * - * @return bool */ public function canInteract(Vector3 $pos, float $maxDistance, float $maxDiff = M_SQRT3 / 2) : bool{ $eyePos = $this->getPosition()->add(0, $this->getEyeHeight(), 0); @@ -1926,12 +1860,12 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ $skinData = new SkinData( $packet->clientData["SkinId"], - base64_decode($packet->clientData["SkinResourcePatch"] ?? ""), - new SkinImage($packet->clientData["SkinImageHeight"], $packet->clientData["SkinImageWidth"], base64_decode($packet->clientData["SkinData"])), + base64_decode($packet->clientData["SkinResourcePatch"] ?? "", true), + new SkinImage($packet->clientData["SkinImageHeight"], $packet->clientData["SkinImageWidth"], base64_decode($packet->clientData["SkinData"], true)), $animations, - new SkinImage($packet->clientData["CapeImageHeight"], $packet->clientData["CapeImageWidth"], base64_decode($packet->clientData["CapeData"] ?? "")), - base64_decode($packet->clientData["SkinGeometryData"] ?? ""), - base64_decode($packet->clientData["SkinAnimationData"] ?? ""), + new SkinImage($packet->clientData["CapeImageHeight"], $packet->clientData["CapeImageWidth"], base64_decode($packet->clientData["CapeData"] ?? "", true)), + base64_decode($packet->clientData["SkinGeometryData"] ?? "", true), + base64_decode($packet->clientData["SkinAnimationData"] ?? "", true), $packet->clientData["PremiumSkin"] ?? false, $packet->clientData["PersonaSkin"] ?? false, $packet->clientData["CapeOnClassicSkin"] ?? false, @@ -1976,6 +1910,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ return true; } + /** + * @return void + */ public function sendPlayStatus(int $status, bool $immediate = false){ $pk = new PlayStatusPacket(); $pk->status = $status; @@ -2019,6 +1956,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ $this->processLogin(); } + /** + * @return void + */ protected function processLogin(){ foreach($this->server->getLoggedInPlayers() as $p){ if($p !== $this and ($p->iusername === $this->iusername or $this->getUniqueId()->equals($p->getUniqueId()))){ @@ -2118,7 +2058,10 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ $pk = new ResourcePackStackPacket(); $manager = $this->server->getResourcePackManager(); $pk->resourcePackStack = $manager->getResourceStack(); - $pk->mustAccept = $manager->resourcePacksRequired(); + //we don't force here, because it doesn't have user-facing effects + //but it does have an annoying side-effect when true: it makes + //the client remove its own non-server-supplied resource packs. + $pk->mustAccept = false; $this->dataPacket($pk); break; case ResourcePackClientResponsePacket::STATUS_COMPLETED: @@ -2132,6 +2075,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ return true; } + /** + * @return void + */ protected function completeLoginSequence(){ /** @var float[] $pos */ $pos = $this->namedtag->getListTag("Pos")->getAllValues(); @@ -2226,10 +2172,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Sends a chat message as this player. If the message begins with a / (forward-slash) it will be treated * as a command. - * - * @param string $message - * - * @return bool */ public function chat(string $message) : bool{ if(!$this->spawned or !$this->isAlive()){ @@ -2329,10 +2271,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Don't expect much from this handler. Most of it is roughly hacked and duct-taped together. - * - * @param InventoryTransactionPacket $packet - * - * @return bool */ public function handleInventoryTransaction(InventoryTransactionPacket $packet) : bool{ if(!$this->spawned or !$this->isAlive()){ @@ -2938,8 +2876,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Drops an item on the ground in front of the player. Returns if the item drop was successful. * - * @param Item $item - * * @return bool if the item was dropped or if the item was null */ public function dropItem(Item $item) : bool{ @@ -3151,7 +3087,7 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Called when a packet is received from the client. This method will call DataPacketReceiveEvent. * - * @param DataPacket $packet + * @return void */ public function handleDataPacket(DataPacket $packet){ if($this->sessionAdapter !== null){ @@ -3161,10 +3097,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Batch a Data packet into the channel list to send at the end of the tick - * - * @param DataPacket $packet - * - * @return bool */ public function batchDataPacket(DataPacket $packet) : bool{ if(!$this->isConnected()){ @@ -3186,10 +3118,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ } /** - * @param DataPacket $packet - * @param bool $needACK - * @param bool $immediate - * * @return bool|int */ public function sendDataPacket(DataPacket $packet, bool $needACK = false, bool $immediate = false){ @@ -3225,9 +3153,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ } /** - * @param DataPacket $packet - * @param bool $needACK - * * @return bool|int */ public function dataPacket(DataPacket $packet, bool $needACK = false){ @@ -3235,9 +3160,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ } /** - * @param DataPacket $packet - * @param bool $needACK - * * @return bool|int */ public function directDataPacket(DataPacket $packet, bool $needACK = false){ @@ -3272,11 +3194,7 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Kicks a player from the server * - * @param string $reason - * @param bool $isAdmin * @param TextContainer|string $quitMessage - * - * @return bool */ public function kick(string $reason = "", bool $isAdmin = true, $quitMessage = null) : bool{ $ev = new PlayerKickEvent($this, $reason, $quitMessage ?? $this->getLeaveMessage()); @@ -3305,11 +3223,11 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ * @deprecated * @see Player::sendTitle() * - * @param string $title - * @param string $subtitle * @param int $fadeIn Duration in ticks for fade-in. If -1 is given, client-sided defaults will be used. * @param int $stay Duration in ticks to stay on screen for * @param int $fadeOut Duration in ticks for fade-out. + * + * @return void */ public function addTitle(string $title, string $subtitle = "", int $fadeIn = -1, int $stay = -1, int $fadeOut = -1){ $this->sendTitle($title, $subtitle, $fadeIn, $stay, $fadeOut); @@ -3336,7 +3254,7 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ * @deprecated * @see Player::sendSubTitle() * - * @param string $subtitle + * @return void */ public function addSubTitle(string $subtitle){ $this->sendSubTitle($subtitle); @@ -3355,7 +3273,7 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ * @deprecated * @see Player::sendActionBarMessage() * - * @param string $message + * @return void */ public function addActionBarMessage(string $message){ $this->sendActionBarMessage($message); @@ -3372,6 +3290,8 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Removes the title from the client's screen. + * + * @return void */ public function removeTitles(){ $pk = new SetTitlePacket(); @@ -3381,6 +3301,8 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Resets the title duration settings to defaults and removes any existing titles. + * + * @return void */ public function resetTitles(){ $pk = new SetTitlePacket(); @@ -3394,6 +3316,8 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ * @param int $fadeIn Title fade-in time in ticks. * @param int $stay Title stay time in ticks. * @param int $fadeOut Title fade-out time in ticks. + * + * @return void */ public function setTitleDuration(int $fadeIn, int $stay, int $fadeOut){ if($fadeIn >= 0 and $stay >= 0 and $fadeOut >= 0){ @@ -3409,8 +3333,7 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Internal function used for sending titles. * - * @param string $title - * @param int $type + * @return void */ protected function sendTitleText(string $title, int $type){ $pk = new SetTitlePacket(); @@ -3423,6 +3346,8 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ * Sends a direct chat message to a player * * @param TextContainer|string $message + * + * @return void */ public function sendMessage($message){ if($message instanceof TextContainer){ @@ -3440,8 +3365,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ } /** - * @param string $message * @param string[] $parameters + * + * @return void */ public function sendTranslation(string $message, array $parameters = []){ $pk = new TextPacket(); @@ -3465,8 +3391,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ * * TODO: add translation type popups * - * @param string $message * @param string $subtitle @deprecated + * + * @return void */ public function sendPopup(string $message, string $subtitle = ""){ $pk = new TextPacket(); @@ -3475,6 +3402,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ $this->dataPacket($pk); } + /** + * @return void + */ public function sendTip(string $message){ $pk = new TextPacket(); $pk->type = TextPacket::TYPE_TIP; @@ -3483,8 +3413,7 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ } /** - * @param string $sender - * @param string $message + * @return void */ public function sendWhisper(string $sender, string $message){ $pk = new TextPacket(); @@ -3496,8 +3425,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Sends a Form to the player, or queue to send it if a form is already open. - * - * @param Form $form */ public function sendForm(Form $form) : void{ $id = $this->formIdCounter++; @@ -3513,10 +3440,7 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ } /** - * @param int $formId * @param mixed $responseData - * - * @return bool */ public function onFormSubmit(int $formId, $responseData) : bool{ if(!isset($this->forms[$formId])){ @@ -3542,7 +3466,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ * * @param TextContainer|string $message Message to be broadcasted * @param string $reason Reason showed in console - * @param bool $notify */ final public function close($message = "", string $reason = "generic reason", bool $notify = true) : void{ if($this->isConnected() and !$this->closed){ @@ -3626,6 +3549,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ } } + /** + * @return mixed[] + */ public function __debugInfo(){ return []; } @@ -3642,6 +3568,8 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ * Handles player data saving * * @throws \InvalidStateException if the player is closed + * + * @return void */ public function save(){ if($this->closed){ @@ -3679,7 +3607,7 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ $this->namedtag->setInt("playerGameType", $this->gamemode); $this->namedtag->setLong("lastPlayed", (int) floor(microtime(true) * 1000)); - if($this->username != "" and $this->namedtag instanceof CompoundTag){ + if($this->username != ""){ $this->server->saveOfflinePlayerData($this->username, $this->namedtag); } } @@ -3803,6 +3731,11 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ return $result; } + /** + * @param Player[]|null $targets + * + * @return void + */ public function sendPosition(Vector3 $pos, float $yaw = null, float $pitch = null, int $mode = MovePlayerPacket::MODE_NORMAL, array $targets = null){ $yaw = $yaw ?? $this->yaw; $pitch = $pitch ?? $this->pitch; @@ -3854,6 +3787,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ return false; } + /** + * @return void + */ protected function addDefaultWindows(){ $this->addWindow($this->getInventory(), ContainerIds::INVENTORY, true); @@ -3875,9 +3811,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ return $this->craftingGrid; } - /** - * @param CraftingGrid $grid - */ public function setCraftingGrid(CraftingGrid $grid) : void{ $this->craftingGrid = $grid; } @@ -3904,10 +3837,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Returns the window ID which the inventory has for this player, or -1 if the window is not open to the player. - * - * @param Inventory $inventory - * - * @return int */ public function getWindowId(Inventory $inventory) : int{ return $this->windows[spl_object_hash($inventory)] ?? ContainerIds::NONE; @@ -3917,8 +3846,6 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ * Returns the inventory window open to the player with the specified window ID, or null if no window is open with * that ID. * - * @param int $windowId - * * @return Inventory|null */ public function getWindow(int $windowId){ @@ -3929,12 +3856,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ * Opens an inventory window to the player. Returns the ID of the created window, or the existing window ID if the * player is already viewing the specified inventory. * - * @param Inventory $inventory * @param int|null $forceId Forces a special ID for the window * @param bool $isPermanent Prevents the window being removed if true. * - * @return int - * * @throws \InvalidArgumentException if a forceID which is already in use is specified * @throws \InvalidStateException if trying to add a window without forceID when no slots are free */ @@ -3976,9 +3900,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ /** * Removes an inventory window from the player. * - * @param Inventory $inventory * @param bool $force Forces removal of permanent windows such as normal inventory, cursor * + * @return void * @throws \InvalidArgumentException if trying to remove a fixed inventory window without the `force` parameter as true */ public function removeWindow(Inventory $inventory, bool $force = false){ @@ -3998,6 +3922,8 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ * Removes all inventory windows from the player. By default this WILL NOT remove permanent windows. * * @param bool $removePermanentWindows Whether to remove permanent windows. + * + * @return void */ public function removeAllWindows(bool $removePermanentWindows = false){ foreach($this->windowIndex as $id => $window){ @@ -4009,6 +3935,9 @@ class Player extends Human implements CommandSender, ChunkLoader, IPlayer{ } } + /** + * @return void + */ protected function sendAllInventories(){ foreach($this->windowIndex as $id => $inventory){ $inventory->sendContents($this); diff --git a/src/pocketmine/PocketMine.php b/src/pocketmine/PocketMine.php index 10de566e79..d09b78d354 100644 --- a/src/pocketmine/PocketMine.php +++ b/src/pocketmine/PocketMine.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace pocketmine { + use pocketmine\utils\Git; use pocketmine\utils\Internet; use pocketmine\utils\MainLogger; use pocketmine\utils\Process; @@ -37,6 +38,10 @@ namespace pocketmine { const MIN_PHP_VERSION = "7.2.0"; + /** + * @param string $message + * @return void + */ function critical_error($message){ echo "[ERROR] $message" . PHP_EOL; } @@ -118,6 +123,10 @@ namespace pocketmine { return $messages; } + /** + * @param \Logger $logger + * @return void + */ function emit_performance_warnings(\Logger $logger){ if(extension_loaded("xdebug")){ $logger->warning("Xdebug extension is enabled. This has a major impact on performance."); @@ -133,6 +142,9 @@ namespace pocketmine { } } + /** + * @return void + */ function set_ini_entries(){ ini_set("allow_url_fopen", '1'); ini_set("display_errors", '1'); @@ -141,8 +153,11 @@ namespace pocketmine { ini_set('assert.exception', '1'); } + /** + * @return void + */ function server(){ - if(!empty($messages = check_platform_dependencies())){ + if(count($messages = check_platform_dependencies()) > 0){ echo PHP_EOL; $binary = version_compare(PHP_VERSION, "5.4") >= 0 ? PHP_BINARY : "unknown"; critical_error("Selected PHP binary ($binary) does not satisfy some requirements."); @@ -158,17 +173,11 @@ namespace pocketmine { error_reporting(-1); set_ini_entries(); - if(\Phar::running(true) !== ""){ - define('pocketmine\PATH', \Phar::running(true) . "/"); - }else{ - define('pocketmine\PATH', dirname(__FILE__, 3) . DIRECTORY_SEPARATOR); - } - $opts = getopt("", ["bootstrap:"]); if(isset($opts["bootstrap"])){ - $bootstrap = realpath($opts["bootstrap"]) ?: $opts["bootstrap"]; + $bootstrap = ($real = realpath($opts["bootstrap"])) !== false ? $real : $opts["bootstrap"]; }else{ - $bootstrap = \pocketmine\PATH . 'vendor/autoload.php'; + $bootstrap = dirname(__FILE__, 3) . '/vendor/autoload.php'; } define('pocketmine\COMPOSER_AUTOLOADER_PATH', $bootstrap); @@ -188,12 +197,7 @@ namespace pocketmine { $gitHash = str_repeat("00", 20); if(\Phar::running(true) === ""){ - if(Process::execute("git rev-parse HEAD", $out) === 0 and $out !== false and strlen($out = trim($out)) === 40){ - $gitHash = trim($out); - if(Process::execute("git diff --quiet") === 1 or Process::execute("git diff --cached --quiet") === 1){ //Locally-modified - $gitHash .= "-dirty"; - } - } + $gitHash = Git::getRepositoryStatePretty(\pocketmine\PATH); }else{ $phar = new \Phar(\Phar::running(false)); $meta = $phar->getMetadata(); @@ -204,8 +208,6 @@ namespace pocketmine { define('pocketmine\GIT_COMMIT', $gitHash); - define('pocketmine\RESOURCE_PATH', \pocketmine\PATH . 'src' . DIRECTORY_SEPARATOR . 'pocketmine' . DIRECTORY_SEPARATOR . 'resources' . DIRECTORY_SEPARATOR); - $opts = getopt("", ["data:", "plugins:", "no-wizard", "enable-ansi", "disable-ansi"]); define('pocketmine\DATA', isset($opts["data"]) ? $opts["data"] . DIRECTORY_SEPARATOR : realpath(getcwd()) . DIRECTORY_SEPARATOR); @@ -263,7 +265,6 @@ namespace pocketmine { //TODO: move this to a Server field define('pocketmine\START_TIME', microtime(true)); - ThreadManager::init(); /* * We now use the Composer autoloader, but this autoloader is still for loading plugins. diff --git a/src/pocketmine/Server.php b/src/pocketmine/Server.php index 6de2b0fb73..4fd6c24761 100644 --- a/src/pocketmine/Server.php +++ b/src/pocketmine/Server.php @@ -184,26 +184,26 @@ class Server{ public const BROADCAST_CHANNEL_ADMINISTRATIVE = "pocketmine.broadcast.admin"; public const BROADCAST_CHANNEL_USERS = "pocketmine.broadcast.user"; - /** @var Server */ + /** @var Server|null */ private static $instance = null; - /** @var \Threaded */ + /** @var \Threaded|null */ private static $sleeper = null; /** @var SleeperHandler */ private $tickSleeper; /** @var BanList */ - private $banByName = null; + private $banByName; /** @var BanList */ - private $banByIP = null; + private $banByIP; /** @var Config */ - private $operators = null; + private $operators; /** @var Config */ - private $whitelist = null; + private $whitelist; /** @var bool */ private $isRunning = true; @@ -212,13 +212,13 @@ class Server{ private $hasStopped = false; /** @var PluginManager */ - private $pluginManager = null; + private $pluginManager; /** @var float */ private $profilingTickRate = 20; /** @var AutoUpdater */ - private $updater = null; + private $updater; /** @var AsyncPool */ private $asyncPool; @@ -256,10 +256,10 @@ class Server{ private $memoryManager; /** @var CommandReader */ - private $console = null; + private $console; /** @var SimpleCommandMap */ - private $commandMap = null; + private $commandMap; /** @var CraftingManager */ private $craftingManager; @@ -276,8 +276,8 @@ class Server{ /** @var bool */ private $autoSave; - /** @var RCON */ - private $rcon; + /** @var RCON|null */ + private $rcon = null; /** @var EntityMetadataStore */ private $entityMetadata; @@ -315,14 +315,17 @@ class Server{ /** @var string */ private $pluginPath; - /** @var string[] */ + /** + * @var string[] + * @phpstan-var array + */ private $uniquePlayers = []; - /** @var QueryHandler */ - private $queryHandler; + /** @var QueryHandler|null */ + private $queryHandler = null; /** @var QueryRegenerateEvent */ - private $queryRegenerateTask = null; + private $queryRegenerateTask; /** @var Config */ private $properties; @@ -344,75 +347,45 @@ class Server{ /** @var Level[] */ private $levels = []; - /** @var Level */ + /** @var Level|null */ private $levelDefault = null; - /** - * @return string - */ public function getName() : string{ return \pocketmine\NAME; } - /** - * @return bool - */ public function isRunning() : bool{ return $this->isRunning; } - /** - * @return string - */ public function getPocketMineVersion() : string{ return \pocketmine\VERSION; } - /** - * @return string - */ public function getVersion() : string{ return ProtocolInfo::MINECRAFT_VERSION; } - /** - * @return string - */ public function getApiVersion() : string{ return \pocketmine\BASE_VERSION; } - /** - * @return string - */ public function getFilePath() : string{ return \pocketmine\PATH; } - /** - * @return string - */ public function getResourcePath() : string{ return \pocketmine\RESOURCE_PATH; } - /** - * @return string - */ public function getDataPath() : string{ return $this->dataPath; } - /** - * @return string - */ public function getPluginPath() : string{ return $this->pluginPath; } - /** - * @return int - */ public function getMaxPlayers() : int{ return $this->maxPlayers; } @@ -420,8 +393,6 @@ class Server{ /** * Returns whether the server requires that players be authenticated to Xbox Live. If true, connecting players who * are not logged into Xbox Live will be disconnected. - * - * @return bool */ public function getOnlineMode() : bool{ return $this->onlineMode; @@ -429,40 +400,26 @@ class Server{ /** * Alias of {@link #getOnlineMode()}. - * @return bool */ public function requiresAuthentication() : bool{ return $this->getOnlineMode(); } - /** - * @return int - */ public function getPort() : int{ return $this->getConfigInt("server-port", 19132); } - /** - * @return int - */ public function getViewDistance() : int{ return max(2, $this->getConfigInt("view-distance", 8)); } /** * Returns a view distance up to the currently-allowed limit. - * - * @param int $distance - * - * @return int */ public function getAllowedViewDistance(int $distance) : int{ return max(2, min($distance, $this->memoryManager->getViewDistance($this->getViewDistance()))); } - /** - * @return string - */ public function getIp() : string{ $str = $this->getConfigString("server-ip"); return $str !== "" ? $str : "0.0.0.0"; @@ -475,15 +432,12 @@ class Server{ return $this->serverID; } - /** - * @return bool - */ public function getAutoSave() : bool{ return $this->autoSave; } /** - * @param bool $value + * @return void */ public function setAutoSave(bool $value){ $this->autoSave = $value; @@ -492,40 +446,24 @@ class Server{ } } - /** - * @return string - */ public function getLevelType() : string{ return $this->getConfigString("level-type", "DEFAULT"); } - /** - * @return bool - */ public function getGenerateStructures() : bool{ return $this->getConfigBool("generate-structures", true); } - /** - * @return int - */ public function getGamemode() : int{ return $this->getConfigInt("gamemode", 0) & 0b11; } - /** - * @return bool - */ public function getForceGamemode() : bool{ return $this->getConfigBool("force-gamemode", false); } /** * Returns the gamemode text name - * - * @param int $mode - * - * @return string */ public static function getGamemodeString(int $mode) : string{ switch($mode){ @@ -559,10 +497,6 @@ class Server{ /** * Parses a string and returns a gamemode integer, -1 if not found - * - * @param string $str - * - * @return int */ public static function getGamemodeFromString(string $str) : int{ switch(strtolower(trim($str))){ @@ -592,51 +526,34 @@ class Server{ /** * Returns Server global difficulty. Note that this may be overridden in individual Levels. - * @return int */ public function getDifficulty() : int{ return $this->getConfigInt("difficulty", Level::DIFFICULTY_NORMAL); } - /** - * @return bool - */ public function hasWhitelist() : bool{ return $this->getConfigBool("white-list", false); } - /** - * @return int - */ public function getSpawnRadius() : int{ return $this->getConfigInt("spawn-protection", 16); } /** * @deprecated - * @return bool */ public function getAllowFlight() : bool{ return true; } - /** - * @return bool - */ public function isHardcore() : bool{ return $this->getConfigBool("hardcore", false); } - /** - * @return int - */ public function getDefaultGamemode() : int{ return $this->getConfigInt("gamemode", 0) & 0b11; } - /** - * @return string - */ public function getMotd() : string{ return $this->getConfigString("motd", \pocketmine\NAME . " Server"); } @@ -697,9 +614,6 @@ class Server{ return $this->craftingManager; } - /** - * @return ResourcePackManager - */ public function getResourcePackManager() : ResourcePackManager{ return $this->resourceManager; } @@ -708,17 +622,12 @@ class Server{ return $this->asyncPool; } - /** - * @return int - */ public function getTick() : int{ return $this->tickCounter; } /** * Returns the last server TPS measure - * - * @return float */ public function getTicksPerSecond() : float{ return round($this->currentTPS, 2); @@ -726,8 +635,6 @@ class Server{ /** * Returns the last server TPS average measure - * - * @return float */ public function getTicksPerSecondAverage() : float{ return round(array_sum($this->tickAverage) / count($this->tickAverage), 2); @@ -735,8 +642,6 @@ class Server{ /** * Returns the TPS usage/load in % - * - * @return float */ public function getTickUsage() : float{ return round($this->currentUse * 100, 2); @@ -744,8 +649,6 @@ class Server{ /** * Returns the TPS usage/load average in % - * - * @return float */ public function getTickUsageAverage() : float{ return round((array_sum($this->useAverage) / count($this->useAverage)) * 100, 2); @@ -777,8 +680,6 @@ class Server{ } /** - * @param string $name - * * @return OfflinePlayer|Player */ public function getOfflinePlayer(string $name){ @@ -794,21 +695,12 @@ class Server{ /** * Returns whether the server has stored any saved data for this player. - * - * @param string $name - * - * @return bool */ public function hasOfflinePlayerData(string $name) : bool{ $name = strtolower($name); return file_exists($this->getDataPath() . "players/$name.dat"); } - /** - * @param string $name - * - * @return CompoundTag - */ public function getOfflinePlayerData(string $name) : CompoundTag{ $name = strtolower($name); $path = $this->getDataPath() . "players/"; @@ -873,8 +765,7 @@ class Server{ } /** - * @param string $name - * @param CompoundTag $nbtTag + * @return void */ public function saveOfflinePlayerData(string $name, CompoundTag $nbtTag){ $ev = new PlayerDataSaveEvent($nbtTag, $name); @@ -899,8 +790,6 @@ class Server{ * * @see Server::getPlayerExact() * - * @param string $name - * * @return Player|null */ public function getPlayer(string $name){ @@ -926,8 +815,6 @@ class Server{ /** * Returns an online player with the given name (case insensitive), or null if not found. * - * @param string $name - * * @return Player|null */ public function getPlayerExact(string $name){ @@ -945,8 +832,6 @@ class Server{ * Returns a list of online players whose names contain with the given string (case insensitive). * If an exact match is found, only that match is returned. * - * @param string $partialName - * * @return Player[] */ public function matchPlayer(string $partialName) : array{ @@ -966,10 +851,6 @@ class Server{ /** * Returns the player online with the specified raw UUID, or null if not found - * - * @param string $rawUUID - * - * @return null|Player */ public function getPlayerByRawUUID(string $rawUUID) : ?Player{ return $this->playerList[$rawUUID] ?? null; @@ -977,10 +858,6 @@ class Server{ /** * Returns the player online with a UUID equivalent to the specified UUID object, or null if not found - * - * @param UUID $uuid - * - * @return null|Player */ public function getPlayerByUUID(UUID $uuid) : ?Player{ return $this->getPlayerByRawUUID($uuid->toBinary()); @@ -993,9 +870,6 @@ class Server{ return $this->levels; } - /** - * @return Level|null - */ public function getDefaultLevel() : ?Level{ return $this->levelDefault; } @@ -1004,8 +878,6 @@ class Server{ * Sets the default level to a different level * This won't change the level-name property, * it only affects the server on runtime - * - * @param Level|null $level */ public function setDefaultLevel(?Level $level) : void{ if($level === null or ($this->isLevelLoaded($level->getFolderName()) and $level !== $this->levelDefault)){ @@ -1013,30 +885,16 @@ class Server{ } } - /** - * @param string $name - * - * @return bool - */ public function isLevelLoaded(string $name) : bool{ return $this->getLevelByName($name) instanceof Level; } - /** - * @param int $levelId - * - * @return Level|null - */ public function getLevel(int $levelId) : ?Level{ return $this->levels[$levelId] ?? null; } /** * NOTE: This matches levels based on the FOLDER name, NOT the display name. - * - * @param string $name - * - * @return Level|null */ public function getLevelByName(string $name) : ?Level{ foreach($this->getLevels() as $level){ @@ -1049,11 +907,6 @@ class Server{ } /** - * @param Level $level - * @param bool $forceUnload - * - * @return bool - * * @throws \InvalidStateException */ public function unloadLevel(Level $level, bool $forceUnload = false) : bool{ @@ -1066,8 +919,6 @@ class Server{ /** * @internal - * - * @param Level $level */ public function removeLevel(Level $level) : void{ unset($this->levels[$level->getId()]); @@ -1076,10 +927,6 @@ class Server{ /** * Loads a level from the data directory * - * @param string $name - * - * @return bool - * * @throws LevelException */ public function loadLevel(string $name) : bool{ @@ -1133,12 +980,9 @@ class Server{ /** * Generates a new level if it does not exist * - * @param string $name - * @param int|null $seed * @param string|null $generator Class name that extends pocketmine\level\generator\Generator - * @param array $options - * - * @return bool + * @phpstan-param class-string $generator + * @phpstan-param array $options */ public function generateLevel(string $name, int $seed = null, $generator = null, array $options = []) : bool{ if(trim($name) === "" or $this->isLevelGenerated($name)){ @@ -1202,20 +1046,15 @@ class Server{ return true; } - /** - * @param string $name - * - * @return bool - */ public function isLevelGenerated(string $name) : bool{ if(trim($name) === ""){ return false; } $path = $this->getDataPath() . "worlds/" . $name . "/"; if(!($this->getLevelByName($name) instanceof Level)){ - return is_dir($path) and !empty(array_filter(scandir($path, SCANDIR_SORT_NONE), function($v){ + return is_dir($path) and count(array_filter(scandir($path, SCANDIR_SORT_NONE), function(string $v) : bool{ return $v !== ".." and $v !== "."; - })); + })) > 0; } return true; @@ -1225,7 +1064,6 @@ class Server{ * Searches all levels for the entity with the specified ID. * Useful for tracking entities across multiple worlds without needing strong references. * - * @param int $entityId * @param Level|null $expectedLevel @deprecated Level to look in first for the target * * @return Entity|null @@ -1242,7 +1080,6 @@ class Server{ } /** - * @param string $variable * @param mixed $defaultValue * * @return mixed @@ -1260,12 +1097,6 @@ class Server{ return $this->propertyCache[$variable] ?? $defaultValue; } - /** - * @param string $variable - * @param string $defaultValue - * - * @return string - */ public function getConfigString(string $variable, string $defaultValue = "") : string{ $v = getopt("", ["$variable::"]); if(isset($v[$variable])){ @@ -1276,19 +1107,12 @@ class Server{ } /** - * @param string $variable - * @param string $value + * @return void */ public function setConfigString(string $variable, string $value){ $this->properties->set($variable, $value); } - /** - * @param string $variable - * @param int $defaultValue - * - * @return int - */ public function getConfigInt(string $variable, int $defaultValue = 0) : int{ $v = getopt("", ["$variable::"]); if(isset($v[$variable])){ @@ -1299,19 +1123,12 @@ class Server{ } /** - * @param string $variable - * @param int $value + * @return void */ public function setConfigInt(string $variable, int $value){ $this->properties->set($variable, $value); } - /** - * @param string $variable - * @param bool $defaultValue - * - * @return bool - */ public function getConfigBool(string $variable, bool $defaultValue = false) : bool{ $v = getopt("", ["$variable::"]); if(isset($v[$variable])){ @@ -1335,16 +1152,13 @@ class Server{ } /** - * @param string $variable - * @param bool $value + * @return void */ public function setConfigBool(string $variable, bool $value){ $this->properties->set($variable, $value ? "1" : "0"); } /** - * @param string $name - * * @return PluginIdentifiableCommand|null */ public function getPluginCommand(string $name){ @@ -1370,7 +1184,7 @@ class Server{ } /** - * @param string $name + * @return void */ public function addOp(string $name){ $this->operators->set(strtolower($name), true); @@ -1382,7 +1196,7 @@ class Server{ } /** - * @param string $name + * @return void */ public function removeOp(string $name){ $this->operators->remove(strtolower($name)); @@ -1394,7 +1208,7 @@ class Server{ } /** - * @param string $name + * @return void */ public function addWhitelist(string $name){ $this->whitelist->set(strtolower($name), true); @@ -1402,27 +1216,17 @@ class Server{ } /** - * @param string $name + * @return void */ public function removeWhitelist(string $name){ $this->whitelist->remove(strtolower($name)); $this->whitelist->save(); } - /** - * @param string $name - * - * @return bool - */ public function isWhitelisted(string $name) : bool{ return !$this->hasWhitelist() or $this->operators->exists($name, true) or $this->whitelist->exists($name, true); } - /** - * @param string $name - * - * @return bool - */ public function isOp(string $name) : bool{ return $this->operators->exists($name, true); } @@ -1441,6 +1245,9 @@ class Server{ return $this->operators; } + /** + * @return void + */ public function reloadWhitelist(){ $this->whitelist->reload(); } @@ -1467,9 +1274,6 @@ class Server{ return $result; } - /** - * @return Server - */ public static function getInstance() : Server{ if(self::$instance === null){ throw new \RuntimeException("Attempt to retrieve Server instance outside server thread"); @@ -1477,24 +1281,23 @@ class Server{ return self::$instance; } + /** + * @return void + */ public static function microSleep(int $microseconds){ - Server::$sleeper->synchronized(function(int $ms){ + if(self::$sleeper === null){ + self::$sleeper = new \Threaded(); + } + self::$sleeper->synchronized(function(int $ms) : void{ Server::$sleeper->wait($ms); }, $microseconds); } - /** - * @param \ClassLoader $autoloader - * @param \AttachableThreadedLogger $logger - * @param string $dataPath - * @param string $pluginPath - */ public function __construct(\ClassLoader $autoloader, \AttachableThreadedLogger $logger, string $dataPath, string $pluginPath){ if(self::$instance !== null){ throw new \InvalidStateException("Only one server instance can exist at once"); } self::$instance = $this; - self::$sleeper = new \Threaded; $this->tickSleeper = new SleeperHandler(); $this->autoloader = $autoloader; $this->logger = $logger; @@ -1586,7 +1389,7 @@ class Server{ $poolSize = max(1, (int) $poolSize); } - $this->asyncPool = new AsyncPool($this, $poolSize, (int) max(-1, (int) $this->getProperty("memory.async-worker-hard-limit", 256)), $this->autoloader, $this->logger); + $this->asyncPool = new AsyncPool($this, $poolSize, max(-1, (int) $this->getProperty("memory.async-worker-hard-limit", 256)), $this->autoloader, $this->logger); if($this->getProperty("network.batch-threshold", 256) >= 0){ Network::$BATCH_THRESHOLD = (int) $this->getProperty("network.batch-threshold", 256); @@ -1603,7 +1406,6 @@ class Server{ $this->doTitleTick = ((bool) $this->getProperty("console.title-tick", true)) && Terminal::hasFormattingCodes(); - $consoleSender = new ConsoleCommandSender(); PermissionManager::getInstance()->subscribeToPermission(Server::BROADCAST_CHANNEL_ADMINISTRATIVE, $consoleSender); @@ -1683,14 +1485,12 @@ class Server{ $this->network = new Network($this); $this->network->setName($this->getMotd()); - $this->logger->info($this->getLanguage()->translateString("pocketmine.server.info", [ $this->getName(), (\pocketmine\IS_DEVELOPMENT_BUILD ? TextFormat::YELLOW : "") . $this->getPocketMineVersion() . TextFormat::RESET ])); $this->logger->info($this->getLanguage()->translateString("pocketmine.server.license", [$this->getName()])); - Timings::init(); TimingsHandler::setEnabled((bool) $this->getProperty("settings.enable-profiling", false)); @@ -1723,10 +1523,9 @@ class Server{ $this->queryRegenerateTask = new QueryRegenerateEvent($this); - $this->pluginManager->loadPlugins($this->pluginPath); - $this->updater = new AutoUpdater($this, $this->getProperty("auto-updater.host", "update.pmmp.io")); + $this->pluginManager->loadPlugins($this->pluginPath); $this->enablePlugins(PluginLoadOrder::STARTUP); $this->network->registerInterface(new RakLibInterface($this)); @@ -1791,9 +1590,7 @@ class Server{ /** * @param TextContainer|string $message - * @param CommandSender[] $recipients - * - * @return int + * @param CommandSender[]|null $recipients */ public function broadcastMessage($message, array $recipients = null) : int{ if(!is_array($recipients)){ @@ -1808,10 +1605,7 @@ class Server{ } /** - * @param string $tip - * @param Player[] $recipients - * - * @return int + * @param Player[]|null $recipients */ public function broadcastTip(string $tip, array $recipients = null) : int{ if(!is_array($recipients)){ @@ -1832,10 +1626,7 @@ class Server{ } /** - * @param string $popup - * @param Player[] $recipients - * - * @return int + * @param Player[]|null $recipients */ public function broadcastPopup(string $popup, array $recipients = null) : int{ if(!is_array($recipients)){ @@ -1857,14 +1648,10 @@ class Server{ } /** - * @param string $title - * @param string $subtitle * @param int $fadeIn Duration in ticks for fade-in. If -1 is given, client-sided defaults will be used. * @param int $stay Duration in ticks to stay on screen for * @param int $fadeOut Duration in ticks for fade-out. * @param Player[]|null $recipients - * - * @return int */ public function broadcastTitle(string $title, string $subtitle = "", int $fadeIn = -1, int $stay = -1, int $fadeOut = -1, array $recipients = null) : int{ if(!is_array($recipients)){ @@ -1887,9 +1674,6 @@ class Server{ /** * @param TextContainer|string $message - * @param string $permissions - * - * @return int */ public function broadcast($message, string $permissions) : int{ /** @var CommandSender[] $recipients */ @@ -1913,7 +1697,8 @@ class Server{ * Broadcasts a Minecraft packet to a list of players * * @param Player[] $players - * @param DataPacket $packet + * + * @return void */ public function broadcastPacket(array $players, DataPacket $packet){ $packet->encode(); @@ -1925,18 +1710,18 @@ class Server{ * * @param Player[] $players * @param DataPacket[] $packets - * @param bool $forceSync - * @param bool $immediate + * + * @return void */ public function batchPackets(array $players, array $packets, bool $forceSync = false, bool $immediate = false){ - if(empty($packets)){ + if(count($packets) === 0){ throw new \InvalidArgumentException("Cannot send empty batch"); } Timings::$playerNetworkTimer->startTiming(); $targets = array_filter($players, function(Player $player) : bool{ return $player->isConnected(); }); - if(!empty($targets)){ + if(count($targets) > 0){ $pk = new BatchPacket(); foreach($packets as $p){ @@ -1962,9 +1747,9 @@ class Server{ } /** - * @param BatchPacket $pk * @param Player[] $players - * @param bool $immediate + * + * @return void */ public function broadcastPacketsCallback(BatchPacket $pk, array $players, bool $immediate = false){ if(!$pk->isEncoded){ @@ -1976,9 +1761,8 @@ class Server{ } } - /** - * @param int $type + * @return void */ public function enablePlugins(int $type){ foreach($this->pluginManager->getPlugins() as $plugin){ @@ -1994,24 +1778,21 @@ class Server{ } /** - * @param Plugin $plugin + * @return void */ public function enablePlugin(Plugin $plugin){ $this->pluginManager->enablePlugin($plugin); } + /** + * @return void + */ public function disablePlugins(){ $this->pluginManager->disablePlugins(); } /** * Executes a command from a CommandSender - * - * @param CommandSender $sender - * @param string $commandLine - * @param bool $internal - * - * @return bool */ public function dispatchCommand(CommandSender $sender, string $commandLine, bool $internal = false) : bool{ if(!$internal){ @@ -2028,12 +1809,14 @@ class Server{ return true; } - $sender->sendMessage($this->getLanguage()->translateString(TextFormat::RED . "%commands.generic.notFound")); return false; } + /** + * @return void + */ public function reload(){ $this->logger->info("Saving worlds..."); @@ -2073,11 +1856,16 @@ class Server{ /** * Shuts the server down correctly + * + * @return void */ public function shutdown(){ $this->isRunning = false; } + /** + * @return void + */ public function forceShutdown(){ if($this->hasStopped){ return; @@ -2099,7 +1887,7 @@ class Server{ $this->rcon->stop(); } - if($this->getProperty("network.upnp-forwarding", false)){ + if((bool) $this->getProperty("network.upnp-forwarding", false)){ $this->logger->info("[UPnP] Removing port forward..."); UPnP::RemovePortForward($this->getPort()); } @@ -2163,7 +1951,7 @@ class Server{ /** * Starts the PocketMine-MP server and starts processing ticks and packets */ - private function start(){ + private function start() : void{ if($this->getConfigBool("enable-query", true)){ $this->queryHandler = new QueryHandler(); } @@ -2172,13 +1960,12 @@ class Server{ $this->network->blockAddress($entry->getName(), -1); } - if($this->getProperty("settings.send-usage", true)){ + if((bool) $this->getProperty("settings.send-usage", true)){ $this->sendUsageTicker = 6000; $this->sendUsage(SendUsageTask::TYPE_OPEN); } - - if($this->getProperty("network.upnp-forwarding", false)){ + if((bool) $this->getProperty("network.upnp-forwarding", false)){ $this->logger->info("[UPnP] Trying to port forward..."); try{ UPnP::PortForward($this->getPort()); @@ -2205,6 +1992,11 @@ class Server{ $this->forceShutdown(); } + /** + * @param int $signo + * + * @return void + */ public function handleSignal($signo){ if($signo === SIGTERM or $signo === SIGINT or $signo === SIGHUP){ $this->shutdown(); @@ -2212,8 +2004,10 @@ class Server{ } /** - * @param \Throwable $e - * @param array|null $trace + * @param mixed[][]|null $trace + * @phpstan-param list>|null $trace + * + * @return void */ public function exceptionHandler(\Throwable $e, $trace = null){ while(@ob_end_flush()){} @@ -2297,7 +2091,7 @@ class Server{ } if($report){ - $url = ($this->getProperty("auto-report.use-https", true) ? "https" : "http") . "://" . $this->getProperty("auto-report.host", "crash.pmmp.io") . "/submit/api"; + $url = ((bool) $this->getProperty("auto-report.use-https", true) ? "https" : "http") . "://" . $this->getProperty("auto-report.host", "crash.pmmp.io") . "/submit/api"; $reply = Internet::postURL($url, [ "report" => "yes", "name" => $this->getName() . " " . $this->getPocketMineVersion(), @@ -2332,6 +2126,9 @@ class Server{ exit(1); } + /** + * @return mixed[] + */ public function __debugInfo(){ return []; } @@ -2340,7 +2137,7 @@ class Server{ return $this->tickSleeper; } - private function tickProcessor(){ + private function tickProcessor() : void{ $this->nextTick = microtime(true); while($this->isRunning){ @@ -2351,6 +2148,9 @@ class Server{ } } + /** + * @return void + */ public function onPlayerLogin(Player $player){ if($this->sendUsageTicker > 0){ $this->uniquePlayers[$player->getRawUniqueId()] = $player->getRawUniqueId(); @@ -2359,27 +2159,39 @@ class Server{ $this->loggedInPlayers[$player->getRawUniqueId()] = $player; } + /** + * @return void + */ public function onPlayerLogout(Player $player){ unset($this->loggedInPlayers[$player->getRawUniqueId()]); } + /** + * @return void + */ public function addPlayer(Player $player){ $this->players[spl_object_hash($player)] = $player; } /** - * @param Player $player + * @return void */ public function removePlayer(Player $player){ unset($this->players[spl_object_hash($player)]); } + /** + * @return void + */ public function addOnlinePlayer(Player $player){ $this->updatePlayerListData($player->getUniqueId(), $player->getId(), $player->getDisplayName(), $player->getSkin(), $player->getXuid()); $this->playerList[$player->getRawUniqueId()] = $player; } + /** + * @return void + */ public function removeOnlinePlayer(Player $player){ if(isset($this->playerList[$player->getRawUniqueId()])){ unset($this->playerList[$player->getRawUniqueId()]); @@ -2389,12 +2201,9 @@ class Server{ } /** - * @param UUID $uuid - * @param int $entityId - * @param string $name - * @param Skin $skin - * @param string $xboxUserId * @param Player[]|null $players + * + * @return void */ public function updatePlayerListData(UUID $uuid, int $entityId, string $name, Skin $skin, string $xboxUserId = "", array $players = null){ $pk = new PlayerListPacket(); @@ -2406,8 +2215,9 @@ class Server{ } /** - * @param UUID $uuid * @param Player[]|null $players + * + * @return void */ public function removePlayerListData(UUID $uuid, array $players = null){ $pk = new PlayerListPacket(); @@ -2417,7 +2227,7 @@ class Server{ } /** - * @param Player $p + * @return void */ public function sendFullPlayerListData(Player $p){ $pk = new PlayerListPacket(); @@ -2453,6 +2263,9 @@ class Server{ } } + /** + * @return void + */ public function doAutoSave(){ if($this->getAutoSave()){ Timings::$worldSaveTimer->startTiming(); @@ -2471,6 +2284,11 @@ class Server{ } } + /** + * @param int $type + * + * @return void + */ public function sendUsage($type = SendUsageTask::TYPE_STATUS){ if((bool) $this->getProperty("anonymous-statistics.enabled", true)){ $this->asyncPool->submitTask(new SendUsageTask($this, $type, $this->uniquePlayers)); @@ -2478,7 +2296,6 @@ class Server{ $this->uniquePlayers = []; } - /** * @return BaseLang */ @@ -2486,9 +2303,6 @@ class Server{ return $this->baseLang; } - /** - * @return bool - */ public function isLanguageForced() : bool{ return $this->forceLanguage; } @@ -2507,7 +2321,7 @@ class Server{ return $this->memoryManager; } - private function titleTick(){ + private function titleTick() : void{ Timings::$titleTickTimer->startTiming(); $d = Process::getRealMemoryUsage(); @@ -2527,10 +2341,7 @@ class Server{ } /** - * @param AdvancedSourceInterface $interface - * @param string $address - * @param int $port - * @param string $payload + * @return void * * TODO: move this to Network */ @@ -2549,7 +2360,6 @@ class Server{ //TODO: add raw packet events } - /** * Tries to execute a server tick */ diff --git a/src/pocketmine/Thread.php b/src/pocketmine/Thread.php index 347ec62bcd..389eb9550b 100644 --- a/src/pocketmine/Thread.php +++ b/src/pocketmine/Thread.php @@ -33,12 +33,19 @@ abstract class Thread extends \Thread{ /** @var string|null */ protected $composerAutoloaderPath; + /** @var bool */ protected $isKilled = false; + /** + * @return \ClassLoader|null + */ public function getClassLoader(){ return $this->classLoader; } + /** + * @return void + */ public function setClassLoader(\ClassLoader $loader = null){ $this->composerAutoloaderPath = \pocketmine\COMPOSER_AUTOLOADER_PATH; @@ -54,6 +61,8 @@ abstract class Thread extends \Thread{ * WARNING: This method MUST be called from any descendent threads' run() method to make autoloading usable. * If you do not do this, you will not be able to use new classes that were not loaded when the thread was started * (unless you are using a custom autoloader). + * + * @return void */ public function registerClassLoader(){ if($this->composerAutoloaderPath !== null){ @@ -64,6 +73,11 @@ abstract class Thread extends \Thread{ } } + /** + * @param int|null $options TODO: pthreads bug + * + * @return bool + */ public function start(?int $options = \PTHREADS_INHERIT_ALL){ ThreadManager::getInstance()->add($this); @@ -75,6 +89,8 @@ abstract class Thread extends \Thread{ /** * Stops the thread using the best way possible. Try to stop it yourself before calling this. + * + * @return void */ public function quit(){ $this->isKilled = true; diff --git a/src/pocketmine/ThreadManager.php b/src/pocketmine/ThreadManager.php index e90d598d60..20c068b944 100644 --- a/src/pocketmine/ThreadManager.php +++ b/src/pocketmine/ThreadManager.php @@ -28,9 +28,13 @@ use function spl_object_hash; class ThreadManager extends \Volatile{ - /** @var ThreadManager */ + /** @var ThreadManager|null */ private static $instance = null; + /** + * @deprecated + * @return void + */ public static function init(){ self::$instance = new ThreadManager(); } @@ -39,24 +43,31 @@ class ThreadManager extends \Volatile{ * @return ThreadManager */ public static function getInstance(){ + if(self::$instance === null){ + self::$instance = new ThreadManager(); + } return self::$instance; } /** * @param Worker|Thread $thread + * + * @return void */ public function add($thread){ if($thread instanceof Thread or $thread instanceof Worker){ - $this->{spl_object_hash($thread)} = $thread; + $this[spl_object_hash($thread)] = $thread; } } /** * @param Worker|Thread $thread + * + * @return void */ public function remove($thread){ if($thread instanceof Thread or $thread instanceof Worker){ - unset($this->{spl_object_hash($thread)}); + unset($this[spl_object_hash($thread)]); } } diff --git a/src/pocketmine/VersionInfo.php b/src/pocketmine/VersionInfo.php index a8e9008381..f062058894 100644 --- a/src/pocketmine/VersionInfo.php +++ b/src/pocketmine/VersionInfo.php @@ -19,6 +19,8 @@ * */ +declare(strict_types=1); + namespace pocketmine; // composer autoload doesn't use require_once and also pthreads can inherit things @@ -28,8 +30,7 @@ if(defined('pocketmine\_VERSION_INFO_INCLUDED')){ } const _VERSION_INFO_INCLUDED = true; - const NAME = "PocketMine-MP"; -const BASE_VERSION = "3.11.2"; +const BASE_VERSION = "3.11.6"; const IS_DEVELOPMENT_BUILD = true; const BUILD_NUMBER = 0; diff --git a/src/pocketmine/Worker.php b/src/pocketmine/Worker.php index f4018ea48f..b7b551c29b 100644 --- a/src/pocketmine/Worker.php +++ b/src/pocketmine/Worker.php @@ -33,12 +33,19 @@ abstract class Worker extends \Worker{ /** @var string|null */ protected $composerAutoloaderPath; + /** @var bool */ protected $isKilled = false; + /** + * @return \ClassLoader|null + */ public function getClassLoader(){ return $this->classLoader; } + /** + * @return void + */ public function setClassLoader(\ClassLoader $loader = null){ $this->composerAutoloaderPath = \pocketmine\COMPOSER_AUTOLOADER_PATH; @@ -54,6 +61,8 @@ abstract class Worker extends \Worker{ * WARNING: This method MUST be called from any descendent threads' run() method to make autoloading usable. * If you do not do this, you will not be able to use new classes that were not loaded when the thread was started * (unless you are using a custom autoloader). + * + * @return void */ public function registerClassLoader(){ if($this->composerAutoloaderPath !== null){ @@ -64,6 +73,11 @@ abstract class Worker extends \Worker{ } } + /** + * @param int|null $options TODO: pthreads bug + * + * @return bool + */ public function start(?int $options = \PTHREADS_INHERIT_ALL){ ThreadManager::getInstance()->add($this); @@ -75,6 +89,8 @@ abstract class Worker extends \Worker{ /** * Stops the thread using the best way possible. Try to stop it yourself before calling this. + * + * @return void */ public function quit(){ $this->isKilled = true; diff --git a/src/pocketmine/block/Air.php b/src/pocketmine/block/Air.php index b953eb9060..7772c9ba9d 100644 --- a/src/pocketmine/block/Air.php +++ b/src/pocketmine/block/Air.php @@ -26,7 +26,6 @@ namespace pocketmine\block; use pocketmine\item\Item; use pocketmine\math\AxisAlignedBB; - /** * Air block */ diff --git a/src/pocketmine/block/Anvil.php b/src/pocketmine/block/Anvil.php index 73aceebb52..2eb8880afc 100644 --- a/src/pocketmine/block/Anvil.php +++ b/src/pocketmine/block/Anvil.php @@ -78,7 +78,7 @@ class Anvil extends Fallable{ public function recalculateBoundingBox() : ?AxisAlignedBB{ $inset = 0.125; - if($this->meta & 0x01){ //east/west + if(($this->meta & 0x01) !== 0){ //east/west return new AxisAlignedBB( $this->x, $this->y, diff --git a/src/pocketmine/block/BaseRail.php b/src/pocketmine/block/BaseRail.php index e6d6b1f583..c5fb8b2e3b 100644 --- a/src/pocketmine/block/BaseRail.php +++ b/src/pocketmine/block/BaseRail.php @@ -99,6 +99,11 @@ abstract class BaseRail extends Flowable{ return false; } + /** + * @param int[] $connections + * @param int[][] $lookup + * @phpstan-param array> $lookup + */ protected static function searchState(array $connections, array $lookup) : int{ $meta = array_search($connections, $lookup, true); if($meta === false){ @@ -114,9 +119,7 @@ abstract class BaseRail extends Flowable{ /** * Returns a meta value for the rail with the given connections. * - * @param array $connections - * - * @return int + * @param int[] $connections * * @throws \InvalidArgumentException if no state matches the given connections */ @@ -164,6 +167,12 @@ abstract class BaseRail extends Flowable{ return $connections; } + /** + * @param int[] $constraints + * + * @return true[] + * @phpstan-return array + */ private function getPossibleConnectionDirections(array $constraints) : array{ switch(count($constraints)){ case 0: @@ -188,6 +197,10 @@ abstract class BaseRail extends Flowable{ } } + /** + * @return true[] + * @phpstan-return array + */ protected function getPossibleConnectionDirectionsOneConstraint(int $constraint) : array{ $opposite = Vector3::getOppositeSide($constraint & ~self::FLAG_ASCEND); @@ -247,6 +260,9 @@ abstract class BaseRail extends Flowable{ } } + /** + * @param int[] $connections + */ private function updateState(array $connections) : void{ if(count($connections) === 1){ $connections[] = Vector3::getOppositeSide($connections[0] & ~self::FLAG_ASCEND); diff --git a/src/pocketmine/block/Bed.php b/src/pocketmine/block/Bed.php index 9a5870bc20..803f07ea39 100644 --- a/src/pocketmine/block/Bed.php +++ b/src/pocketmine/block/Bed.php @@ -69,13 +69,13 @@ class Bed extends Transparent{ return ($this->meta & self::BITFLAG_HEAD) !== 0; } - /** - * @return bool - */ public function isOccupied() : bool{ return ($this->meta & self::BITFLAG_OCCUPIED) !== 0; } + /** + * @return void + */ public function setOccupied(bool $occupied = true){ if($occupied){ $this->meta |= self::BITFLAG_OCCUPIED; @@ -90,12 +90,6 @@ class Bed extends Transparent{ } } - /** - * @param int $meta - * @param bool $isHead - * - * @return int - */ public static function getOtherHalfSide(int $meta, bool $isHead = false) : int{ $rotation = $meta & 0x03; $side = -1; @@ -122,9 +116,6 @@ class Bed extends Transparent{ return $side; } - /** - * @return Bed|null - */ public function getOtherHalf() : ?Bed{ $other = $this->getSide(self::getOtherHalfSide($this->meta, $this->isHeadPart())); if($other instanceof Bed and $other->getId() === $this->getId() and $other->isHeadPart() !== $this->isHeadPart() and (($other->getDamage() & 0x03) === ($this->getDamage() & 0x03))){ diff --git a/src/pocketmine/block/Block.php b/src/pocketmine/block/Block.php index 3fee8b2609..df18785e15 100644 --- a/src/pocketmine/block/Block.php +++ b/src/pocketmine/block/Block.php @@ -40,6 +40,7 @@ use pocketmine\network\mcpe\protocol\types\RuntimeBlockMapping; use pocketmine\Player; use pocketmine\plugin\Plugin; use function array_merge; +use function count; use function get_class; use const PHP_INT_MAX; @@ -49,12 +50,6 @@ class Block extends Position implements BlockIds, Metadatable{ * Returns a new Block instance with the specified ID, meta and position. * * This function redirects to {@link BlockFactory#get}. - * - * @param int $id - * @param int $meta - * @param Position|null $pos - * - * @return Block */ public static function get(int $id, int $meta = 0, Position $pos = null) : Block{ return BlockFactory::get($id, $meta, $pos); @@ -72,7 +67,6 @@ class Block extends Position implements BlockIds, Metadatable{ /** @var AxisAlignedBB|null */ protected $boundingBox = null; - /** @var AxisAlignedBB[]|null */ protected $collisionBoxes = null; @@ -89,16 +83,10 @@ class Block extends Position implements BlockIds, Metadatable{ $this->itemId = $itemId; } - /** - * @return string - */ public function getName() : string{ return $this->fallbackName ?? "Unknown"; } - /** - * @return int - */ final public function getId() : int{ return $this->id; } @@ -106,8 +94,6 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Returns the ID of the item form of the block. * Used for drops for blocks (some blocks such as doors have a different item ID). - * - * @return int */ public function getItemId() : int{ return $this->itemId ?? $this->getId(); @@ -115,22 +101,15 @@ class Block extends Position implements BlockIds, Metadatable{ /** * @internal - * @return int */ public function getRuntimeId() : int{ return RuntimeBlockMapping::toStaticRuntimeId($this->getId(), $this->getDamage()); } - /** - * @return int - */ final public function getDamage() : int{ return $this->meta; } - /** - * @param int $meta - */ final public function setDamage(int $meta) : void{ if($meta < 0 or $meta > 0xf){ throw new \InvalidArgumentException("Block damage values must be 0-15, not $meta"); @@ -144,8 +123,6 @@ class Block extends Position implements BlockIds, Metadatable{ * * If your block should not have any meta value when it's dropped as an item, override this to return 0 in * descendent classes. - * - * @return int */ public function getVariantBitmask() : int{ return -1; @@ -153,24 +130,18 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Returns the block meta, stripped of non-variant flags. - * @return int */ public function getVariant() : int{ return $this->meta & $this->getVariantBitmask(); } - /** * AKA: Block->isPlaceable - * @return bool */ public function canBePlaced() : bool{ return true; } - /** - * @return bool - */ public function canBeReplaced() : bool{ return false; } @@ -181,15 +152,6 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Places the Block, using block space and block target, and side. Returns if the block has been placed. - * - * @param Item $item - * @param Block $blockReplace - * @param Block $blockClicked - * @param int $face - * @param Vector3 $clickVector - * @param Player|null $player - * - * @return bool */ public function place(Item $item, Block $blockReplace, Block $blockClicked, int $face, Vector3 $clickVector, Player $player = null) : bool{ return $this->getLevel()->setBlock($this, $this, true, true); @@ -197,18 +159,11 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Returns if the block can be broken with an specific Item - * - * @param Item $item - * - * @return bool */ public function isBreakable(Item $item) : bool{ return true; } - /** - * @return int - */ public function getToolType() : int{ return BlockToolType::TYPE_NONE; } @@ -222,8 +177,6 @@ class Block extends Position implements BlockIds, Metadatable{ * Otherwise, 1 should be returned if a tool is required, 0 if not. * * @see Item::getBlockToolHarvestLevel() - * - * @return int */ public function getToolHarvestLevel() : int{ return 0; @@ -235,10 +188,6 @@ class Block extends Position implements BlockIds, Metadatable{ * * In most cases this is also used to determine whether block drops should be created or not, except in some * special cases such as vines. - * - * @param Item $tool - * - * @return bool */ public function isCompatibleWithTool(Item $tool) : bool{ if($this->getHardness() < 0){ @@ -253,23 +202,14 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Do the actions needed so the block is broken with the Item - * - * @param Item $item - * @param Player|null $player - * - * @return bool */ public function onBreak(Item $item, Player $player = null) : bool{ return $this->getLevel()->setBlock($this, BlockFactory::get(Block::AIR), true, true); } - /** * Returns the seconds that this block takes to be broken using an specific Item * - * @param Item $item - * - * @return float * @throws \InvalidArgumentException if the item efficiency is not a positive number */ public function getBreakTime(Item $item) : float{ @@ -299,8 +239,6 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Returns whether random block updates will be done on this block. - * - * @return bool */ public function ticksRandomly() : bool{ return false; @@ -323,11 +261,6 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Do actions when activated by Item. Returns if it has done anything - * - * @param Item $item - * @param Player|null $player - * - * @return bool */ public function onActivate(Item $item, Player $player = null) : bool{ return false; @@ -335,7 +268,6 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Returns a base value used to compute block break times. - * @return float */ public function getHardness() : float{ return 10; @@ -343,15 +275,11 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Returns the block's resistance to explosions. Usually 5x hardness. - * @return float */ public function getBlastResistance() : float{ return $this->getHardness() * 5; } - /** - * @return float - */ public function getFrictionFactor() : float{ return 0.6; } @@ -379,16 +307,11 @@ class Block extends Position implements BlockIds, Metadatable{ * Examples of this behaviour include leaves and cobwebs. * * Light-diffusing blocks are included by the heightmap. - * - * @return bool */ public function diffusesSkyLight() : bool{ return false; } - /** - * @return bool - */ public function isTransparent() : bool{ return false; } @@ -399,7 +322,6 @@ class Block extends Position implements BlockIds, Metadatable{ /** * AKA: Block->isFlowable - * @return bool */ public function canBeFlowedInto() : bool{ return false; @@ -415,21 +337,17 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Returns whether entities can climb up this block. - * @return bool */ public function canClimb() : bool{ return false; } - public function addVelocityToEntity(Entity $entity, Vector3 $vector) : void{ } /** * Sets the block position to a new Position object - * - * @param Position $v */ final public function position(Position $v) : void{ $this->x = (int) $v->x; @@ -442,8 +360,6 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Returns an array of Item objects to be dropped * - * @param Item $item - * * @return Item[] */ public function getDrops(Item $item) : array{ @@ -461,8 +377,6 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Returns an array of Items to be dropped when the block is broken using the correct tool type. * - * @param Item $item - * * @return Item[] */ public function getDropsForCompatibleTool(Item $item) : array{ @@ -474,8 +388,6 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Returns an array of Items to be dropped when the block is broken using a compatible Silk Touch-enchanted tool. * - * @param Item $item - * * @return Item[] */ public function getSilkTouchDrops(Item $item) : array{ @@ -486,10 +398,6 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Returns how much XP will be dropped by breaking this block with the given item. - * - * @param Item $item - * - * @return int */ public function getXpDropForTool(Item $item) : int{ if($item->hasEnchantment(Enchantment::SILK_TOUCH) or !$this->isCompatibleWithTool($item)){ @@ -501,8 +409,6 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Returns how much XP this block will drop when broken with an appropriate tool. - * - * @return int */ protected function getXpDropAmount() : int{ return 0; @@ -511,8 +417,6 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Returns whether Silk Touch enchanted tools will cause this block to drop as itself. Since most blocks drop * themselves anyway, this is implicitly true. - * - * @return bool */ public function isAffectedBySilkTouch() : bool{ return true; @@ -520,7 +424,6 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Returns the item that players will equip when middle-clicking on this block. - * @return Item */ public function getPickedItem() : Item{ return ItemFactory::get($this->getItemId(), $this->getVariant()); @@ -528,7 +431,6 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Returns the time in ticks which the block will fuel a furnace for. - * @return int */ public function getFuelTime() : int{ return 0; @@ -537,8 +439,6 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Returns the chance that the block will catch fire from nearby fire sources. Higher values lead to faster catching * fire. - * - * @return int */ public function getFlameEncouragement() : int{ return 0; @@ -546,8 +446,6 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Returns the base flammability of this block. Higher values lead to the block burning away more quickly. - * - * @return int */ public function getFlammability() : int{ return 0; @@ -555,8 +453,6 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Returns whether fire lit on this block will burn indefinitely. - * - * @return bool */ public function burnsForever() : bool{ return false; @@ -564,8 +460,6 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Returns whether this block can catch fire. - * - * @return bool */ public function isFlammable() : bool{ return $this->getFlammability() > 0; @@ -581,9 +475,6 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Returns the Block on the side $side, works like Vector3::getSide() * - * @param int $side - * @param int $step - * * @return Block */ public function getSide(int $side, int $step = 1){ @@ -642,10 +533,6 @@ class Block extends Position implements BlockIds, Metadatable{ /** * Checks for collision against an AxisAlignedBB - * - * @param AxisAlignedBB $bb - * - * @return bool */ public function collidesWithBB(AxisAlignedBB $bb) : bool{ foreach($this->getCollisionBoxes() as $bb2){ @@ -657,9 +544,6 @@ class Block extends Position implements BlockIds, Metadatable{ return false; } - /** - * @param Entity $entity - */ public function onEntityCollide(Entity $entity) : void{ } @@ -679,16 +563,13 @@ class Block extends Position implements BlockIds, Metadatable{ * @return AxisAlignedBB[] */ protected function recalculateCollisionBoxes() : array{ - if($bb = $this->recalculateBoundingBox()){ + if(($bb = $this->recalculateBoundingBox()) !== null){ return [$bb]; } return []; } - /** - * @return AxisAlignedBB|null - */ public function getBoundingBox() : ?AxisAlignedBB{ if($this->boundingBox === null){ $this->boundingBox = $this->recalculateBoundingBox(); @@ -696,9 +577,6 @@ class Block extends Position implements BlockIds, Metadatable{ return $this->boundingBox; } - /** - * @return AxisAlignedBB|null - */ protected function recalculateBoundingBox() : ?AxisAlignedBB{ return new AxisAlignedBB( $this->x, @@ -719,15 +597,9 @@ class Block extends Position implements BlockIds, Metadatable{ $this->collisionBoxes = null; } - /** - * @param Vector3 $pos1 - * @param Vector3 $pos2 - * - * @return RayTraceResult|null - */ public function calculateIntercept(Vector3 $pos1, Vector3 $pos2) : ?RayTraceResult{ $bbs = $this->getCollisionBoxes(); - if(empty($bbs)){ + if(count($bbs) === 0){ return null; } diff --git a/src/pocketmine/block/BlockFactory.php b/src/pocketmine/block/BlockFactory.php index 99c29bbf0d..3bc389c8ae 100644 --- a/src/pocketmine/block/BlockFactory.php +++ b/src/pocketmine/block/BlockFactory.php @@ -32,23 +32,47 @@ use function min; * Manages block registration and instance creation */ class BlockFactory{ - /** @var \SplFixedArray */ - private static $fullList = null; + /** + * @var \SplFixedArray|Block[] + * @phpstan-var \SplFixedArray + */ + private static $fullList; - /** @var \SplFixedArray */ - public static $solid = null; - /** @var \SplFixedArray */ - public static $transparent = null; - /** @var \SplFixedArray */ - public static $hardness = null; - /** @var \SplFixedArray */ - public static $light = null; - /** @var \SplFixedArray */ - public static $lightFilter = null; - /** @var \SplFixedArray */ - public static $diffusesSkyLight = null; - /** @var \SplFixedArray */ - public static $blastResistance = null; + /** + * @var \SplFixedArray|bool[] + * @phpstan-var \SplFixedArray + */ + public static $solid; + /** + * @var \SplFixedArray|bool[] + * @phpstan-var \SplFixedArray + */ + public static $transparent; + /** + * @var \SplFixedArray|float[] + * @phpstan-var \SplFixedArray + */ + public static $hardness; + /** + * @var \SplFixedArray|int[] + * @phpstan-var \SplFixedArray + */ + public static $light; + /** + * @var \SplFixedArray|int[] + * @phpstan-var \SplFixedArray + */ + public static $lightFilter; + /** + * @var \SplFixedArray|bool[] + * @phpstan-var \SplFixedArray + */ + public static $diffusesSkyLight; + /** + * @var \SplFixedArray|float[] + * @phpstan-var \SplFixedArray + */ + public static $blastResistance; /** * Initializes the block factory. By default this is called only once on server start, however you may wish to use @@ -334,7 +358,6 @@ class BlockFactory{ * NOTE: If you are registering a new block type, you will need to add it to the creative inventory yourself - it * will not automatically appear there. * - * @param Block $block * @param bool $override Whether to override existing registrations * * @throws \RuntimeException if something attempted to override an already-registered block without specifying the @@ -364,12 +387,6 @@ class BlockFactory{ /** * Returns a new Block instance with the specified ID, meta and position. - * - * @param int $id - * @param int $meta - * @param Position $pos - * - * @return Block */ public static function get(int $id, int $meta = 0, Position $pos = null) : Block{ if($meta < 0 or $meta > 0xf){ @@ -398,7 +415,7 @@ class BlockFactory{ /** * @internal - * @return \SplFixedArray + * @phpstan-return \SplFixedArray */ public static function getBlockStatesArray() : \SplFixedArray{ return self::$fullList; @@ -406,10 +423,6 @@ class BlockFactory{ /** * Returns whether a specified block ID is already registered in the block factory. - * - * @param int $id - * - * @return bool */ public static function isRegistered(int $id) : bool{ $b = self::$fullList[$id << 4]; @@ -419,11 +432,6 @@ class BlockFactory{ /** * @internal * @deprecated - * - * @param int $id - * @param int $meta - * - * @return int */ public static function toStaticRuntimeId(int $id, int $meta = 0) : int{ return RuntimeBlockMapping::toStaticRuntimeId($id, $meta); @@ -433,8 +441,6 @@ class BlockFactory{ * @deprecated * @internal * - * @param int $runtimeId - * * @return int[] [id, meta] */ public static function fromStaticRuntimeId(int $runtimeId) : array{ diff --git a/src/pocketmine/block/Chest.php b/src/pocketmine/block/Chest.php index a9cadbb1b4..47d96e33f0 100644 --- a/src/pocketmine/block/Chest.php +++ b/src/pocketmine/block/Chest.php @@ -116,7 +116,7 @@ class Chest extends Transparent{ if( !$this->getSide(Vector3::SIDE_UP)->isTransparent() or - ($chest->isPaired() and !$chest->getPair()->getBlock()->getSide(Vector3::SIDE_UP)->isTransparent()) or + (($pair = $chest->getPair()) !== null and !$pair->getBlock()->getSide(Vector3::SIDE_UP)->isTransparent()) or !$chest->canOpenWith($item->getCustomName()) ){ return true; diff --git a/src/pocketmine/block/CobblestoneWall.php b/src/pocketmine/block/CobblestoneWall.php index 98f9c51ff0..09699c1cd6 100644 --- a/src/pocketmine/block/CobblestoneWall.php +++ b/src/pocketmine/block/CobblestoneWall.php @@ -111,6 +111,9 @@ class CobblestoneWall extends Transparent{ ); } + /** + * @return bool + */ public function canConnect(Block $block){ return $block instanceof static or $block instanceof FenceGate or ($block->isSolid() and !$block->isTransparent()); } diff --git a/src/pocketmine/block/ConcretePowder.php b/src/pocketmine/block/ConcretePowder.php index 6035af8407..68b7a49d90 100644 --- a/src/pocketmine/block/ConcretePowder.php +++ b/src/pocketmine/block/ConcretePowder.php @@ -53,16 +53,10 @@ class ConcretePowder extends Fallable{ } } - /** - * @return null|Block - */ public function tickFalling() : ?Block{ return $this->checkAdjacentWater(); } - /** - * @return null|Block - */ private function checkAdjacentWater() : ?Block{ for($i = 1; $i < 6; ++$i){ //Do not check underneath if($this->getSide($i) instanceof Water){ diff --git a/src/pocketmine/block/Crops.php b/src/pocketmine/block/Crops.php index d8c2a6d193..32852472b5 100644 --- a/src/pocketmine/block/Crops.php +++ b/src/pocketmine/block/Crops.php @@ -41,7 +41,6 @@ abstract class Crops extends Flowable{ return false; } - public function onActivate(Item $item, Player $player = null) : bool{ if($this->meta < 7 and $item->getId() === Item::DYE and $item->getDamage() === 0x0F){ //Bonemeal $block = clone $this; diff --git a/src/pocketmine/block/Dandelion.php b/src/pocketmine/block/Dandelion.php index bf9f16b8ec..3071df931a 100644 --- a/src/pocketmine/block/Dandelion.php +++ b/src/pocketmine/block/Dandelion.php @@ -39,7 +39,6 @@ class Dandelion extends Flowable{ return "Dandelion"; } - public function place(Item $item, Block $blockReplace, Block $blockClicked, int $face, Vector3 $clickVector, Player $player = null) : bool{ $down = $this->getSide(Vector3::SIDE_DOWN); if($down->getId() === Block::GRASS or $down->getId() === Block::DIRT or $down->getId() === Block::FARMLAND){ diff --git a/src/pocketmine/block/Door.php b/src/pocketmine/block/Door.php index a23df95f0b..d100a4c706 100644 --- a/src/pocketmine/block/Door.php +++ b/src/pocketmine/block/Door.php @@ -29,14 +29,13 @@ use pocketmine\math\AxisAlignedBB; use pocketmine\math\Vector3; use pocketmine\Player; - abstract class Door extends Transparent{ public function isSolid() : bool{ return false; } - private function getFullDamage(){ + private function getFullDamage() : int{ $damage = $this->getDamage(); $isUp = ($damage & 0x08) > 0; diff --git a/src/pocketmine/block/DoublePlant.php b/src/pocketmine/block/DoublePlant.php index 4da0815a82..ccb8c1cbdc 100644 --- a/src/pocketmine/block/DoublePlant.php +++ b/src/pocketmine/block/DoublePlant.php @@ -68,10 +68,9 @@ class DoublePlant extends Flowable{ /** * Returns whether this double-plant has a corresponding other half. - * @return bool */ public function isValidHalfPlant() : bool{ - if($this->meta & self::BITFLAG_TOP){ + if(($this->meta & self::BITFLAG_TOP) !== 0){ $other = $this->getSide(Vector3::SIDE_DOWN); }else{ $other = $this->getSide(Vector3::SIDE_UP); @@ -103,7 +102,7 @@ class DoublePlant extends Flowable{ } public function getDrops(Item $item) : array{ - if($this->meta & self::BITFLAG_TOP){ + if(($this->meta & self::BITFLAG_TOP) !== 0){ if($this->isCompatibleWithTool($item)){ return parent::getDrops($item); } diff --git a/src/pocketmine/block/Fallable.php b/src/pocketmine/block/Fallable.php index d3fe4dec51..10cba95544 100644 --- a/src/pocketmine/block/Fallable.php +++ b/src/pocketmine/block/Fallable.php @@ -45,9 +45,6 @@ abstract class Fallable extends Solid{ } } - /** - * @return null|Block - */ public function tickFalling() : ?Block{ return null; } diff --git a/src/pocketmine/block/Farmland.php b/src/pocketmine/block/Farmland.php index 4480abc8c4..243f8af3cd 100644 --- a/src/pocketmine/block/Farmland.php +++ b/src/pocketmine/block/Farmland.php @@ -48,7 +48,6 @@ class Farmland extends Transparent{ return BlockToolType::TYPE_SHOVEL; } - protected function recalculateBoundingBox() : ?AxisAlignedBB{ return new AxisAlignedBB( $this->x, diff --git a/src/pocketmine/block/Fence.php b/src/pocketmine/block/Fence.php index 1e579c1eb4..8fd322c887 100644 --- a/src/pocketmine/block/Fence.php +++ b/src/pocketmine/block/Fence.php @@ -25,6 +25,7 @@ namespace pocketmine\block; use pocketmine\math\AxisAlignedBB; use pocketmine\math\Vector3; +use function count; abstract class Fence extends Transparent{ @@ -85,7 +86,7 @@ abstract class Fence extends Transparent{ ); } - if(empty($bbs)){ + if(count($bbs) === 0){ //centre post AABB (only needed if not connected on any axis - other BBs overlapping will do this if any connections are made) return [ new AxisAlignedBB( @@ -102,6 +103,9 @@ abstract class Fence extends Transparent{ return $bbs; } + /** + * @return bool + */ public function canConnect(Block $block){ return $block instanceof static or $block instanceof FenceGate or ($block->isSolid() and !$block->isTransparent()); } diff --git a/src/pocketmine/block/FenceGate.php b/src/pocketmine/block/FenceGate.php index 8f08a10c91..5f5a4d3918 100644 --- a/src/pocketmine/block/FenceGate.php +++ b/src/pocketmine/block/FenceGate.php @@ -39,7 +39,6 @@ class FenceGate extends Transparent{ return BlockToolType::TYPE_AXE; } - protected function recalculateBoundingBox() : ?AxisAlignedBB{ if(($this->getDamage() & 0x04) > 0){ diff --git a/src/pocketmine/block/Furnace.php b/src/pocketmine/block/Furnace.php index eb8acd9ed5..1a75fc837e 100644 --- a/src/pocketmine/block/Furnace.php +++ b/src/pocketmine/block/Furnace.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\block; - class Furnace extends BurningFurnace{ protected $id = self::FURNACE; diff --git a/src/pocketmine/block/GlazedTerracotta.php b/src/pocketmine/block/GlazedTerracotta.php index 336b513257..9e38626660 100644 --- a/src/pocketmine/block/GlazedTerracotta.php +++ b/src/pocketmine/block/GlazedTerracotta.php @@ -1,6 +1,5 @@ isTransparent()){ $faces = [ diff --git a/src/pocketmine/block/Leaves.php b/src/pocketmine/block/Leaves.php index 55985964e5..788e4a7812 100644 --- a/src/pocketmine/block/Leaves.php +++ b/src/pocketmine/block/Leaves.php @@ -39,6 +39,7 @@ class Leaves extends Transparent{ public const DARK_OAK = 1; protected $id = self::LEAVES; + /** @var int */ protected $woodType = self::WOOD; public function __construct(int $meta = 0){ @@ -67,8 +68,11 @@ class Leaves extends Transparent{ return true; } - - protected function findLog(Block $pos, array $visited, int $distance, ?int $fromSide = null) : bool{ + /** + * @param true[] $visited reference parameter + * @phpstan-param array $visited + */ + protected function findLog(Block $pos, array &$visited, int $distance, ?int $fromSide = null) : bool{ $index = $pos->x . "." . $pos->y . "." . $pos->z; if(isset($visited[$index])){ return false; @@ -168,7 +172,7 @@ class Leaves extends Transparent{ } public function getDrops(Item $item) : array{ - if($item->getBlockToolType() & BlockToolType::TYPE_SHEARS){ + if(($item->getBlockToolType() & BlockToolType::TYPE_SHEARS) !== 0){ return $this->getDropsForCompatibleTool($item); } diff --git a/src/pocketmine/block/Leaves2.php b/src/pocketmine/block/Leaves2.php index bb62ac2de7..3abe14aec5 100644 --- a/src/pocketmine/block/Leaves2.php +++ b/src/pocketmine/block/Leaves2.php @@ -29,6 +29,7 @@ use pocketmine\item\ItemFactory; class Leaves2 extends Leaves{ protected $id = self::LEAVES2; + /** @var int */ protected $woodType = self::WOOD2; public function getName() : string{ diff --git a/src/pocketmine/block/Liquid.php b/src/pocketmine/block/Liquid.php index 878b15cde1..255dc16315 100644 --- a/src/pocketmine/block/Liquid.php +++ b/src/pocketmine/block/Liquid.php @@ -38,6 +38,7 @@ use function min; abstract class Liquid extends Transparent{ + /** @var int */ public $adjacentSources = 0; /** @var Vector3|null */ @@ -90,6 +91,9 @@ abstract class Liquid extends Transparent{ abstract public function getBucketEmptySound() : int; + /** + * @return float + */ public function getFluidHeightPercent(){ $d = $this->meta; if($d >= 8){ @@ -207,8 +211,6 @@ abstract class Liquid extends Transparent{ /** * Returns how many liquid levels are lost per block flowed horizontally. Affects how far the liquid can flow. - * - * @return int */ public function getFlowDecayPerBlock() : int{ return 1; @@ -430,6 +432,9 @@ abstract class Liquid extends Transparent{ return ($decay >= 0 && $blockDecay >= $decay) ? $decay : $blockDecay; } + /** + * @return void + */ protected function checkForHarden(){ } diff --git a/src/pocketmine/block/MossyCobblestone.php b/src/pocketmine/block/MossyCobblestone.php index c9b83b6c8e..c9427c9f9f 100644 --- a/src/pocketmine/block/MossyCobblestone.php +++ b/src/pocketmine/block/MossyCobblestone.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\block; - class MossyCobblestone extends Cobblestone{ protected $id = self::MOSSY_COBBLESTONE; diff --git a/src/pocketmine/block/NetherWartPlant.php b/src/pocketmine/block/NetherWartPlant.php index acb0296f7a..7428730ac5 100644 --- a/src/pocketmine/block/NetherWartPlant.php +++ b/src/pocketmine/block/NetherWartPlant.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\block; - use pocketmine\event\block\BlockGrowEvent; use pocketmine\item\Item; use pocketmine\item\ItemFactory; diff --git a/src/pocketmine/block/SignPost.php b/src/pocketmine/block/SignPost.php index 273f8c640b..bba195a223 100644 --- a/src/pocketmine/block/SignPost.php +++ b/src/pocketmine/block/SignPost.php @@ -57,7 +57,6 @@ class SignPost extends Transparent{ return null; } - public function place(Item $item, Block $blockReplace, Block $blockClicked, int $face, Vector3 $clickVector, Player $player = null) : bool{ if($face !== Vector3::SIDE_DOWN){ diff --git a/src/pocketmine/block/Sponge.php b/src/pocketmine/block/Sponge.php index 4553f6fc57..a7a217165b 100644 --- a/src/pocketmine/block/Sponge.php +++ b/src/pocketmine/block/Sponge.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\block; - class Sponge extends Solid{ protected $id = self::SPONGE; diff --git a/src/pocketmine/block/TNT.php b/src/pocketmine/block/TNT.php index 5ca3f9d0e8..44cfb6fbc9 100644 --- a/src/pocketmine/block/TNT.php +++ b/src/pocketmine/block/TNT.php @@ -74,6 +74,9 @@ class TNT extends Solid{ } } + /** + * @return void + */ public function ignite(int $fuse = 80){ $this->getLevel()->setBlock($this, BlockFactory::get(Block::AIR), true); diff --git a/src/pocketmine/block/Thin.php b/src/pocketmine/block/Thin.php index 4364f80985..a84ec34c15 100644 --- a/src/pocketmine/block/Thin.php +++ b/src/pocketmine/block/Thin.php @@ -25,6 +25,7 @@ namespace pocketmine\block; use pocketmine\math\AxisAlignedBB; use pocketmine\math\Vector3; +use function count; abstract class Thin extends Transparent{ @@ -77,7 +78,7 @@ abstract class Thin extends Transparent{ ); } - if(empty($bbs)){ + if(count($bbs) === 0){ //centre post AABB (only needed if not connected on any axis - other BBs overlapping will do this if any connections are made) return [ new AxisAlignedBB( diff --git a/src/pocketmine/block/Transparent.php b/src/pocketmine/block/Transparent.php index 8654cc4004..9c3f28ed04 100644 --- a/src/pocketmine/block/Transparent.php +++ b/src/pocketmine/block/Transparent.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\block; - abstract class Transparent extends Block{ public function isTransparent() : bool{ diff --git a/src/pocketmine/block/Vine.php b/src/pocketmine/block/Vine.php index c451d0bae3..dadc7a3298 100644 --- a/src/pocketmine/block/Vine.php +++ b/src/pocketmine/block/Vine.php @@ -197,7 +197,7 @@ class Vine extends Flowable{ } public function getDrops(Item $item) : array{ - if($item->getBlockToolType() & BlockToolType::TYPE_SHEARS){ + if(($item->getBlockToolType() & BlockToolType::TYPE_SHEARS) !== 0){ return $this->getDropsForCompatibleTool($item); } diff --git a/src/pocketmine/block/WaterLily.php b/src/pocketmine/block/WaterLily.php index 5327857d54..8d4ebc7cff 100644 --- a/src/pocketmine/block/WaterLily.php +++ b/src/pocketmine/block/WaterLily.php @@ -55,7 +55,6 @@ class WaterLily extends Flowable{ ); } - public function place(Item $item, Block $blockReplace, Block $blockClicked, int $face, Vector3 $clickVector, Player $player = null) : bool{ if($blockClicked instanceof Water){ $up = $blockClicked->getSide(Vector3::SIDE_UP); diff --git a/src/pocketmine/block/Wood2.php b/src/pocketmine/block/Wood2.php index f452aaef8b..a3bad03a25 100644 --- a/src/pocketmine/block/Wood2.php +++ b/src/pocketmine/block/Wood2.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\block; - class Wood2 extends Wood{ public const ACACIA = 0; diff --git a/src/pocketmine/command/Command.php b/src/pocketmine/command/Command.php index 33b8a645b1..4bb0352ef2 100644 --- a/src/pocketmine/command/Command.php +++ b/src/pocketmine/command/Command.php @@ -50,9 +50,7 @@ abstract class Command{ /** @var string[] */ private $aliases = []; - /** - * @var string[] - */ + /** @var string[] */ private $activeAliases = []; /** @var CommandMap|null */ @@ -67,16 +65,13 @@ abstract class Command{ /** @var string|null */ private $permission = null; - /** @var string */ + /** @var string|null */ private $permissionMessage = null; - /** @var TimingsHandler */ - public $timings; + /** @var TimingsHandler|null */ + public $timings = null; /** - * @param string $name - * @param string $description - * @param string $usageMessage * @param string[] $aliases */ public function __construct(string $name, string $description = "", string $usageMessage = null, array $aliases = []){ @@ -88,18 +83,13 @@ abstract class Command{ } /** - * @param CommandSender $sender - * @param string $commandLabel - * @param string[] $args + * @param string[] $args * * @return mixed * @throws CommandException */ abstract public function execute(CommandSender $sender, string $commandLabel, array $args); - /** - * @return string - */ public function getName() : string{ return $this->name; } @@ -111,19 +101,13 @@ abstract class Command{ return $this->permission; } - /** - * @param string|null $permission + * @return void */ public function setPermission(string $permission = null){ $this->permission = $permission; } - /** - * @param CommandSender $target - * - * @return bool - */ public function testPermission(CommandSender $target) : bool{ if($this->testPermissionSilent($target)){ return true; @@ -138,11 +122,6 @@ abstract class Command{ return false; } - /** - * @param CommandSender $target - * - * @return bool - */ public function testPermissionSilent(CommandSender $target) : bool{ if($this->permission === null or $this->permission === ""){ return true; @@ -157,9 +136,6 @@ abstract class Command{ return false; } - /** - * @return string - */ public function getLabel() : string{ return $this->label; } @@ -181,10 +157,6 @@ abstract class Command{ /** * Registers the command into a Command map - * - * @param CommandMap $commandMap - * - * @return bool */ public function register(CommandMap $commandMap) : bool{ if($this->allowChangesFrom($commandMap)){ @@ -196,11 +168,6 @@ abstract class Command{ return false; } - /** - * @param CommandMap $commandMap - * - * @return bool - */ public function unregister(CommandMap $commandMap) : bool{ if($this->allowChangesFrom($commandMap)){ $this->commandMap = null; @@ -213,18 +180,10 @@ abstract class Command{ return false; } - /** - * @param CommandMap $commandMap - * - * @return bool - */ private function allowChangesFrom(CommandMap $commandMap) : bool{ return $this->commandMap === null or $this->commandMap === $commandMap; } - /** - * @return bool - */ public function isRegistered() : bool{ return $this->commandMap !== null; } @@ -236,29 +195,22 @@ abstract class Command{ return $this->activeAliases; } - /** - * @return string|null - */ public function getPermissionMessage() : ?string{ return $this->permissionMessage; } - /** - * @return string - */ public function getDescription() : string{ return $this->description; } - /** - * @return string - */ public function getUsage() : string{ return $this->usageMessage; } /** * @param string[] $aliases + * + * @return void */ public function setAliases(array $aliases){ $this->aliases = $aliases; @@ -268,30 +220,30 @@ abstract class Command{ } /** - * @param string $description + * @return void */ public function setDescription(string $description){ $this->description = $description; } /** - * @param string $permissionMessage + * @return void */ public function setPermissionMessage(string $permissionMessage){ $this->permissionMessage = $permissionMessage; } /** - * @param string $usage + * @return void */ public function setUsage(string $usage){ $this->usageMessage = $usage; } /** - * @param CommandSender $source * @param TextContainer|string $message - * @param bool $sendToSource + * + * @return void */ public static function broadcastCommandMessage(CommandSender $source, $message, bool $sendToSource = true){ if($message instanceof TextContainer){ @@ -326,9 +278,6 @@ abstract class Command{ } } - /** - * @return string - */ public function __toString() : string{ return $this->name; } diff --git a/src/pocketmine/command/CommandExecutor.php b/src/pocketmine/command/CommandExecutor.php index fcc75f15ff..fb989590de 100644 --- a/src/pocketmine/command/CommandExecutor.php +++ b/src/pocketmine/command/CommandExecutor.php @@ -23,16 +23,10 @@ declare(strict_types=1); namespace pocketmine\command; - interface CommandExecutor{ /** - * @param CommandSender $sender - * @param Command $command - * @param string $label * @param string[] $args - * - * @return bool */ public function onCommand(CommandSender $sender, Command $command, string $label, array $args) : bool; diff --git a/src/pocketmine/command/CommandMap.php b/src/pocketmine/command/CommandMap.php index 837d6e2bdb..149f36868e 100644 --- a/src/pocketmine/command/CommandMap.php +++ b/src/pocketmine/command/CommandMap.php @@ -23,30 +23,17 @@ declare(strict_types=1); namespace pocketmine\command; - interface CommandMap{ /** - * @param string $fallbackPrefix * @param Command[] $commands + * + * @return void */ public function registerAll(string $fallbackPrefix, array $commands); - /** - * @param string $fallbackPrefix - * @param Command $command - * @param string|null $label - * - * @return bool - */ public function register(string $fallbackPrefix, Command $command, string $label = null) : bool; - /** - * @param CommandSender $sender - * @param string $cmdLine - * - * @return bool - */ public function dispatch(CommandSender $sender, string $cmdLine) : bool; /** @@ -55,11 +42,8 @@ interface CommandMap{ public function clearCommands(); /** - * @param string $name - * * @return Command|null */ public function getCommand(string $name); - } diff --git a/src/pocketmine/command/CommandReader.php b/src/pocketmine/command/CommandReader.php index 1aaa1721d2..656d824646 100644 --- a/src/pocketmine/command/CommandReader.php +++ b/src/pocketmine/command/CommandReader.php @@ -54,7 +54,9 @@ class CommandReader extends Thread{ /** @var \Threaded */ protected $buffer; + /** @var bool */ private $shutdown = false; + /** @var int */ private $type = self::TYPE_STREAM; /** @var SleeperNotifier|null */ @@ -71,6 +73,9 @@ class CommandReader extends Thread{ } } + /** + * @return void + */ public function shutdown(){ $this->shutdown = true; } @@ -94,7 +99,7 @@ class CommandReader extends Thread{ throw new \ThreadException($message); } - private function initStdin(){ + private function initStdin() : void{ if(is_resource(self::$stdin)){ fclose(self::$stdin); } @@ -111,8 +116,6 @@ class CommandReader extends Thread{ * Checks if the specified stream is a FIFO pipe. * * @param resource $stream - * - * @return bool */ private function isPipe($stream) : bool{ return is_resource($stream) and (!stream_isatty($stream) or ((fstat($stream)["mode"] & 0170000) === 0010000)); @@ -151,7 +154,7 @@ class CommandReader extends Thread{ case self::TYPE_PIPED: if(($raw = fgets(self::$stdin)) === false){ //broken pipe or EOF $this->initStdin(); - $this->synchronized(function(){ + $this->synchronized(function() : void{ $this->wait(200000); }); //prevent CPU waste if it's end of pipe return true; //loop back round @@ -185,6 +188,9 @@ class CommandReader extends Thread{ return null; } + /** + * @return void + */ public function run(){ $this->registerClassLoader(); diff --git a/src/pocketmine/command/CommandSender.php b/src/pocketmine/command/CommandSender.php index 97fed1b297..63406b2620 100644 --- a/src/pocketmine/command/CommandSender.php +++ b/src/pocketmine/command/CommandSender.php @@ -31,6 +31,8 @@ interface CommandSender extends Permissible{ /** * @param TextContainer|string $message + * + * @return void */ public function sendMessage($message); @@ -39,23 +41,18 @@ interface CommandSender extends Permissible{ */ public function getServer(); - /** - * @return string - */ public function getName() : string; /** * Returns the line height of the command-sender's screen. Used for determining sizes for command output pagination * such as in the /help command. - * - * @return int */ public function getScreenLineHeight() : int; /** * Sets the line height used for command output pagination for this command sender. `null` will reset it to default. * - * @param int|null $height + * @return void */ public function setScreenLineHeight(int $height = null); } diff --git a/src/pocketmine/command/ConsoleCommandSender.php b/src/pocketmine/command/ConsoleCommandSender.php index 32c422a9c5..2ce7fd9ce4 100644 --- a/src/pocketmine/command/ConsoleCommandSender.php +++ b/src/pocketmine/command/ConsoleCommandSender.php @@ -37,6 +37,7 @@ use const PHP_INT_MAX; class ConsoleCommandSender implements CommandSender{ + /** @var PermissibleBase */ private $perm; /** @var int|null */ @@ -48,8 +49,6 @@ class ConsoleCommandSender implements CommandSender{ /** * @param Permission|string $name - * - * @return bool */ public function isPermissionSet($name) : bool{ return $this->perm->isPermissionSet($name); @@ -57,27 +56,16 @@ class ConsoleCommandSender implements CommandSender{ /** * @param Permission|string $name - * - * @return bool */ public function hasPermission($name) : bool{ return $this->perm->hasPermission($name); } - /** - * @param Plugin $plugin - * @param string $name - * @param bool $value - * - * @return PermissionAttachment - */ public function addAttachment(Plugin $plugin, string $name = null, bool $value = null) : PermissionAttachment{ return $this->perm->addAttachment($plugin, $name, $value); } /** - * @param PermissionAttachment $attachment - * * @return void */ public function removeAttachment(PermissionAttachment $attachment){ @@ -104,6 +92,8 @@ class ConsoleCommandSender implements CommandSender{ /** * @param TextContainer|string $message + * + * @return void */ public function sendMessage($message){ if($message instanceof TextContainer){ @@ -117,22 +107,16 @@ class ConsoleCommandSender implements CommandSender{ } } - /** - * @return string - */ public function getName() : string{ return "CONSOLE"; } - /** - * @return bool - */ public function isOp() : bool{ return true; } /** - * @param bool $value + * @return void */ public function setOp(bool $value){ diff --git a/src/pocketmine/command/FormattedCommandAlias.php b/src/pocketmine/command/FormattedCommandAlias.php index 87655da029..f6e11f5e5d 100644 --- a/src/pocketmine/command/FormattedCommandAlias.php +++ b/src/pocketmine/command/FormattedCommandAlias.php @@ -32,10 +32,10 @@ use function strpos; use function substr; class FormattedCommandAlias extends Command{ + /** @var string[] */ private $formatStrings = []; /** - * @param string $alias * @param string[] $formatStrings */ public function __construct(string $alias, array $formatStrings){ @@ -65,10 +65,7 @@ class FormattedCommandAlias extends Command{ } /** - * @param string $formatString - * @param array $args - * - * @return string + * @param string[] $args */ private function buildCommand(string $formatString, array $args) : string{ $index = strpos($formatString, '$'); @@ -143,13 +140,6 @@ class FormattedCommandAlias extends Command{ return $formatString; } - /** - * @param int $i - * @param int $j - * @param int $k - * - * @return bool - */ private static function inRange(int $i, int $j, int $k) : bool{ return $i >= $j and $i <= $k; } diff --git a/src/pocketmine/command/PluginCommand.php b/src/pocketmine/command/PluginCommand.php index 4c7757b590..16e3bc1831 100644 --- a/src/pocketmine/command/PluginCommand.php +++ b/src/pocketmine/command/PluginCommand.php @@ -34,10 +34,6 @@ class PluginCommand extends Command implements PluginIdentifiableCommand{ /** @var CommandExecutor */ private $executor; - /** - * @param string $name - * @param Plugin $owner - */ public function __construct(string $name, Plugin $owner){ parent::__construct($name); $this->owningPlugin = $owner; @@ -69,15 +65,12 @@ class PluginCommand extends Command implements PluginIdentifiableCommand{ } /** - * @param CommandExecutor $executor + * @return void */ public function setExecutor(CommandExecutor $executor){ $this->executor = $executor; } - /** - * @return Plugin - */ public function getPlugin() : Plugin{ return $this->owningPlugin; } diff --git a/src/pocketmine/command/PluginIdentifiableCommand.php b/src/pocketmine/command/PluginIdentifiableCommand.php index 035bdc3277..02e85f7e92 100644 --- a/src/pocketmine/command/PluginIdentifiableCommand.php +++ b/src/pocketmine/command/PluginIdentifiableCommand.php @@ -27,8 +27,5 @@ use pocketmine\plugin\Plugin; interface PluginIdentifiableCommand{ - /** - * @return Plugin - */ public function getPlugin() : Plugin; } diff --git a/src/pocketmine/command/RemoteConsoleCommandSender.php b/src/pocketmine/command/RemoteConsoleCommandSender.php index 054d7ad881..48e33a1275 100644 --- a/src/pocketmine/command/RemoteConsoleCommandSender.php +++ b/src/pocketmine/command/RemoteConsoleCommandSender.php @@ -41,6 +41,9 @@ class RemoteConsoleCommandSender extends ConsoleCommandSender{ $this->messages .= trim($message, "\r\n") . "\n"; } + /** + * @return string + */ public function getMessage(){ return $this->messages; } diff --git a/src/pocketmine/command/SimpleCommandMap.php b/src/pocketmine/command/SimpleCommandMap.php index d7296f82f8..02926d0925 100644 --- a/src/pocketmine/command/SimpleCommandMap.php +++ b/src/pocketmine/command/SimpleCommandMap.php @@ -72,6 +72,7 @@ use function explode; use function implode; use function min; use function preg_match_all; +use function strcasecmp; use function stripslashes; use function strpos; use function strtolower; @@ -79,9 +80,7 @@ use function trim; class SimpleCommandMap implements CommandMap{ - /** - * @var Command[] - */ + /** @var Command[] */ protected $knownCommands = []; /** @var Server */ @@ -92,7 +91,7 @@ class SimpleCommandMap implements CommandMap{ $this->setDefaultCommands(); } - private function setDefaultCommands(){ + private function setDefaultCommands() : void{ $this->registerAll("pocketmine", [ new BanCommand("ban"), new BanIpCommand("ban-ip"), @@ -137,20 +136,12 @@ class SimpleCommandMap implements CommandMap{ ]); } - public function registerAll(string $fallbackPrefix, array $commands){ foreach($commands as $command){ $this->register($fallbackPrefix, $command); } } - /** - * @param string $fallbackPrefix - * @param Command $command - * @param string|null $label - * - * @return bool - */ public function register(string $fallbackPrefix, Command $command, string $label = null) : bool{ if($label === null){ $label = $command->getName(); @@ -177,11 +168,6 @@ class SimpleCommandMap implements CommandMap{ return $registered; } - /** - * @param Command $command - * - * @return bool - */ public function unregister(Command $command) : bool{ foreach($this->knownCommands as $lbl => $cmd){ if($cmd === $command){ @@ -194,21 +180,13 @@ class SimpleCommandMap implements CommandMap{ return true; } - /** - * @param Command $command - * @param bool $isAlias - * @param string $fallbackPrefix - * @param string $label - * - * @return bool - */ private function registerAlias(Command $command, bool $isAlias, string $fallbackPrefix, string $label) : bool{ $this->knownCommands[$fallbackPrefix . ":" . $label] = $command; if(($command instanceof VanillaCommand or $isAlias) and isset($this->knownCommands[$label])){ return false; } - if(isset($this->knownCommands[$label]) and $this->knownCommands[$label]->getLabel() !== null and $this->knownCommands[$label]->getLabel() === $label){ + if(isset($this->knownCommands[$label]) and $this->knownCommands[$label]->getLabel() === $label){ return false; } @@ -226,8 +204,8 @@ class SimpleCommandMap implements CommandMap{ * This method is intended to provide capability for handling commands with spaces in their name. * The referenced parameters will be modified accordingly depending on the resulting matched command. * - * @param string &$commandName - * @param string[] &$args + * @param string $commandName reference parameter + * @param string[] $args reference parameter * * @return Command|null */ @@ -296,7 +274,6 @@ class SimpleCommandMap implements CommandMap{ return $this->knownCommands; } - /** * @return void */ @@ -318,22 +295,21 @@ class SimpleCommandMap implements CommandMap{ $commandName = ""; $command = $this->matchCommand($commandName, $args); - if($command === null){ $bad[] = $commandString; - }elseif($commandName === $alias){ + }elseif(strcasecmp($commandName, $alias) === 0){ $recursive[] = $commandString; }else{ $targets[] = $commandString; } } - if(!empty($recursive)){ + if(count($recursive) > 0){ $this->server->getLogger()->warning($this->server->getLanguage()->translateString("pocketmine.command.alias.recursive", [$alias, implode(", ", $recursive)])); continue; } - if(!empty($bad)){ + if(count($bad) > 0){ $this->server->getLogger()->warning($this->server->getLanguage()->translateString("pocketmine.command.alias.notFound", [$alias, implode(", ", $bad)])); continue; } diff --git a/src/pocketmine/command/defaults/BanIpCommand.php b/src/pocketmine/command/defaults/BanIpCommand.php index 38c8d5f458..e60b9b219f 100644 --- a/src/pocketmine/command/defaults/BanIpCommand.php +++ b/src/pocketmine/command/defaults/BanIpCommand.php @@ -75,7 +75,7 @@ class BanIpCommand extends VanillaCommand{ return true; } - private function processIPBan(string $ip, CommandSender $sender, string $reason){ + private function processIPBan(string $ip, CommandSender $sender, string $reason) : void{ $sender->getServer()->getIPBans()->addBan($ip, $reason, null, $sender->getName()); foreach($sender->getServer()->getOnlinePlayers() as $player){ diff --git a/src/pocketmine/command/defaults/BanListCommand.php b/src/pocketmine/command/defaults/BanListCommand.php index ca75f97678..90212f8154 100644 --- a/src/pocketmine/command/defaults/BanListCommand.php +++ b/src/pocketmine/command/defaults/BanListCommand.php @@ -63,7 +63,7 @@ class BanListCommand extends VanillaCommand{ } $list = $list->getEntries(); - $message = implode(", ", array_map(function(BanEntry $entry){ + $message = implode(", ", array_map(function(BanEntry $entry) : string{ return $entry->getName(); }, $list)); diff --git a/src/pocketmine/command/defaults/EffectCommand.php b/src/pocketmine/command/defaults/EffectCommand.php index e036021a3a..3da54604ab 100644 --- a/src/pocketmine/command/defaults/EffectCommand.php +++ b/src/pocketmine/command/defaults/EffectCommand.php @@ -76,7 +76,7 @@ class EffectCommand extends VanillaCommand{ } if($effect === null){ - $sender->sendMessage(new TranslationContainer(TextFormat::RED . "%commands.effect.notFound", [(string) $args[1]])); + $sender->sendMessage(new TranslationContainer(TextFormat::RED . "%commands.effect.notFound", [$args[1]])); return true; } @@ -124,7 +124,6 @@ class EffectCommand extends VanillaCommand{ self::broadcastCommandMessage($sender, new TranslationContainer("%commands.effect.success", [$effect->getName(), $instance->getAmplifier(), $player->getDisplayName(), $instance->getDuration() / 20, $effect->getId()])); } - return true; } } diff --git a/src/pocketmine/command/defaults/EnchantCommand.php b/src/pocketmine/command/defaults/EnchantCommand.php index c40886297a..74dd99d15d 100644 --- a/src/pocketmine/command/defaults/EnchantCommand.php +++ b/src/pocketmine/command/defaults/EnchantCommand.php @@ -88,7 +88,6 @@ class EnchantCommand extends VanillaCommand{ $item->addEnchantment(new EnchantmentInstance($enchantment, $level)); $player->getInventory()->setItemInHand($item); - self::broadcastCommandMessage($sender, new TranslationContainer("%commands.enchant.success", [$player->getName()])); return true; } diff --git a/src/pocketmine/command/defaults/HelpCommand.php b/src/pocketmine/command/defaults/HelpCommand.php index def7c3246c..5e761d1807 100644 --- a/src/pocketmine/command/defaults/HelpCommand.php +++ b/src/pocketmine/command/defaults/HelpCommand.php @@ -57,22 +57,22 @@ class HelpCommand extends VanillaCommand{ } if(count($args) === 0){ - $command = ""; + $commandName = ""; $pageNumber = 1; }elseif(is_numeric($args[count($args) - 1])){ $pageNumber = (int) array_pop($args); if($pageNumber <= 0){ $pageNumber = 1; } - $command = implode(" ", $args); + $commandName = implode(" ", $args); }else{ - $command = implode(" ", $args); + $commandName = implode(" ", $args); $pageNumber = 1; } $pageHeight = $sender->getScreenLineHeight(); - if($command === ""){ + if($commandName === ""){ /** @var Command[][] $commands */ $commands = []; foreach($sender->getServer()->getCommandMap()->getCommands() as $command){ @@ -82,7 +82,7 @@ class HelpCommand extends VanillaCommand{ } ksort($commands, SORT_NATURAL | SORT_FLAG_CASE); $commands = array_chunk($commands, $pageHeight); - $pageNumber = (int) min(count($commands), $pageNumber); + $pageNumber = min(count($commands), $pageNumber); if($pageNumber < 1){ $pageNumber = 1; } @@ -95,7 +95,7 @@ class HelpCommand extends VanillaCommand{ return true; }else{ - if(($cmd = $sender->getServer()->getCommandMap()->getCommand(strtolower($command))) instanceof Command){ + if(($cmd = $sender->getServer()->getCommandMap()->getCommand(strtolower($commandName))) instanceof Command){ if($cmd->testPermissionSilent($sender)){ $message = TextFormat::YELLOW . "--------- " . TextFormat::WHITE . " Help: /" . $cmd->getName() . TextFormat::YELLOW . " ---------\n"; $message .= TextFormat::GOLD . "Description: " . TextFormat::WHITE . $cmd->getDescription() . "\n"; @@ -105,7 +105,7 @@ class HelpCommand extends VanillaCommand{ return true; } } - $sender->sendMessage(TextFormat::RED . "No help for " . strtolower($command)); + $sender->sendMessage(TextFormat::RED . "No help for " . strtolower($commandName)); return true; } diff --git a/src/pocketmine/command/defaults/KickCommand.php b/src/pocketmine/command/defaults/KickCommand.php index 1d10cb2def..aebc688ca6 100644 --- a/src/pocketmine/command/defaults/KickCommand.php +++ b/src/pocketmine/command/defaults/KickCommand.php @@ -68,7 +68,6 @@ class KickCommand extends VanillaCommand{ $sender->sendMessage(new TranslationContainer(TextFormat::RED . "%commands.generic.player.notFound")); } - return true; } } diff --git a/src/pocketmine/command/defaults/ListCommand.php b/src/pocketmine/command/defaults/ListCommand.php index f87248096b..6915ee39ad 100644 --- a/src/pocketmine/command/defaults/ListCommand.php +++ b/src/pocketmine/command/defaults/ListCommand.php @@ -47,9 +47,9 @@ class ListCommand extends VanillaCommand{ return true; } - $playerNames = array_map(function(Player $player){ + $playerNames = array_map(function(Player $player) : string{ return $player->getName(); - }, array_filter($sender->getServer()->getOnlinePlayers(), function(Player $player) use ($sender){ + }, array_filter($sender->getServer()->getOnlinePlayers(), function(Player $player) use ($sender) : bool{ return $player->isOnline() and (!($sender instanceof Player) or $sender->canSee($player)); })); diff --git a/src/pocketmine/command/defaults/ParticleCommand.php b/src/pocketmine/command/defaults/ParticleCommand.php index 687a4e6e75..7b89b53728 100644 --- a/src/pocketmine/command/defaults/ParticleCommand.php +++ b/src/pocketmine/command/defaults/ParticleCommand.php @@ -119,7 +119,6 @@ class ParticleCommand extends VanillaCommand{ return true; } - $sender->sendMessage(new TranslationContainer("commands.particle.success", [$name, $count])); $random = new Random((int) (microtime(true) * 1000) + mt_rand()); @@ -137,13 +136,6 @@ class ParticleCommand extends VanillaCommand{ } /** - * @param string $name - * @param Vector3 $pos - * @param float $xd - * @param float $yd - * @param float $zd - * @param int|null $data - * * @return Particle|null */ private function getParticle(string $name, Vector3 $pos, float $xd, float $yd, float $zd, int $data = null){ diff --git a/src/pocketmine/command/defaults/TeleportCommand.php b/src/pocketmine/command/defaults/TeleportCommand.php index 353a33f4fe..c53bd92400 100644 --- a/src/pocketmine/command/defaults/TeleportCommand.php +++ b/src/pocketmine/command/defaults/TeleportCommand.php @@ -52,7 +52,7 @@ class TeleportCommand extends VanillaCommand{ return true; } - $args = array_values(array_filter($args, function($arg){ + $args = array_values(array_filter($args, function(string $arg) : bool{ return $arg !== ""; })); if(count($args) < 1 or count($args) > 6){ diff --git a/src/pocketmine/command/defaults/TimeCommand.php b/src/pocketmine/command/defaults/TimeCommand.php index 2b358140f1..bd94e2ae52 100644 --- a/src/pocketmine/command/defaults/TimeCommand.php +++ b/src/pocketmine/command/defaults/TimeCommand.php @@ -85,7 +85,6 @@ class TimeCommand extends VanillaCommand{ return true; } - if(count($args) < 2){ throw new InvalidCommandSyntaxException(); } diff --git a/src/pocketmine/command/defaults/TimingsCommand.php b/src/pocketmine/command/defaults/TimingsCommand.php index 4251ac33c6..fea5010b7b 100644 --- a/src/pocketmine/command/defaults/TimingsCommand.php +++ b/src/pocketmine/command/defaults/TimingsCommand.php @@ -126,18 +126,25 @@ class TimingsCommand extends VanillaCommand{ /** @var string */ private $host; + /** + * @param string[] $data + * @phpstan-param array $data + */ public function __construct(CommandSender $sender, string $host, string $agent, array $data){ parent::__construct([ - ["page" => "https://$host?upload=true", "extraOpts" => [ - CURLOPT_HTTPHEADER => [ - "User-Agent: $agent", - "Content-Type: application/x-www-form-urlencoded" - ], - CURLOPT_POST => true, - CURLOPT_POSTFIELDS => http_build_query($data), - CURLOPT_AUTOREFERER => false, - CURLOPT_FOLLOWLOCATION => false - ]] + [ + "page" => "https://$host?upload=true", + "extraOpts" => [ + CURLOPT_HTTPHEADER => [ + "User-Agent: $agent", + "Content-Type: application/x-www-form-urlencoded" + ], + CURLOPT_POST => true, + CURLOPT_POSTFIELDS => http_build_query($data), + CURLOPT_AUTOREFERER => false, + CURLOPT_FOLLOWLOCATION => false + ] + ] ], $sender); $this->host = $host; } diff --git a/src/pocketmine/command/defaults/TransferServerCommand.php b/src/pocketmine/command/defaults/TransferServerCommand.php index c69a8621b5..f0e0027771 100644 --- a/src/pocketmine/command/defaults/TransferServerCommand.php +++ b/src/pocketmine/command/defaults/TransferServerCommand.php @@ -21,10 +21,8 @@ declare(strict_types=1); - namespace pocketmine\command\defaults; - use pocketmine\command\CommandSender; use pocketmine\command\utils\InvalidCommandSyntaxException; use pocketmine\Player; diff --git a/src/pocketmine/command/defaults/VanillaCommand.php b/src/pocketmine/command/defaults/VanillaCommand.php index 50c5313a15..c4b821e6da 100644 --- a/src/pocketmine/command/defaults/VanillaCommand.php +++ b/src/pocketmine/command/defaults/VanillaCommand.php @@ -36,12 +36,7 @@ abstract class VanillaCommand extends Command{ public const MIN_COORD = -30000000; /** - * @param CommandSender $sender * @param mixed $value - * @param int $min - * @param int $max - * - * @return int */ protected function getInteger(CommandSender $sender, $value, int $min = self::MIN_COORD, int $max = self::MAX_COORD) : int{ $i = (int) $value; @@ -55,15 +50,6 @@ abstract class VanillaCommand extends Command{ return $i; } - /** - * @param float $original - * @param CommandSender $sender - * @param string $input - * @param float $min - * @param float $max - * - * @return float - */ protected function getRelativeDouble(float $original, CommandSender $sender, string $input, float $min = self::MIN_COORD, float $max = self::MAX_COORD) : float{ if($input[0] === "~"){ $value = $this->getDouble($sender, substr($input, 1)); @@ -75,12 +61,7 @@ abstract class VanillaCommand extends Command{ } /** - * @param CommandSender $sender * @param mixed $value - * @param float $min - * @param float $max - * - * @return float */ protected function getDouble(CommandSender $sender, $value, float $min = self::MIN_COORD, float $max = self::MAX_COORD) : float{ $i = (double) $value; diff --git a/src/pocketmine/command/defaults/VersionCommand.php b/src/pocketmine/command/defaults/VersionCommand.php index b6140939bd..e132671bd1 100644 --- a/src/pocketmine/command/defaults/VersionCommand.php +++ b/src/pocketmine/command/defaults/VersionCommand.php @@ -84,7 +84,7 @@ class VersionCommand extends VanillaCommand{ return true; } - private function describeToSender(Plugin $plugin, CommandSender $sender){ + private function describeToSender(Plugin $plugin, CommandSender $sender) : void{ $desc = $plugin->getDescription(); $sender->sendMessage(TextFormat::DARK_GREEN . $desc->getName() . TextFormat::WHITE . " version " . TextFormat::DARK_GREEN . $desc->getVersion()); diff --git a/src/pocketmine/entity/Ageable.php b/src/pocketmine/entity/Ageable.php index cc835dbbfb..bc74036d8e 100644 --- a/src/pocketmine/entity/Ageable.php +++ b/src/pocketmine/entity/Ageable.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\entity; - interface Ageable{ public function isBaby() : bool; } diff --git a/src/pocketmine/entity/Animal.php b/src/pocketmine/entity/Animal.php index 5474c39ca7..bc8fdbe99d 100644 --- a/src/pocketmine/entity/Animal.php +++ b/src/pocketmine/entity/Animal.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\entity; - abstract class Animal extends Creature implements Ageable{ public function isBaby() : bool{ diff --git a/src/pocketmine/entity/Attribute.php b/src/pocketmine/entity/Attribute.php index a34fbbc930..0c004353fd 100644 --- a/src/pocketmine/entity/Attribute.php +++ b/src/pocketmine/entity/Attribute.php @@ -46,14 +46,22 @@ class Attribute{ public const HORSE_JUMP_STRENGTH = 14; public const ZOMBIE_SPAWN_REINFORCEMENTS = 15; + /** @var int */ private $id; + /** @var float */ protected $minValue; + /** @var float */ protected $maxValue; + /** @var float */ protected $defaultValue; + /** @var float */ protected $currentValue; + /** @var string */ protected $name; + /** @var bool */ protected $shouldSend; + /** @var bool */ protected $desynchronized = true; /** @var Attribute[] */ @@ -79,15 +87,6 @@ class Attribute{ } /** - * @param int $id - * @param string $name - * @param float $minValue - * @param float $maxValue - * @param float $defaultValue - * @param bool $shouldSend - * - * @return Attribute - * * @throws \InvalidArgumentException */ public static function addAttribute(int $id, string $name, float $minValue, float $maxValue, float $defaultValue, bool $shouldSend = true) : Attribute{ @@ -98,20 +97,10 @@ class Attribute{ return self::$attributes[$id] = new Attribute($id, $name, $minValue, $maxValue, $defaultValue, $shouldSend); } - /** - * @param int $id - * - * @return Attribute|null - */ public static function getAttribute(int $id) : ?Attribute{ return isset(self::$attributes[$id]) ? clone self::$attributes[$id] : null; } - /** - * @param string $name - * - * @return Attribute|null - */ public static function getAttributeByName(string $name) : ?Attribute{ foreach(self::$attributes as $a){ if($a->getName() === $name){ @@ -137,6 +126,9 @@ class Attribute{ return $this->minValue; } + /** + * @return $this + */ public function setMinValue(float $minValue){ if($minValue > ($max = $this->getMaxValue())){ throw new \InvalidArgumentException("Minimum $minValue is greater than the maximum $max"); @@ -153,6 +145,9 @@ class Attribute{ return $this->maxValue; } + /** + * @return $this + */ public function setMaxValue(float $maxValue){ if($maxValue < ($min = $this->getMinValue())){ throw new \InvalidArgumentException("Maximum $maxValue is less than the minimum $min"); @@ -169,6 +164,9 @@ class Attribute{ return $this->defaultValue; } + /** + * @return $this + */ public function setDefaultValue(float $defaultValue){ if($defaultValue > $this->getMaxValue() or $defaultValue < $this->getMinValue()){ throw new \InvalidArgumentException("Default $defaultValue is outside the range " . $this->getMinValue() . " - " . $this->getMaxValue()); @@ -190,10 +188,6 @@ class Attribute{ } /** - * @param float $value - * @param bool $fit - * @param bool $forceSend - * * @return $this */ public function setValue(float $value, bool $fit = false, bool $forceSend = false){ diff --git a/src/pocketmine/entity/AttributeMap.php b/src/pocketmine/entity/AttributeMap.php index 82c46d0710..930e90c145 100644 --- a/src/pocketmine/entity/AttributeMap.php +++ b/src/pocketmine/entity/AttributeMap.php @@ -25,6 +25,9 @@ namespace pocketmine\entity; use function array_filter; +/** + * @phpstan-implements \ArrayAccess + */ class AttributeMap implements \ArrayAccess{ /** @var Attribute[] */ private $attributes = []; @@ -33,11 +36,6 @@ class AttributeMap implements \ArrayAccess{ $this->attributes[$attribute->getId()] = $attribute; } - /** - * @param int $id - * - * @return Attribute|null - */ public function getAttribute(int $id) : ?Attribute{ return $this->attributes[$id] ?? null; } @@ -53,19 +51,20 @@ class AttributeMap implements \ArrayAccess{ * @return Attribute[] */ public function needSend() : array{ - return array_filter($this->attributes, function(Attribute $attribute){ + return array_filter($this->attributes, function(Attribute $attribute) : bool{ return $attribute->isSyncable() and $attribute->isDesynchronized(); }); } + /** + * @param int $offset + */ public function offsetExists($offset) : bool{ return isset($this->attributes[$offset]); } /** * @param int $offset - * - * @return float */ public function offsetGet($offset) : float{ return $this->attributes[$offset]->getValue(); @@ -79,6 +78,9 @@ class AttributeMap implements \ArrayAccess{ $this->attributes[$offset]->setValue($value); } + /** + * @param int $offset + */ public function offsetUnset($offset) : void{ throw new \RuntimeException("Could not unset an attribute from an attribute map"); } diff --git a/src/pocketmine/entity/Creature.php b/src/pocketmine/entity/Creature.php index fbbd7dbf4c..5e9b4aa7a0 100644 --- a/src/pocketmine/entity/Creature.php +++ b/src/pocketmine/entity/Creature.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\entity; - abstract class Creature extends Living{ } diff --git a/src/pocketmine/entity/Damageable.php b/src/pocketmine/entity/Damageable.php index 613010b774..fbc33ff152 100644 --- a/src/pocketmine/entity/Damageable.php +++ b/src/pocketmine/entity/Damageable.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\entity; - interface Damageable{ } diff --git a/src/pocketmine/entity/DataPropertyManager.php b/src/pocketmine/entity/DataPropertyManager.php index 890ff3e2fb..d3f3afcb1b 100644 --- a/src/pocketmine/entity/DataPropertyManager.php +++ b/src/pocketmine/entity/DataPropertyManager.php @@ -32,110 +32,68 @@ use function is_string; class DataPropertyManager{ + /** + * @var mixed[][] + * @phpstan-var array + */ private $properties = []; + /** + * @var mixed[][] + * @phpstan-var array + */ private $dirtyProperties = []; public function __construct(){ } - /** - * @param int $key - * - * @return int|null - */ public function getByte(int $key) : ?int{ $value = $this->getPropertyValue($key, Entity::DATA_TYPE_BYTE); assert(is_int($value) or $value === null); return $value; } - /** - * @param int $key - * @param int $value - * @param bool $force - */ public function setByte(int $key, int $value, bool $force = false) : void{ $this->setPropertyValue($key, Entity::DATA_TYPE_BYTE, $value, $force); } - /** - * @param int $key - * - * @return int|null - */ public function getShort(int $key) : ?int{ $value = $this->getPropertyValue($key, Entity::DATA_TYPE_SHORT); assert(is_int($value) or $value === null); return $value; } - /** - * @param int $key - * @param int $value - * @param bool $force - */ public function setShort(int $key, int $value, bool $force = false) : void{ $this->setPropertyValue($key, Entity::DATA_TYPE_SHORT, $value, $force); } - /** - * @param int $key - * - * @return int|null - */ public function getInt(int $key) : ?int{ $value = $this->getPropertyValue($key, Entity::DATA_TYPE_INT); assert(is_int($value) or $value === null); return $value; } - /** - * @param int $key - * @param int $value - * @param bool $force - */ public function setInt(int $key, int $value, bool $force = false) : void{ $this->setPropertyValue($key, Entity::DATA_TYPE_INT, $value, $force); } - /** - * @param int $key - * - * @return float|null - */ public function getFloat(int $key) : ?float{ $value = $this->getPropertyValue($key, Entity::DATA_TYPE_FLOAT); assert(is_float($value) or $value === null); return $value; } - /** - * @param int $key - * @param float $value - * @param bool $force - */ public function setFloat(int $key, float $value, bool $force = false) : void{ $this->setPropertyValue($key, Entity::DATA_TYPE_FLOAT, $value, $force); } - /** - * @param int $key - * - * @return null|string - */ public function getString(int $key) : ?string{ $value = $this->getPropertyValue($key, Entity::DATA_TYPE_STRING); assert(is_string($value) or $value === null); return $value; } - /** - * @param int $key - * @param string $value - * @param bool $force - */ public function setString(int $key, string $value, bool $force = false) : void{ $this->setPropertyValue($key, Entity::DATA_TYPE_STRING, $value, $force); } @@ -150,87 +108,44 @@ class DataPropertyManager{ $this->setPropertyValue($key, Entity::DATA_TYPE_COMPOUND_TAG, $value, $force); } - /** - * @param int $key - * - * @return null|Vector3 - */ public function getBlockPos(int $key) : ?Vector3{ $value = $this->getPropertyValue($key, Entity::DATA_TYPE_POS); assert($value instanceof Vector3 or $value === null); return $value; } - /** - * @param int $key - * @param null|Vector3 $value - * @param bool $force - */ public function setBlockPos(int $key, ?Vector3 $value, bool $force = false) : void{ - $this->setPropertyValue($key, Entity::DATA_TYPE_POS, $value ? $value->floor() : null, $force); + $this->setPropertyValue($key, Entity::DATA_TYPE_POS, $value !== null ? $value->floor() : null, $force); } - /** - * @param int $key - * - * @return int|null - */ public function getLong(int $key) : ?int{ $value = $this->getPropertyValue($key, Entity::DATA_TYPE_LONG); assert(is_int($value) or $value === null); return $value; } - /** - * @param int $key - * @param int $value - * @param bool $force - */ public function setLong(int $key, int $value, bool $force = false) : void{ $this->setPropertyValue($key, Entity::DATA_TYPE_LONG, $value, $force); } - /** - * @param int $key - * - * @return null|Vector3 - */ public function getVector3(int $key) : ?Vector3{ $value = $this->getPropertyValue($key, Entity::DATA_TYPE_VECTOR3F); assert($value instanceof Vector3 or $value === null); return $value; } - /** - * @param int $key - * @param null|Vector3 $value - * @param bool $force - */ public function setVector3(int $key, ?Vector3 $value, bool $force = false) : void{ - $this->setPropertyValue($key, Entity::DATA_TYPE_VECTOR3F, $value ? $value->asVector3() : null, $force); + $this->setPropertyValue($key, Entity::DATA_TYPE_VECTOR3F, $value !== null ? $value->asVector3() : null, $force); } - /** - * @param int $key - */ public function removeProperty(int $key) : void{ unset($this->properties[$key]); } - /** - * @param int $key - * - * @return bool - */ public function hasProperty(int $key) : bool{ return isset($this->properties[$key]); } - /** - * @param int $key - * - * @return int - */ public function getPropertyType(int $key) : int{ if(isset($this->properties[$key])){ return $this->properties[$key][0]; @@ -246,9 +161,6 @@ class DataPropertyManager{ } /** - * @param int $key - * @param int $type - * * @return mixed */ public function getPropertyValue(int $key, int $type){ @@ -259,10 +171,7 @@ class DataPropertyManager{ } /** - * @param int $key - * @param int $type * @param mixed $value - * @param bool $force */ public function setPropertyValue(int $key, int $type, $value, bool $force = false) : void{ if(!$force){ @@ -274,7 +183,8 @@ class DataPropertyManager{ /** * Returns all properties. * - * @return array + * @return mixed[][] + * @phpstan-return array */ public function getAll() : array{ return $this->properties; @@ -283,7 +193,8 @@ class DataPropertyManager{ /** * Returns properties that have changed and need to be broadcasted. * - * @return array + * @return mixed[][] + * @phpstan-return array */ public function getDirty() : array{ return $this->dirtyProperties; diff --git a/src/pocketmine/entity/Effect.php b/src/pocketmine/entity/Effect.php index 96299d3ca2..c50e600490 100644 --- a/src/pocketmine/entity/Effect.php +++ b/src/pocketmine/entity/Effect.php @@ -93,27 +93,14 @@ class Effect{ self::registerEffect(new Effect(Effect::CONDUIT_POWER, "%potion.conduitPower", new Color(0x1d, 0xc2, 0xd1))); } - /** - * @param Effect $effect - */ public static function registerEffect(Effect $effect) : void{ self::$effects[$effect->getId()] = $effect; } - /** - * @param int $id - * - * @return Effect|null - */ public static function getEffect(int $id) : ?Effect{ return self::$effects[$id] ?? null; } - /** - * @param string $name - * - * @return Effect|null - */ public static function getEffectByName(string $name) : ?Effect{ $const = self::class . "::" . strtoupper($name); if(defined($const)){ @@ -154,7 +141,6 @@ class Effect{ /** * Returns the effect ID as per Minecraft PE - * @return int */ public function getId() : int{ return $this->id; @@ -162,7 +148,6 @@ class Effect{ /** * Returns the translation key used to translate this effect's name. - * @return string */ public function getName() : string{ return $this->name; @@ -170,7 +155,6 @@ class Effect{ /** * Returns a Color object representing this effect's particle colour. - * @return Color */ public function getColor() : Color{ return clone $this->color; @@ -179,8 +163,6 @@ class Effect{ /** * Returns whether this effect is harmful. * TODO: implement inverse effect results for undead mobs - * - * @return bool */ public function isBad() : bool{ return $this->bad; @@ -188,15 +170,13 @@ class Effect{ /** * Returns whether the effect is by default an instant effect. - * @return bool */ public function isInstantEffect() : bool{ return $this->defaultDuration <= 1; } /** - * Returns the default duration this effect will apply for if a duration is not specified. - * @return int + * Returns the default duration (in ticks) this effect will apply for if a duration is not specified. */ public function getDefaultDuration() : int{ return $this->defaultDuration; @@ -204,7 +184,6 @@ class Effect{ /** * Returns whether this effect will give the subject potion bubbles. - * @return bool */ public function hasBubbles() : bool{ return $this->hasBubbles; @@ -212,10 +191,6 @@ class Effect{ /** * Returns whether the effect will do something on the current tick. - * - * @param EffectInstance $instance - * - * @return bool */ public function canTick(EffectInstance $instance) : bool{ switch($this->id){ @@ -248,12 +223,6 @@ class Effect{ /** * Applies effect results to an entity. This will not be called unless canTick() returns true. - * - * @param Living $entity - * @param EffectInstance $instance - * @param float $potency - * @param null|Entity $source - * @param null|Entity $sourceOwner */ public function applyEffect(Living $entity, EffectInstance $instance, float $potency = 1.0, ?Entity $source = null, ?Entity $sourceOwner = null) : void{ switch($this->id){ @@ -314,9 +283,6 @@ class Effect{ /** * Applies effects to the entity when the effect is first added. - * - * @param Living $entity - * @param EffectInstance $instance */ public function add(Living $entity, EffectInstance $instance) : void{ switch($this->id){ @@ -347,9 +313,6 @@ class Effect{ /** * Removes the effect from the entity, resetting any changed values back to their original defaults. - * - * @param Living $entity - * @param EffectInstance $instance */ public function remove(Living $entity, EffectInstance $instance) : void{ switch($this->id){ diff --git a/src/pocketmine/entity/EffectInstance.php b/src/pocketmine/entity/EffectInstance.php index c66341926a..9423d53c77 100644 --- a/src/pocketmine/entity/EffectInstance.php +++ b/src/pocketmine/entity/EffectInstance.php @@ -47,12 +47,7 @@ class EffectInstance{ private $color; /** - * @param Effect $effectType * @param int|null $duration Passing null will use the effect type's default duration - * @param int $amplifier - * @param bool $visible - * @param bool $ambient - * @param null|Color $overrideColor */ public function __construct(Effect $effectType, ?int $duration = null, int $amplifier = 0, bool $visible = true, bool $ambient = false, ?Color $overrideColor = null){ $this->effectType = $effectType; @@ -67,22 +62,19 @@ class EffectInstance{ return $this->effectType->getId(); } - /** - * @return Effect - */ public function getType() : Effect{ return $this->effectType; } /** - * @return int + * Returns the number of ticks remaining until the effect expires. */ public function getDuration() : int{ return $this->duration; } /** - * @param int $duration + * Sets the number of ticks remaining until the effect expires. * * @throws \InvalidArgumentException * @@ -100,8 +92,6 @@ class EffectInstance{ /** * Decreases the duration by the given number of ticks, without dropping below zero. * - * @param int $ticks - * * @return $this */ public function decreaseDuration(int $ticks) : EffectInstance{ @@ -112,32 +102,23 @@ class EffectInstance{ /** * Returns whether the duration has run out. - * - * @return bool */ public function hasExpired() : bool{ return $this->duration <= 0; } - /** - * @return int - */ public function getAmplifier() : int{ return $this->amplifier; } /** * Returns the level of this effect, which is always one higher than the amplifier. - * - * @return int */ public function getEffectLevel() : int{ return $this->amplifier + 1; } /** - * @param int $amplifier - * * @return $this */ public function setAmplifier(int $amplifier) : EffectInstance{ @@ -148,16 +129,12 @@ class EffectInstance{ /** * Returns whether this effect will produce some visible effect, such as bubbles or particles. - * - * @return bool */ public function isVisible() : bool{ return $this->visible; } /** - * @param bool $visible - * * @return $this */ public function setVisible(bool $visible = true) : EffectInstance{ @@ -170,16 +147,12 @@ class EffectInstance{ * Returns whether the effect originated from the ambient environment. * Ambient effects can originate from things such as a Beacon's area of effect radius. * If this flag is set, the amount of visible particles will be reduced by a factor of 5. - * - * @return bool */ public function isAmbient() : bool{ return $this->ambient; } /** - * @param bool $ambient - * * @return $this */ public function setAmbient(bool $ambient = true) : EffectInstance{ @@ -191,8 +164,6 @@ class EffectInstance{ /** * Returns the particle colour of this effect instance. This can be overridden on a per-EffectInstance basis, so it * is not reflective of the default colour of the effect. - * - * @return Color */ public function getColor() : Color{ return clone $this->color; @@ -200,10 +171,6 @@ class EffectInstance{ /** * Sets the colour of this EffectInstance. - * - * @param Color $color - * - * @return EffectInstance */ public function setColor(Color $color) : EffectInstance{ $this->color = clone $color; @@ -213,8 +180,6 @@ class EffectInstance{ /** * Resets the colour of this EffectInstance to the default specified by its type. - * - * @return EffectInstance */ public function resetColor() : EffectInstance{ $this->color = $this->effectType->getColor(); diff --git a/src/pocketmine/entity/Entity.php b/src/pocketmine/entity/Entity.php index 22d1e79fcf..cfb8be6b72 100644 --- a/src/pocketmine/entity/Entity.php +++ b/src/pocketmine/entity/Entity.php @@ -317,10 +317,17 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ public const DATA_PLAYER_FLAG_SLEEP = 1; public const DATA_PLAYER_FLAG_DEAD = 2; //TODO: CHECK + /** @var int */ public static $entityCount = 1; - /** @var string[] */ + /** + * @var string[] + * @phpstan-var array> + */ private static $knownEntities = []; - /** @var string[][] */ + /** + * @var string[][] + * @phpstan-var array, list> + */ private static $saveNames = []; /** @@ -352,17 +359,12 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ PaintingMotive::init(); } - /** * Creates an entity with the specified type, level and NBT, with optional additional arguments to pass to the * entity's constructor * * @param int|string $type - * @param Level $level - * @param CompoundTag $nbt * @param mixed ...$args - * - * @return Entity|null */ public static function createEntity($type, Level $level, CompoundTag $nbt, ...$args) : ?Entity{ if(isset(self::$knownEntities[$type])){ @@ -380,15 +382,12 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ * @param string $className Class that extends Entity * @param bool $force Force registration even if the entity does not have a valid network ID * @param string[] $saveNames An array of save names which this entity might be saved under. Defaults to the short name of the class itself if empty. + * @phpstan-param class-string $className * * NOTE: The first save name in the $saveNames array will be used when saving the entity to disk. The reflection * name of the class will be appended to the end and only used if no other save names are specified. - * - * @return bool */ public static function registerEntity(string $className, bool $force = false, array $saveNames = []) : bool{ - /** @var Entity $className */ - $class = new \ReflectionClass($className); if(is_a($className, Entity::class, true) and !$class->isAbstract()){ if($className::NETWORK_ID !== -1){ @@ -416,13 +415,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Helper function which creates minimal NBT needed to spawn an entity. - * - * @param Vector3 $pos - * @param Vector3|null $motion - * @param float $yaw - * @param float $pitch - * - * @return CompoundTag */ public static function createBaseNBT(Vector3 $pos, ?Vector3 $motion = null, float $yaw = 0.0, float $pitch = 0.0) : CompoundTag{ return new CompoundTag("", [ @@ -432,9 +424,9 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ new DoubleTag("", $pos->z) ]), new ListTag("Motion", [ - new DoubleTag("", $motion ? $motion->x : 0.0), - new DoubleTag("", $motion ? $motion->y : 0.0), - new DoubleTag("", $motion ? $motion->z : 0.0) + new DoubleTag("", $motion !== null ? $motion->x : 0.0), + new DoubleTag("", $motion !== null ? $motion->y : 0.0), + new DoubleTag("", $motion !== null ? $motion->z : 0.0) ]), new ListTag("Rotation", [ new FloatTag("", $yaw), @@ -443,9 +435,7 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ ]); } - /** - * @var Player[] - */ + /** @var Player[] */ protected $hasSpawned = []; /** @var int */ @@ -480,7 +470,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** @var Vector3 */ public $temporalVector; - /** @var float */ public $lastYaw; /** @var float */ @@ -504,6 +493,7 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** @var float */ private $health = 20.0; + /** @var int */ private $maxHealth = 20; /** @var float */ @@ -650,73 +640,42 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ } - /** - * @return string - */ public function getNameTag() : string{ return $this->propertyManager->getString(self::DATA_NAMETAG); } - /** - * @return bool - */ public function isNameTagVisible() : bool{ return $this->getGenericFlag(self::DATA_FLAG_CAN_SHOW_NAMETAG); } - /** - * @return bool - */ public function isNameTagAlwaysVisible() : bool{ return $this->propertyManager->getByte(self::DATA_ALWAYS_SHOW_NAMETAG) === 1; } - - /** - * @param string $name - */ public function setNameTag(string $name) : void{ $this->propertyManager->setString(self::DATA_NAMETAG, $name); } - /** - * @param bool $value - */ public function setNameTagVisible(bool $value = true) : void{ $this->setGenericFlag(self::DATA_FLAG_CAN_SHOW_NAMETAG, $value); } - /** - * @param bool $value - */ public function setNameTagAlwaysVisible(bool $value = true) : void{ $this->propertyManager->setByte(self::DATA_ALWAYS_SHOW_NAMETAG, $value ? 1 : 0); } - /** - * @return string|null - */ public function getScoreTag() : ?string{ return $this->propertyManager->getString(self::DATA_SCORE_TAG); } - /** - * @param string $score - */ public function setScoreTag(string $score) : void{ $this->propertyManager->setString(self::DATA_SCORE_TAG, $score); } - /** - * @return float - */ public function getScale() : float{ return $this->propertyManager->getFloat(self::DATA_SCALE); } - /** - * @param float $value - */ public function setScale(float $value) : void{ if($value <= 0){ throw new \InvalidArgumentException("Scale must be greater than 0"); @@ -787,7 +746,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Returns whether the entity is able to climb blocks such as ladders or vines. - * @return bool */ public function canClimb() : bool{ return $this->getGenericFlag(self::DATA_FLAG_CAN_CLIMB); @@ -795,8 +753,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Sets whether the entity is able to climb climbable blocks. - * - * @param bool $value */ public function setCanClimb(bool $value = true) : void{ $this->setGenericFlag(self::DATA_FLAG_CAN_CLIMB, $value); @@ -804,8 +760,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Returns whether this entity is climbing a block. By default this is only true if the entity is climbing a ladder or vine or similar block. - * - * @return bool */ public function canClimbWalls() : bool{ return $this->getGenericFlag(self::DATA_FLAG_WALLCLIMBING); @@ -813,8 +767,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Sets whether the entity is climbing a block. If true, the entity can climb anything. - * - * @param bool $value */ public function setCanClimbWalls(bool $value = true) : void{ $this->setGenericFlag(self::DATA_FLAG_WALLCLIMBING, $value); @@ -822,7 +774,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Returns the entity ID of the owning entity, or null if the entity doesn't have an owner. - * @return int|null */ public function getOwningEntityId() : ?int{ return $this->propertyManager->getLong(self::DATA_OWNER_EID); @@ -830,7 +781,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Returns the owning entity, or null if the entity was not found. - * @return Entity|null */ public function getOwningEntity() : ?Entity{ $eid = $this->getOwningEntityId(); @@ -844,8 +794,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Sets the owner of the entity. Passing null will remove the current owner. * - * @param Entity|null $owner - * * @throws \InvalidArgumentException if the supplied entity is not valid */ public function setOwningEntity(?Entity $owner) : void{ @@ -860,7 +808,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Returns the entity ID of the entity's target, or null if it doesn't have a target. - * @return int|null */ public function getTargetEntityId() : ?int{ return $this->propertyManager->getLong(self::DATA_TARGET_EID); @@ -869,8 +816,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Returns the entity's target entity, or null if not found. * This is used for things like hostile mobs attacking entities, and for fishing rods reeling hit entities in. - * - * @return Entity|null */ public function getTargetEntity() : ?Entity{ $eid = $this->getTargetEntityId(); @@ -884,8 +829,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Sets the entity's target entity. Passing null will remove the current target. * - * @param Entity|null $target - * * @throws \InvalidArgumentException if the target entity is not valid */ public function setTargetEntity(?Entity $target) : void{ @@ -900,7 +843,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Returns whether this entity will be saved when its chunk is unloaded. - * @return bool */ public function canSaveWithChunk() : bool{ return $this->savedWithChunk; @@ -909,8 +851,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Sets whether this entity will be saved when its chunk is unloaded. This can be used to prevent the entity being * saved to disk. - * - * @param bool $value */ public function setCanSaveWithChunk(bool $value) : void{ $this->savedWithChunk = $value; @@ -918,8 +858,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Returns the short save name - * - * @return string */ public function getSaveId() : string{ if(!isset(self::$saveNames[static::class])){ @@ -966,8 +904,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ } protected function initEntity() : void{ - assert($this->namedtag instanceof CompoundTag); - if($this->namedtag->hasTag("CustomName", StringTag::class)){ $this->setNameTag($this->namedtag->getString("CustomName")); @@ -985,9 +921,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ } - /** - * @param EntityDamageEvent $source - */ public function attack(EntityDamageEvent $source) : void{ $source->call(); if($source->isCancelled()){ @@ -999,9 +932,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ $this->setHealth($this->getHealth() - $source->getFinalDamage()); } - /** - * @param EntityRegainHealthEvent $source - */ public function heal(EntityRegainHealthEvent $source) : void{ $source->call(); if($source->isCancelled()){ @@ -1018,10 +948,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Called to tick entities while dead. Returns whether the entity should be flagged for despawn yet. - * - * @param int $tickDiff - * - * @return bool */ protected function onDeathUpdate(int $tickDiff) : bool{ return true; @@ -1031,17 +957,12 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ return $this->health > 0; } - /** - * @return float - */ public function getHealth() : float{ return $this->health; } /** * Sets the health of the Entity. This won't send any update to the players - * - * @param float $amount */ public function setHealth(float $amount) : void{ if($amount == $this->health){ @@ -1060,30 +981,18 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ } } - /** - * @return int - */ public function getMaxHealth() : int{ return $this->maxHealth; } - /** - * @param int $amount - */ public function setMaxHealth(int $amount) : void{ $this->maxHealth = $amount; } - /** - * @param EntityDamageEvent $type - */ public function setLastDamageCause(EntityDamageEvent $type) : void{ $this->lastDamageCause = $type; } - /** - * @return EntityDamageEvent|null - */ public function getLastDamageCause() : ?EntityDamageEvent{ return $this->lastDamageCause; } @@ -1102,7 +1011,7 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ $this->justCreated = false; $changedProperties = $this->propertyManager->getDirty(); - if(!empty($changedProperties)){ + if(count($changedProperties) > 0){ $this->sendData($this->hasSpawned, $changedProperties); $this->propertyManager->clearDirtyProperties(); } @@ -1146,15 +1055,11 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ $this->setGenericFlag(self::DATA_FLAG_ONFIRE, $this->isOnFire()); } - /** - * @return int - */ public function getFireTicks() : int{ return $this->fireTicks; } /** - * @param int $fireTicks * @throws \InvalidArgumentException */ public function setFireTicks(int $fireTicks) : void{ @@ -1210,15 +1115,19 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ } protected function updateMovement(bool $teleport = false) : void{ - //TODO: hack for client-side AI interference: prevent client sided movement when motion is 0 - $this->setImmobile($this->motion->x == 0 and $this->motion->y == 0 and $this->motion->z == 0); - $diffPosition = ($this->x - $this->lastX) ** 2 + ($this->y - $this->lastY) ** 2 + ($this->z - $this->lastZ) ** 2; $diffRotation = ($this->yaw - $this->lastYaw) ** 2 + ($this->pitch - $this->lastPitch) ** 2; $diffMotion = $this->motion->subtract($this->lastMotion)->lengthSquared(); - if($teleport or $diffPosition > 0.0001 or $diffRotation > 1.0){ + $still = $this->motion->lengthSquared() == 0.0; + $wasStill = $this->lastMotion->lengthSquared() == 0.0; + if($wasStill !== $still){ + //TODO: hack for client-side AI interference: prevent client sided movement when motion is 0 + $this->setImmobile($still); + } + + if($teleport or $diffPosition > 0.0001 or $diffRotation > 1.0 or (!$wasStill and $still)){ $this->lastX = $this->x; $this->lastY = $this->y; $this->lastZ = $this->z; @@ -1229,7 +1138,7 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ $this->broadcastMovement($teleport); } - if($diffMotion > 0.0025 or ($diffMotion > 0.0001 and $this->motion->lengthSquared() <= 0.0001)){ //0.05 ** 2 + if($diffMotion > 0.0025 or $wasStill !== $still){ //0.05 ** 2 $this->lastMotion = clone $this->motion; $this->broadcastMotion(); @@ -1391,9 +1300,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ return false; } - /** - * @return int|null - */ public function getDirection() : ?int{ $rotation = ($this->yaw - 90) % 360; if($rotation < 0){ @@ -1412,9 +1318,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ } } - /** - * @return Vector3 - */ public function getDirectionVector() : Vector3{ $y = -sin(deg2rad($this->pitch)); $xz = cos(deg2rad($this->pitch)); @@ -1452,7 +1355,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ return true; } - $this->timings->startTiming(); if($this->hasMovementUpdate()){ @@ -1481,7 +1383,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ $hasUpdate = $this->entityBaseTick($tickDiff); Timings::$timerEntityBaseTick->stopTiming(); - $this->timings->stopTiming(); //if($this->isStatic()) @@ -1504,8 +1405,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Flags the entity as needing a movement update on the next tick. Setting this forces a movement update even if the * entity's motion is zero. Used to trigger movement updates when blocks change near entities. - * - * @param bool $value */ final public function setForceMovementUpdate(bool $value = true) : void{ $this->forceMovementUpdate = $value; @@ -1515,7 +1414,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Returns whether the entity needs a movement update on the next tick. - * @return bool */ public function hasMovementUpdate() : bool{ return ( @@ -1535,10 +1433,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ $this->fallDistance = 0.0; } - /** - * @param float $distanceThisTick - * @param bool $onGround - */ protected function updateFallState(float $distanceThisTick, bool $onGround) : void{ if($onGround){ if($this->fallDistance > 0){ @@ -1552,8 +1446,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Called when a falling entity hits the ground. - * - * @param float $fallDistance */ public function fall(float $fallDistance) : void{ @@ -1619,7 +1511,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ $this->isCollided = $this->onGround; $this->updateFallState($dy, $this->onGround); - Timings::$entityMoveTimer->stopTiming(); return true; @@ -1704,7 +1595,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ $this->boundingBox->offset(0, 0, $dz); - if($this->stepHeight > 0 and $fallingFlag and $this->ySize < 0.05 and ($movX != $dx or $movZ != $dz)){ $cx = $dx; $cy = $dy; @@ -1817,8 +1707,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Returns whether this entity can be moved by currents in liquids. - * - * @return bool */ public function canBeMovedByCurrents() : bool{ return true; @@ -1954,10 +1842,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * @param Vector3|Position|Location $pos - * @param float|null $yaw - * @param float|null $pitch - * - * @return bool */ public function teleport(Vector3 $pos, ?float $yaw = null, ?float $pitch = null) : bool{ if($pos instanceof Location){ @@ -2026,8 +1910,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Called by spawnTo() to send whatever packets needed to spawn the entity to the client. - * - * @param Player $player */ protected function sendSpawnPacket(Player $player) : void{ $pk = new AddActorPacket(); @@ -2044,9 +1926,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ $player->dataPacket($pk); } - /** - * @param Player $player - */ public function spawnTo(Player $player) : void{ if(!isset($this->hasSpawned[$player->getLoaderId()]) and $this->chunk !== null and isset($player->usedChunks[Level::chunkHash($this->chunk->getX(), $this->chunk->getZ())])){ $this->hasSpawned[$player->getLoaderId()] = $player; @@ -2076,9 +1955,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * @deprecated WARNING: This function DOES NOT permanently hide the entity from the player. As soon as the entity or * player moves, the player will once again be able to see the entity. - * - * @param Player $player - * @param bool $send */ public function despawnFrom(Player $player, bool $send = true) : void{ if(isset($this->hasSpawned[$player->getLoaderId()])){ @@ -2115,7 +1991,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Returns whether the entity has been "closed". - * @return bool */ public function isClosed() : bool{ return $this->closed; @@ -2155,12 +2030,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ } } - /** - * @param int $propertyId - * @param int $flagId - * @param bool $value - * @param int $propertyType - */ public function setDataFlag(int $propertyId, int $flagId, bool $value = true, int $propertyType = self::DATA_TYPE_LONG) : void{ if($this->getDataFlag($propertyId, $flagId) !== $value){ $flags = (int) $this->propertyManager->getPropertyValue($propertyId, $propertyType); @@ -2169,22 +2038,12 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ } } - /** - * @param int $propertyId - * @param int $flagId - * - * @return bool - */ public function getDataFlag(int $propertyId, int $flagId) : bool{ return (((int) $this->propertyManager->getPropertyValue($propertyId, -1)) & (1 << $flagId)) > 0; } /** * Wrapper around {@link Entity#getDataFlag} for generic data flag reading. - * - * @param int $flagId - * - * @return bool */ public function getGenericFlag(int $flagId) : bool{ return $this->getDataFlag($flagId >= 64 ? self::DATA_FLAGS2 : self::DATA_FLAGS, $flagId % 64); @@ -2192,9 +2051,6 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * Wrapper around {@link Entity#setDataFlag} for generic data flag setting. - * - * @param int $flagId - * @param bool $value */ public function setGenericFlag(int $flagId, bool $value = true) : void{ $this->setDataFlag($flagId >= 64 ? self::DATA_FLAGS2 : self::DATA_FLAGS, $flagId % 64, $value, self::DATA_TYPE_LONG); @@ -2202,7 +2058,8 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ /** * @param Player[]|Player $player - * @param array $data Properly formatted entity data, defaults to everything + * @param mixed[][] $data Properly formatted entity data, defaults to everything + * @phpstan-param array $data */ public function sendData($player, ?array $data = null) : void{ if(!is_array($player)){ @@ -2225,6 +2082,9 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ } } + /** + * @param Player[]|null $players + */ public function broadcastEntityEvent(int $eventId, ?int $eventData = null, ?array $players = null) : void{ $pk = new ActorEventPacket(); $pk->entityRuntimeId = $this->id; @@ -2279,6 +2139,7 @@ abstract class Entity extends Location implements Metadatable, EntityIds{ * @param string $name * @param mixed $value * + * @return void * @throws \ErrorException * @throws \InvalidArgumentException */ diff --git a/src/pocketmine/entity/Explosive.php b/src/pocketmine/entity/Explosive.php index 77099ef586..fad701190e 100644 --- a/src/pocketmine/entity/Explosive.php +++ b/src/pocketmine/entity/Explosive.php @@ -23,8 +23,10 @@ declare(strict_types=1); namespace pocketmine\entity; - interface Explosive{ + /** + * @return void + */ public function explode(); } diff --git a/src/pocketmine/entity/Human.php b/src/pocketmine/entity/Human.php index e0f2c9abc7..9049024f6a 100644 --- a/src/pocketmine/entity/Human.php +++ b/src/pocketmine/entity/Human.php @@ -61,6 +61,7 @@ use function array_merge; use function array_rand; use function array_values; use function ceil; +use function count; use function in_array; use function max; use function min; @@ -80,6 +81,7 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ /** @var UUID */ protected $uuid; + /** @var string */ protected $rawUUID; public $width = 0.6; @@ -89,10 +91,14 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ /** @var Skin */ protected $skin; + /** @var int */ protected $foodTickTimer = 0; + /** @var int */ protected $totalXp = 0; + /** @var int */ protected $xpSeed; + /** @var int */ protected $xpCooldown = 0; protected $baseOffset = 1.62; @@ -110,9 +116,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ } /** - * @param CompoundTag $skinTag - * - * @return Skin * @throws \InvalidArgumentException */ protected static function deserializeSkinNBT(CompoundTag $skinTag) : Skin{ @@ -131,32 +134,21 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ * @deprecated * * Checks the length of a supplied skin bitmap and returns whether the length is valid. - * - * @param string $skin - * - * @return bool */ public static function isValidSkin(string $skin) : bool{ return in_array(strlen($skin), Skin::ACCEPTED_SKIN_SIZES, true); } - /** - * @return UUID|null - */ public function getUniqueId() : ?UUID{ return $this->uuid; } - /** - * @return string - */ public function getRawUniqueId() : string{ return $this->rawUUID; } /** * Returns a Skin object containing information about this human's skin. - * @return Skin */ public function getSkin() : Skin{ return $this->skin; @@ -165,8 +157,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ /** * Sets the human's skin. This will not send any update to viewers, you need to do that manually using * {@link sendSkin}. - * - * @param Skin $skin */ public function setSkin(Skin $skin) : void{ $skin->validate(); @@ -204,8 +194,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ * WARNING: This method does not check if full and may throw an exception if out of bounds. * Use {@link Human::addFood()} for this purpose * - * @param float $new - * * @throws \InvalidArgumentException */ public function setFood(float $new) : void{ @@ -235,8 +223,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ /** * Returns whether this Human may consume objects requiring hunger. - * - * @return bool */ public function isHungry() : bool{ return $this->getFood() < $this->getMaxFood(); @@ -250,8 +236,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ * WARNING: This method does not check if saturated and may throw an exception if out of bounds. * Use {@link Human::addSaturation()} for this purpose * - * @param float $saturation - * * @throws \InvalidArgumentException */ public function setSaturation(float $saturation) : void{ @@ -270,8 +254,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ /** * WARNING: This method does not check if exhausted and does not consume saturation/food. * Use {@link Human::exhaust()} for this purpose. - * - * @param float $exhaustion */ public function setExhaustion(float $exhaustion) : void{ $this->attributeMap->getAttribute(Attribute::EXHAUSTION)->setValue($exhaustion); @@ -280,9 +262,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ /** * Increases a human's exhaustion level. * - * @param float $amount - * @param int $cause - * * @return float the amount of exhaustion level increased */ public function exhaust(float $amount, int $cause = PlayerExhaustEvent::CAUSE_CUSTOM) : float{ @@ -330,7 +309,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ /** * Returns the player's experience level. - * @return int */ public function getXpLevel() : int{ return (int) $this->attributeMap->getAttribute(Attribute::EXPERIENCE_LEVEL)->getValue(); @@ -338,10 +316,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ /** * Sets the player's experience level. This does not affect their total XP or their XP progress. - * - * @param int $level - * - * @return bool */ public function setXpLevel(int $level) : bool{ return $this->setXpAndProgress($level, null); @@ -349,11 +323,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ /** * Adds a number of XP levels to the player. - * - * @param int $amount - * @param bool $playSound - * - * @return bool */ public function addXpLevels(int $amount, bool $playSound = true) : bool{ $oldLevel = $this->getXpLevel(); @@ -373,10 +342,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ /** * Subtracts a number of XP levels from the player. - * - * @param int $amount - * - * @return bool */ public function subtractXpLevels(int $amount) : bool{ return $this->addXpLevels(-$amount); @@ -384,7 +349,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ /** * Returns a value between 0.0 and 1.0 to indicate how far through the current level the player is. - * @return float */ public function getXpProgress() : float{ return $this->attributeMap->getAttribute(Attribute::EXPERIENCE)->getValue(); @@ -392,10 +356,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ /** * Sets the player's progress through the current level to a value between 0.0 and 1.0. - * - * @param float $progress - * - * @return bool */ public function setXpProgress(float $progress) : bool{ return $this->setXpAndProgress(null, $progress); @@ -403,7 +363,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ /** * Returns the number of XP points the player has progressed into their current level. - * @return int */ public function getRemainderXp() : int{ return (int) (ExperienceUtils::getXpToCompleteLevel($this->getXpLevel()) * $this->getXpProgress()); @@ -413,8 +372,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ * Returns the amount of XP points the player currently has, calculated from their current level and progress * through their current level. This will be reduced by enchanting deducting levels and is used to calculate the * amount of XP the player drops on death. - * - * @return int */ public function getCurrentTotalXp() : int{ return ExperienceUtils::getXpToReachLevel($this->getXpLevel()) + $this->getRemainderXp(); @@ -423,10 +380,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ /** * Sets the current total of XP the player has, recalculating their XP level and progress. * Note that this DOES NOT update the player's lifetime total XP. - * - * @param int $amount - * - * @return bool */ public function setCurrentTotalXp(int $amount) : bool{ $newLevel = ExperienceUtils::getLevelFromXp($amount); @@ -438,10 +391,7 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ * Adds an amount of XP to the player, recalculating their XP level and progress. XP amount will be added to the * player's lifetime XP. * - * @param int $amount * @param bool $playSound Whether to play level-up and XP gained sounds. - * - * @return bool */ public function addXp(int $amount, bool $playSound = true) : bool{ $this->totalXp += $amount; @@ -472,10 +422,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ /** * Takes an amount of XP from the player, recalculating their XP level and progress. - * - * @param int $amount - * - * @return bool */ public function subtractXp(int $amount) : bool{ return $this->addXp(-$amount); @@ -508,8 +454,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ /** * Returns the total XP the player has collected in their lifetime. Resets when the player dies. * XP levels being removed in enchanting do not reduce this number. - * - * @return int */ public function getLifetimeTotalXp() : int{ return $this->totalXp; @@ -518,8 +462,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ /** * Sets the lifetime total XP of the player. This does not recalculate their level or progress. Used for player * score when they die. (TODO: add this when MCPE supports it) - * - * @param int $amount */ public function setLifetimeTotalXp(int $amount) : void{ if($amount < 0){ @@ -531,7 +473,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ /** * Returns whether the human can pickup XP orbs (checks cooldown time) - * @return bool */ public function canPickupXp() : bool{ return $this->xpCooldown === 0; @@ -548,13 +489,13 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ $equipment[$mainHandIndex] = $item; } //TODO: check offhand - foreach($this->armorInventory->getContents() as $k => $item){ - if($item instanceof Durable and $item->hasEnchantment(Enchantment::MENDING)){ - $equipment[$k] = $item; + foreach($this->armorInventory->getContents() as $k => $armorItem){ + if($armorItem instanceof Durable and $armorItem->hasEnchantment(Enchantment::MENDING)){ + $equipment[$k] = $armorItem; } } - if(!empty($equipment)){ + if(count($equipment) > 0){ $repairItem = $equipment[$k = array_rand($equipment)]; if($repairItem->getDamage() > 0){ $repairAmount = min($repairItem->getDamage(), $xpValue * 2); @@ -575,8 +516,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ /** * Sets the duration in ticks until the human can pick up another XP orb. - * - * @param int $value */ public function resetXpCooldown(int $value = 2) : void{ $this->xpCooldown = $value; @@ -585,7 +524,7 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ public function getXpDropAmount() : int{ //this causes some XP to be lost on death when above level 1 (by design), dropping at most enough points for //about 7.5 levels of XP. - return (int) min(100, 7 * $this->getXpLevel()); + return min(100, 7 * $this->getXpLevel()); } /** @@ -896,10 +835,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ /** * Wrapper around {@link Entity#getDataFlag} for player-specific data flag reading. - * - * @param int $flagId - * - * @return bool */ public function getPlayerFlag(int $flagId) : bool{ return $this->getDataFlag(self::DATA_PLAYER_FLAGS, $flagId); @@ -907,9 +842,6 @@ class Human extends Creature implements ProjectileSource, InventoryHolder{ /** * Wrapper around {@link Entity#setDataFlag} for player-specific data flag setting. - * - * @param int $flagId - * @param bool $value */ public function setPlayerFlag(int $flagId, bool $value = true) : void{ $this->setDataFlag(self::DATA_PLAYER_FLAGS, $flagId, $value, self::DATA_TYPE_BYTE); diff --git a/src/pocketmine/entity/Living.php b/src/pocketmine/entity/Living.php index fcbff7e1fc..5de84968b7 100644 --- a/src/pocketmine/entity/Living.php +++ b/src/pocketmine/entity/Living.php @@ -70,6 +70,7 @@ abstract class Living extends Entity implements Damageable{ protected $gravity = 0.08; protected $drag = 0.02; + /** @var int */ protected $attackTime = 0; /** @var int */ @@ -77,6 +78,7 @@ abstract class Living extends Entity implements Damageable{ /** @var int */ protected $maxDeadTicks = 25; + /** @var float */ protected $jumpVelocity = 0.42; /** @var EffectInstance[] */ @@ -109,7 +111,7 @@ abstract class Living extends Entity implements Damageable{ $this->setHealth($health); - /** @var CompoundTag[]|ListTag $activeEffectsTag */ + /** @var CompoundTag[]|ListTag|null */ $activeEffectsTag = $this->namedtag->getListTag("ActiveEffects"); if($activeEffectsTag !== null){ foreach($activeEffectsTag as $e){ @@ -185,7 +187,6 @@ abstract class Living extends Entity implements Damageable{ } } - public function hasLineOfSight(Entity $entity) : bool{ //TODO: head height return true; @@ -211,8 +212,6 @@ abstract class Living extends Entity implements Damageable{ /** * Removes the effect with the specified ID from the mob. - * - * @param int $effectId */ public function removeEffect(int $effectId) : void{ if(isset($this->effects[$effectId])){ @@ -238,10 +237,6 @@ abstract class Living extends Entity implements Damageable{ /** * Returns the effect instance active on this entity with the specified ID, or null if the mob does not have the * effect. - * - * @param int $effectId - * - * @return EffectInstance|null */ public function getEffect(int $effectId) : ?EffectInstance{ return $this->effects[$effectId] ?? null; @@ -249,10 +244,6 @@ abstract class Living extends Entity implements Damageable{ /** * Returns whether the specified effect is active on the mob. - * - * @param int $effectId - * - * @return bool */ public function hasEffect(int $effectId) : bool{ return isset($this->effects[$effectId]); @@ -260,10 +251,9 @@ abstract class Living extends Entity implements Damageable{ /** * Returns whether the mob has any active effects. - * @return bool */ public function hasEffects() : bool{ - return !empty($this->effects); + return count($this->effects) > 0; } /** @@ -271,8 +261,6 @@ abstract class Living extends Entity implements Damageable{ * If a weaker effect of the same type is already applied, it will be replaced. * If a weaker or equal-strength effect is already applied but has a shorter duration, it will be replaced. * - * @param EffectInstance $effect - * * @return bool whether the effect has been successfully applied. */ public function addEffect(EffectInstance $effect) : bool{ @@ -332,7 +320,7 @@ abstract class Living extends Entity implements Damageable{ } } - if(!empty($colors)){ + if(count($colors) > 0){ $this->propertyManager->setInt(Entity::DATA_POTION_COLOR, Color::mix(...$colors)->toARGB()); $this->propertyManager->setByte(Entity::DATA_POTION_AMBIENT, $ambient ? 1 : 0); }else{ @@ -343,8 +331,6 @@ abstract class Living extends Entity implements Damageable{ /** * Sends the mob's potion effects to the specified player. - * - * @param Player $player */ public function sendPotionEffects(Player $player) : void{ foreach($this->effects as $effect){ @@ -371,10 +357,6 @@ abstract class Living extends Entity implements Damageable{ /** * Causes the mob to consume the given Consumable object, applying applicable effects, health bonuses, food bonuses, * etc. - * - * @param Consumable $consumable - * - * @return bool */ public function consumeObject(Consumable $consumable) : bool{ foreach($consumable->getAdditionalEffects() as $effect){ @@ -388,7 +370,6 @@ abstract class Living extends Entity implements Damageable{ /** * Returns the initial upwards velocity of a jumping entity in blocks/tick, including additional velocity due to effects. - * @return float */ public function getJumpVelocity() : float{ return $this->jumpVelocity + ($this->hasEffect(Effect::JUMP) ? ($this->getEffect(Effect::JUMP)->getEffectLevel() / 10) : 0); @@ -415,8 +396,6 @@ abstract class Living extends Entity implements Damageable{ * Returns how many armour points this mob has. Armour points provide a percentage reduction to damage. * For mobs which can wear armour, this should return the sum total of the armour points provided by their * equipment. - * - * @return int */ public function getArmorPoints() : int{ $total = 0; @@ -429,10 +408,6 @@ abstract class Living extends Entity implements Damageable{ /** * Returns the highest level of the specified enchantment on any armour piece that the entity is currently wearing. - * - * @param int $enchantmentId - * - * @return int */ public function getHighestArmorEnchantmentLevel(int $enchantmentId) : int{ $result = 0; @@ -443,9 +418,6 @@ abstract class Living extends Entity implements Damageable{ return $result; } - /** - * @return ArmorInventory - */ public function getArmorInventory() : ArmorInventory{ return $this->armorInventory; } @@ -457,8 +429,6 @@ abstract class Living extends Entity implements Damageable{ /** * Called prior to EntityDamageEvent execution to apply modifications to the event's damage, such as reduction due * to effects or armour. - * - * @param EntityDamageEvent $source */ public function applyDamageModifiers(EntityDamageEvent $source) : void{ if($source->canBeReducedByArmor()){ @@ -486,8 +456,6 @@ abstract class Living extends Entity implements Damageable{ * Called after EntityDamageEvent execution to apply post-hurt effects, such as reducing absorption or modifying * armour durability. * This will not be called by damage sources causing death. - * - * @param EntityDamageEvent $source */ protected function applyPostDamageEffects(EntityDamageEvent $source) : void{ $this->setAbsorption(max(0, $this->getAbsorption() + $source->getModifier(EntityDamageEvent::MODIFIER_ABSORPTION))); @@ -517,8 +485,6 @@ abstract class Living extends Entity implements Damageable{ /** * Damages the worn armour according to the amount of damage given. Each 4 points (rounded down) deals 1 damage * point to each armour piece, but never less than 1 total. - * - * @param float $damage */ public function damageArmor(float $damage) : void{ $durabilityRemoved = (int) max(floor($damage / 4), 1); @@ -712,15 +678,11 @@ abstract class Living extends Entity implements Damageable{ } } - return !empty($this->effects); + return count($this->effects) > 0; } /** * Ticks the entity's air supply, consuming it when underwater and regenerating it when out of water. - * - * @param int $tickDiff - * - * @return bool */ protected function doAirSupplyTick(int $tickDiff) : bool{ $ticks = $this->getAirSupplyTicks(); @@ -756,7 +718,6 @@ abstract class Living extends Entity implements Damageable{ /** * Returns whether the entity can currently breathe. - * @return bool */ public function canBreathe() : bool{ return $this->hasEffect(Effect::WATER_BREATHING) or $this->hasEffect(Effect::CONDUIT_POWER) or !$this->isUnderwater(); @@ -764,7 +725,6 @@ abstract class Living extends Entity implements Damageable{ /** * Returns whether the entity is currently breathing or not. If this is false, the entity's air supply will be used. - * @return bool */ public function isBreathing() : bool{ return $this->getGenericFlag(self::DATA_FLAG_BREATHING); @@ -773,8 +733,6 @@ abstract class Living extends Entity implements Damageable{ /** * Sets whether the entity is currently breathing. If false, it will cause the entity's air supply to be used. * For players, this also shows the oxygen bar. - * - * @param bool $value */ public function setBreathing(bool $value = true) : void{ $this->setGenericFlag(self::DATA_FLAG_BREATHING, $value); @@ -783,8 +741,6 @@ abstract class Living extends Entity implements Damageable{ /** * Returns the number of ticks remaining in the entity's air supply. Note that the entity may survive longer than * this amount of time without damage due to enchantments such as Respiration. - * - * @return int */ public function getAirSupplyTicks() : int{ return $this->propertyManager->getShort(self::DATA_AIR); @@ -792,8 +748,6 @@ abstract class Living extends Entity implements Damageable{ /** * Sets the number of air ticks left in the entity's air supply. - * - * @param int $ticks */ public function setAirSupplyTicks(int $ticks) : void{ $this->propertyManager->setShort(self::DATA_AIR, $ticks); @@ -801,7 +755,6 @@ abstract class Living extends Entity implements Damageable{ /** * Returns the maximum amount of air ticks the entity's air supply can contain. - * @return int */ public function getMaxAirSupplyTicks() : int{ return $this->propertyManager->getShort(self::DATA_MAX_AIR); @@ -809,8 +762,6 @@ abstract class Living extends Entity implements Damageable{ /** * Sets the maximum amount of air ticks the air supply can hold. - * - * @param int $ticks */ public function setMaxAirSupplyTicks(int $ticks) : void{ $this->propertyManager->setShort(self::DATA_MAX_AIR, $ticks); @@ -834,16 +785,14 @@ abstract class Living extends Entity implements Damageable{ /** * Returns the amount of XP this mob will drop on death. - * @return int */ public function getXpDropAmount() : int{ return 0; } /** - * @param int $maxDistance - * @param int $maxLength - * @param array $transparent + * @param true[] $transparent + * @phpstan-param array $transparent * * @return Block[] */ @@ -885,14 +834,12 @@ abstract class Living extends Entity implements Damageable{ } /** - * @param int $maxDistance - * @param array $transparent - * - * @return Block|null + * @param true[] $transparent + * @phpstan-param array $transparent */ public function getTargetBlock(int $maxDistance, array $transparent = []) : ?Block{ $line = $this->getLineOfSight($maxDistance, 1, $transparent); - if(!empty($line)){ + if(count($line) > 0){ return array_shift($line); } @@ -902,8 +849,6 @@ abstract class Living extends Entity implements Damageable{ /** * Changes the entity's yaw and pitch to make it look at the specified Vector3 position. For mobs, this will cause * their heads to turn. - * - * @param Vector3 $target */ public function lookAt(Vector3 $target) : void{ $horizontal = sqrt(($target->x - $this->x) ** 2 + ($target->z - $this->z) ** 2); diff --git a/src/pocketmine/entity/Monster.php b/src/pocketmine/entity/Monster.php index d2b0091b2a..92cf3bd29a 100644 --- a/src/pocketmine/entity/Monster.php +++ b/src/pocketmine/entity/Monster.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\entity; - abstract class Monster extends Creature{ } diff --git a/src/pocketmine/entity/NPC.php b/src/pocketmine/entity/NPC.php index 01f715a0ea..70094a3cec 100644 --- a/src/pocketmine/entity/NPC.php +++ b/src/pocketmine/entity/NPC.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\entity; - interface NPC{ } diff --git a/src/pocketmine/entity/Rideable.php b/src/pocketmine/entity/Rideable.php index 8d72a14cf5..27d62effca 100644 --- a/src/pocketmine/entity/Rideable.php +++ b/src/pocketmine/entity/Rideable.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\entity; - interface Rideable{ } diff --git a/src/pocketmine/entity/Skin.php b/src/pocketmine/entity/Skin.php index d5a1477ea9..f94ce9a88d 100644 --- a/src/pocketmine/entity/Skin.php +++ b/src/pocketmine/entity/Skin.php @@ -57,7 +57,6 @@ class Skin{ /** * @deprecated - * @return bool */ public function isValid() : bool{ try{ @@ -85,37 +84,22 @@ class Skin{ //TODO: validate geometry } - /** - * @return string - */ public function getSkinId() : string{ return $this->skinId; } - /** - * @return string - */ public function getSkinData() : string{ return $this->skinData; } - /** - * @return string - */ public function getCapeData() : string{ return $this->capeData; } - /** - * @return string - */ public function getGeometryName() : string{ return $this->geometryName; } - /** - * @return string - */ public function getGeometryData() : string{ return $this->geometryData; } diff --git a/src/pocketmine/entity/Squid.php b/src/pocketmine/entity/Squid.php index 950164fc0d..0dd2d64e02 100644 --- a/src/pocketmine/entity/Squid.php +++ b/src/pocketmine/entity/Squid.php @@ -42,8 +42,10 @@ class Squid extends WaterAnimal{ /** @var Vector3|null */ public $swimDirection = null; + /** @var float */ public $swimSpeed = 0.1; + /** @var int */ private $switchDirectionTicker = 0; public function initEntity() : void{ @@ -76,7 +78,6 @@ class Squid extends WaterAnimal{ return new Vector3(mt_rand(-1000, 1000) / 1000, mt_rand(-500, 500) / 1000, mt_rand(-1000, 1000) / 1000); } - public function entityBaseTick(int $tickDiff = 1) : bool{ if($this->closed){ return false; diff --git a/src/pocketmine/entity/Vehicle.php b/src/pocketmine/entity/Vehicle.php index 21fdbe44f0..2929c183b6 100644 --- a/src/pocketmine/entity/Vehicle.php +++ b/src/pocketmine/entity/Vehicle.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\entity; - abstract class Vehicle extends Entity implements Rideable{ } diff --git a/src/pocketmine/entity/Villager.php b/src/pocketmine/entity/Villager.php index 233690ca9c..b6dac6306e 100644 --- a/src/pocketmine/entity/Villager.php +++ b/src/pocketmine/entity/Villager.php @@ -59,8 +59,6 @@ class Villager extends Creature implements NPC, Ageable{ /** * Sets the villager profession - * - * @param int $profession */ public function setProfession(int $profession) : void{ $this->propertyManager->setInt(self::DATA_VARIANT, $profession); diff --git a/src/pocketmine/entity/object/ExperienceOrb.php b/src/pocketmine/entity/object/ExperienceOrb.php index 12b60375b9..3a70e17d9b 100644 --- a/src/pocketmine/entity/object/ExperienceOrb.php +++ b/src/pocketmine/entity/object/ExperienceOrb.php @@ -49,10 +49,6 @@ class ExperienceOrb extends Entity{ /** * Returns the largest size of normal XP orb that will be spawned for the specified amount of XP. Used to split XP * up into multiple orbs when an amount of XP is dropped. - * - * @param int $amount - * - * @return int */ public static function getMaxOrbSize(int $amount) : int{ foreach(self::ORB_SPLIT_SIZES as $split){ @@ -67,8 +63,6 @@ class ExperienceOrb extends Entity{ /** * Splits the specified amount of XP into an array of acceptable XP orb sizes. * - * @param int $amount - * * @return int[] */ public static function splitIntoOrbSizes(int $amount) : array{ diff --git a/src/pocketmine/entity/object/ItemEntity.php b/src/pocketmine/entity/object/ItemEntity.php index 71fd1a3c07..5988e61369 100644 --- a/src/pocketmine/entity/object/ItemEntity.php +++ b/src/pocketmine/entity/object/ItemEntity.php @@ -67,7 +67,6 @@ class ItemEntity extends Entity{ $this->owner = $this->namedtag->getString("Owner", $this->owner); $this->thrower = $this->namedtag->getString("Thrower", $this->thrower); - $itemTag = $this->namedtag->getCompoundTag("Item"); if($itemTag === null){ throw new \UnexpectedValueException("Invalid " . get_class($this) . " entity: expected \"Item\" NBT tag not found"); @@ -78,7 +77,6 @@ class ItemEntity extends Entity{ throw new \UnexpectedValueException("Item for " . get_class($this) . " is invalid"); } - (new ItemSpawnEvent($this))->call(); } @@ -134,9 +132,6 @@ class ItemEntity extends Entity{ } } - /** - * @return Item - */ public function getItem() : Item{ return $this->item; } @@ -149,44 +144,26 @@ class ItemEntity extends Entity{ return false; } - /** - * @return int - */ public function getPickupDelay() : int{ return $this->pickupDelay; } - /** - * @param int $delay - */ public function setPickupDelay(int $delay) : void{ $this->pickupDelay = $delay; } - /** - * @return string - */ public function getOwner() : string{ return $this->owner; } - /** - * @param string $owner - */ public function setOwner(string $owner) : void{ $this->owner = $owner; } - /** - * @return string - */ public function getThrower() : string{ return $this->thrower; } - /** - * @param string $thrower - */ public function setThrower(string $thrower) : void{ $this->thrower = $thrower; } diff --git a/src/pocketmine/entity/object/Painting.php b/src/pocketmine/entity/object/Painting.php index f60368519e..f9767b211e 100644 --- a/src/pocketmine/entity/object/Painting.php +++ b/src/pocketmine/entity/object/Painting.php @@ -83,8 +83,8 @@ class Painting extends Entity{ $this->namedtag->setInt("TileY", (int) $this->blockIn->y); $this->namedtag->setInt("TileZ", (int) $this->blockIn->z); - $this->namedtag->setByte("Facing", (int) $this->direction); - $this->namedtag->setByte("Direction", (int) $this->direction); //Save both for full compatibility + $this->namedtag->setByte("Facing", $this->direction); + $this->namedtag->setByte("Direction", $this->direction); //Save both for full compatibility $this->namedtag->setString("Motive", $this->motive); } @@ -168,7 +168,6 @@ class Painting extends Entity{ /** * Returns the painting motive (which image is displayed on the painting) - * @return PaintingMotive */ public function getMotive() : PaintingMotive{ return PaintingMotive::getMotiveByName($this->motive); @@ -180,12 +179,6 @@ class Painting extends Entity{ /** * Returns the bounding-box a painting with the specified motive would have at the given position and direction. - * - * @param Vector3 $blockIn - * @param int $facing - * @param PaintingMotive $motive - * - * @return AxisAlignedBB */ private static function getPaintingBB(Vector3 $blockIn, int $facing, PaintingMotive $motive) : AxisAlignedBB{ $width = $motive->getWidth(); @@ -241,14 +234,6 @@ class Painting extends Entity{ /** * Returns whether a painting with the specified motive can be placed at the given position. - * - * @param Level $level - * @param Vector3 $blockIn - * @param int $facing - * @param bool $checkOverlap - * @param PaintingMotive $motive - * - * @return bool */ public static function canFit(Level $level, Vector3 $blockIn, int $facing, bool $checkOverlap, PaintingMotive $motive) : bool{ $width = $motive->getWidth(); diff --git a/src/pocketmine/entity/object/PaintingMotive.php b/src/pocketmine/entity/object/PaintingMotive.php index c0f0cabc8a..a21bba2fc4 100644 --- a/src/pocketmine/entity/object/PaintingMotive.php +++ b/src/pocketmine/entity/object/PaintingMotive.php @@ -64,18 +64,10 @@ class PaintingMotive{ } } - /** - * @param PaintingMotive $motive - */ public static function registerMotive(PaintingMotive $motive) : void{ self::$motives[$motive->getName()] = $motive; } - /** - * @param string $name - * - * @return PaintingMotive|null - */ public static function getMotiveByName(string $name) : ?PaintingMotive{ return self::$motives[$name] ?? null; } @@ -94,30 +86,20 @@ class PaintingMotive{ /** @var int */ protected $height; - public function __construct(int $width, int $height, string $name){ $this->name = $name; $this->width = $width; $this->height = $height; } - /** - * @return string - */ public function getName() : string{ return $this->name; } - /** - * @return int - */ public function getWidth() : int{ return $this->width; } - /** - * @return int - */ public function getHeight() : int{ return $this->height; } diff --git a/src/pocketmine/entity/object/PrimedTNT.php b/src/pocketmine/entity/object/PrimedTNT.php index ce04b781bd..c00c6f1543 100644 --- a/src/pocketmine/entity/object/PrimedTNT.php +++ b/src/pocketmine/entity/object/PrimedTNT.php @@ -43,11 +43,11 @@ class PrimedTNT extends Entity implements Explosive{ protected $gravity = 0.04; protected $drag = 0.02; + /** @var int */ protected $fuse; public $canCollide = false; - public function attack(EntityDamageEvent $source) : void{ if($source->getCause() === EntityDamageEvent::CAUSE_VOID){ parent::attack($source); @@ -69,7 +69,6 @@ class PrimedTNT extends Entity implements Explosive{ $this->level->broadcastLevelEvent($this, LevelEventPacket::EVENT_SOUND_IGNITE); } - public function canCollideWith(Entity $entity) : bool{ return false; } diff --git a/src/pocketmine/entity/projectile/Arrow.php b/src/pocketmine/entity/projectile/Arrow.php index 4ae8f6a4c5..60de955b65 100644 --- a/src/pocketmine/entity/projectile/Arrow.php +++ b/src/pocketmine/entity/projectile/Arrow.php @@ -102,16 +102,10 @@ class Arrow extends Projectile{ } } - /** - * @return float - */ public function getPunchKnockback() : float{ return $this->punchKnockback; } - /** - * @param float $punchKnockback - */ public function setPunchKnockback(float $punchKnockback) : void{ $this->punchKnockback = $punchKnockback; } @@ -157,16 +151,10 @@ class Arrow extends Projectile{ } } - /** - * @return int - */ public function getPickupMode() : int{ return $this->pickupMode; } - /** - * @param int $pickupMode - */ public function setPickupMode(int $pickupMode) : void{ $this->pickupMode = $pickupMode; } diff --git a/src/pocketmine/entity/projectile/Projectile.php b/src/pocketmine/entity/projectile/Projectile.php index 2544f79ed0..1921ebb550 100644 --- a/src/pocketmine/entity/projectile/Projectile.php +++ b/src/pocketmine/entity/projectile/Projectile.php @@ -120,8 +120,6 @@ abstract class Projectile extends Entity{ /** * Returns the base damage applied on collision. This is multiplied by the projectile's speed to give a result * damage. - * - * @return float */ public function getBaseDamage() : float{ return $this->damage; @@ -129,8 +127,6 @@ abstract class Projectile extends Entity{ /** * Sets the base amount of damage applied by the projectile. - * - * @param float $damage */ public function setBaseDamage(float $damage) : void{ $this->damage = $damage; @@ -138,7 +134,6 @@ abstract class Projectile extends Entity{ /** * Returns the amount of damage this projectile will deal to the entity it hits. - * @return int */ public function getResultDamage() : int{ return (int) ceil($this->motion->length() * $this->damage); @@ -270,7 +265,6 @@ abstract class Projectile extends Entity{ $this->checkChunks(); $this->checkBlockCollision(); - Timings::$entityMoveTimer->stopTiming(); } @@ -279,10 +273,6 @@ abstract class Projectile extends Entity{ * This can be overridden by other projectiles to allow altering the blocks which are collided with (for example * some projectiles collide with any non-air block). * - * @param Block $block - * @param Vector3 $start - * @param Vector3 $end - * * @return RayTraceResult|null the result of the ray trace if successful, or null if no interception is found. */ protected function calculateInterceptWithBlock(Block $block, Vector3 $start, Vector3 $end) : ?RayTraceResult{ @@ -292,8 +282,6 @@ abstract class Projectile extends Entity{ /** * Called when the projectile hits something. Override this to perform non-target-specific effects when the * projectile hits something. - * - * @param ProjectileHitEvent $event */ protected function onHit(ProjectileHitEvent $event) : void{ @@ -301,9 +289,6 @@ abstract class Projectile extends Entity{ /** * Called when the projectile collides with an Entity. - * - * @param Entity $entityHit - * @param RayTraceResult $hitResult */ protected function onHitEntity(Entity $entityHit, RayTraceResult $hitResult) : void{ $damage = $this->getResultDamage(); @@ -331,9 +316,6 @@ abstract class Projectile extends Entity{ /** * Called when the projectile collides with a Block. - * - * @param Block $blockHit - * @param RayTraceResult $hitResult */ protected function onHitBlock(Block $blockHit, RayTraceResult $hitResult) : void{ $this->blockHit = $blockHit->asVector3(); diff --git a/src/pocketmine/entity/projectile/ProjectileSource.php b/src/pocketmine/entity/projectile/ProjectileSource.php index 0bab7da5f2..e74cafad9a 100644 --- a/src/pocketmine/entity/projectile/ProjectileSource.php +++ b/src/pocketmine/entity/projectile/ProjectileSource.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\entity\projectile; - interface ProjectileSource{ } diff --git a/src/pocketmine/entity/projectile/SplashPotion.php b/src/pocketmine/entity/projectile/SplashPotion.php index 5f9ecd9dba..1d841f37ef 100644 --- a/src/pocketmine/entity/projectile/SplashPotion.php +++ b/src/pocketmine/entity/projectile/SplashPotion.php @@ -34,6 +34,7 @@ use pocketmine\item\Potion; use pocketmine\network\mcpe\protocol\LevelEventPacket; use pocketmine\network\mcpe\protocol\LevelSoundEventPacket; use pocketmine\utils\Color; +use function count; use function round; use function sqrt; @@ -63,7 +64,7 @@ class SplashPotion extends Throwable{ $effects = $this->getPotionEffects(); $hasEffects = true; - if(empty($effects)){ + if(count($effects) === 0){ $colors = [ new Color(0x38, 0x5d, 0xc6) //Default colour for splash water bottle and similar with no effects. ]; @@ -130,22 +131,17 @@ class SplashPotion extends Throwable{ /** * Returns the meta value of the potion item that this splash potion corresponds to. This decides what effects will be applied to the entity when it collides with its target. - * @return int */ public function getPotionId() : int{ return $this->propertyManager->getShort(self::DATA_POTION_AUX_VALUE) ?? 0; } - /** - * @param int $id - */ public function setPotionId(int $id) : void{ $this->propertyManager->setShort(self::DATA_POTION_AUX_VALUE, $id); } /** * Returns whether this splash potion will create an area-effect cloud when it lands. - * @return bool */ public function willLinger() : bool{ return $this->getDataFlag(self::DATA_FLAGS, self::DATA_FLAG_LINGER); @@ -153,8 +149,6 @@ class SplashPotion extends Throwable{ /** * Sets whether this splash potion will create an area-effect-cloud when it lands. - * - * @param bool $value */ public function setLinger(bool $value = true) : void{ $this->setDataFlag(self::DATA_FLAGS, self::DATA_FLAG_LINGER, $value); diff --git a/src/pocketmine/entity/utils/ExperienceUtils.php b/src/pocketmine/entity/utils/ExperienceUtils.php index 38c0ab991b..9b387b397f 100644 --- a/src/pocketmine/entity/utils/ExperienceUtils.php +++ b/src/pocketmine/entity/utils/ExperienceUtils.php @@ -30,10 +30,6 @@ abstract class ExperienceUtils{ /** * Calculates and returns the amount of XP needed to get from level 0 to level $level - * - * @param int $level - * - * @return int */ public static function getXpToReachLevel(int $level) : int{ if($level <= 16){ @@ -47,10 +43,6 @@ abstract class ExperienceUtils{ /** * Returns the amount of XP needed to reach $level + 1. - * - * @param int $level - * - * @return int */ public static function getXpToCompleteLevel(int $level) : int{ if($level <= 15){ @@ -65,10 +57,6 @@ abstract class ExperienceUtils{ /** * Calculates and returns the number of XP levels the specified amount of XP points are worth. * This returns a floating-point number, the decimal part being the progress through the resulting level. - * - * @param int $xp - * - * @return float */ public static function getLevelFromXp(int $xp) : float{ if($xp <= self::getXpToReachLevel(16)){ @@ -87,6 +75,6 @@ abstract class ExperienceUtils{ $x = Math::solveQuadratic($a, $b, $c - $xp); - return (float) max($x); //we're only interested in the positive solution + return max($x); //we're only interested in the positive solution } } diff --git a/src/pocketmine/event/Cancellable.php b/src/pocketmine/event/Cancellable.php index f4017a199f..e284e739c8 100644 --- a/src/pocketmine/event/Cancellable.php +++ b/src/pocketmine/event/Cancellable.php @@ -23,18 +23,14 @@ declare(strict_types=1); namespace pocketmine\event; - /** * Events that can be cancelled must use the interface Cancellable */ interface Cancellable{ - /** - * @return bool - */ public function isCancelled() : bool; /** - * @param bool $value + * @return void */ public function setCancelled(bool $value = true); } diff --git a/src/pocketmine/event/Event.php b/src/pocketmine/event/Event.php index b2c0b9deed..1ed0f4f253 100644 --- a/src/pocketmine/event/Event.php +++ b/src/pocketmine/event/Event.php @@ -39,16 +39,11 @@ abstract class Event{ /** @var bool */ private $isCancelled = false; - /** - * @return string - */ final public function getEventName() : string{ return $this->eventName ?? get_class($this); } /** - * @return bool - * * @throws \BadMethodCallException */ public function isCancelled() : bool{ @@ -60,8 +55,6 @@ abstract class Event{ } /** - * @param bool $value - * * @throws \BadMethodCallException */ public function setCancelled(bool $value = true) : void{ diff --git a/src/pocketmine/event/EventPriority.php b/src/pocketmine/event/EventPriority.php index 71d52f1c1d..a6d65003ff 100644 --- a/src/pocketmine/event/EventPriority.php +++ b/src/pocketmine/event/EventPriority.php @@ -76,10 +76,6 @@ abstract class EventPriority{ public const MONITOR = 0; /** - * @param string $name - * - * @return int - * * @throws \InvalidArgumentException */ public static function fromString(string $name) : int{ diff --git a/src/pocketmine/event/HandlerList.php b/src/pocketmine/event/HandlerList.php index 6f630c7d2b..abfd41b1cc 100644 --- a/src/pocketmine/event/HandlerList.php +++ b/src/pocketmine/event/HandlerList.php @@ -31,9 +31,7 @@ use function in_array; use function spl_object_hash; class HandlerList{ - /** - * @var HandlerList[] classname => HandlerList - */ + /** @var HandlerList[] classname => HandlerList */ private static $allLists = []; /** @@ -61,9 +59,6 @@ class HandlerList{ * * Calling this method also lazily initializes the $classMap inheritance tree of handler lists. * - * @param string $event - * - * @return null|HandlerList * @throws \ReflectionException */ public static function getHandlerListFor(string $event) : ?HandlerList{ @@ -96,7 +91,6 @@ class HandlerList{ return self::$allLists; } - /** @var string */ private $class; /** @var RegisteredListener[][] */ @@ -112,8 +106,6 @@ class HandlerList{ } /** - * @param RegisteredListener $listener - * * @throws \Exception */ public function register(RegisteredListener $listener) : void{ @@ -157,17 +149,12 @@ class HandlerList{ } /** - * @param int $priority - * * @return RegisteredListener[] */ public function getListenersByPriority(int $priority) : array{ return $this->handlerSlots[$priority]; } - /** - * @return null|HandlerList - */ public function getParent() : ?HandlerList{ return $this->parentList; } diff --git a/src/pocketmine/event/block/BlockBreakEvent.php b/src/pocketmine/event/block/BlockBreakEvent.php index f294757993..63a6783f84 100644 --- a/src/pocketmine/event/block/BlockBreakEvent.php +++ b/src/pocketmine/event/block/BlockBreakEvent.php @@ -46,12 +46,7 @@ class BlockBreakEvent extends BlockEvent implements Cancellable{ protected $xpDrops; /** - * @param Player $player - * @param Block $block - * @param Item $item - * @param bool $instaBreak * @param Item[] $drops - * @param int $xpDrops */ public function __construct(Player $player, Block $block, Item $item, bool $instaBreak = false, array $drops, int $xpDrops = 0){ parent::__construct($block); @@ -65,7 +60,6 @@ class BlockBreakEvent extends BlockEvent implements Cancellable{ /** * Returns the player who is destroying the block. - * @return Player */ public function getPlayer() : Player{ return $this->player; @@ -73,7 +67,6 @@ class BlockBreakEvent extends BlockEvent implements Cancellable{ /** * Returns the item used to destroy the block. - * @return Item */ public function getItem() : Item{ return $this->item; @@ -82,21 +75,15 @@ class BlockBreakEvent extends BlockEvent implements Cancellable{ /** * Returns whether the block may be broken in less than the amount of time calculated. This is usually true for * creative players. - * - * @return bool */ public function getInstaBreak() : bool{ return $this->instaBreak; } - /** - * @param bool $instaBreak - */ public function setInstaBreak(bool $instaBreak) : void{ $this->instaBreak = $instaBreak; } - /** * @return Item[] */ @@ -122,8 +109,6 @@ class BlockBreakEvent extends BlockEvent implements Cancellable{ /** * Returns how much XP will be dropped by breaking this block. - * - * @return int */ public function getXpDropAmount() : int{ return $this->xpDrops; @@ -131,8 +116,6 @@ class BlockBreakEvent extends BlockEvent implements Cancellable{ /** * Sets how much XP will be dropped by breaking this block. - * - * @param int $amount */ public function setXpDropAmount(int $amount) : void{ if($amount < 0){ diff --git a/src/pocketmine/event/block/BlockBurnEvent.php b/src/pocketmine/event/block/BlockBurnEvent.php index 1764199d51..328e676691 100644 --- a/src/pocketmine/event/block/BlockBurnEvent.php +++ b/src/pocketmine/event/block/BlockBurnEvent.php @@ -40,7 +40,6 @@ class BlockBurnEvent extends BlockEvent implements Cancellable{ /** * Returns the block (usually Fire) which caused the target block to be burned away. - * @return Block */ public function getCausingBlock() : Block{ return $this->causingBlock; diff --git a/src/pocketmine/event/block/BlockEvent.php b/src/pocketmine/event/block/BlockEvent.php index ec70779322..d506529ba7 100644 --- a/src/pocketmine/event/block/BlockEvent.php +++ b/src/pocketmine/event/block/BlockEvent.php @@ -33,16 +33,10 @@ abstract class BlockEvent extends Event{ /** @var Block */ protected $block; - /** - * @param Block $block - */ public function __construct(Block $block){ $this->block = $block; } - /** - * @return Block - */ public function getBlock() : Block{ return $this->block; } diff --git a/src/pocketmine/event/block/BlockGrowEvent.php b/src/pocketmine/event/block/BlockGrowEvent.php index c2caff64fc..d6ff655d8b 100644 --- a/src/pocketmine/event/block/BlockGrowEvent.php +++ b/src/pocketmine/event/block/BlockGrowEvent.php @@ -38,9 +38,6 @@ class BlockGrowEvent extends BlockEvent implements Cancellable{ $this->newState = $newState; } - /** - * @return Block - */ public function getNewState() : Block{ return $this->newState; } diff --git a/src/pocketmine/event/block/BlockPlaceEvent.php b/src/pocketmine/event/block/BlockPlaceEvent.php index 44e3b9e6d3..d619164e2d 100644 --- a/src/pocketmine/event/block/BlockPlaceEvent.php +++ b/src/pocketmine/event/block/BlockPlaceEvent.php @@ -53,7 +53,6 @@ class BlockPlaceEvent extends BlockEvent implements Cancellable{ /** * Returns the player who is placing the block. - * @return Player */ public function getPlayer() : Player{ return $this->player; @@ -61,22 +60,15 @@ class BlockPlaceEvent extends BlockEvent implements Cancellable{ /** * Gets the item in hand - * @return Item */ public function getItem() : Item{ return $this->item; } - /** - * @return Block - */ public function getBlockReplaced() : Block{ return $this->blockReplace; } - /** - * @return Block - */ public function getBlockAgainst() : Block{ return $this->blockAgainst; } diff --git a/src/pocketmine/event/block/BlockSpreadEvent.php b/src/pocketmine/event/block/BlockSpreadEvent.php index d68fdb2ce9..098e2d6d91 100644 --- a/src/pocketmine/event/block/BlockSpreadEvent.php +++ b/src/pocketmine/event/block/BlockSpreadEvent.php @@ -37,9 +37,6 @@ class BlockSpreadEvent extends BlockFormEvent{ $this->source = $source; } - /** - * @return Block - */ public function getSource() : Block{ return $this->source; } diff --git a/src/pocketmine/event/block/SignChangeEvent.php b/src/pocketmine/event/block/SignChangeEvent.php index ff1e1f0564..c7d694bc21 100644 --- a/src/pocketmine/event/block/SignChangeEvent.php +++ b/src/pocketmine/event/block/SignChangeEvent.php @@ -38,8 +38,6 @@ class SignChangeEvent extends BlockEvent implements Cancellable{ private $lines = []; /** - * @param Block $theBlock - * @param Player $thePlayer * @param string[] $theLines */ public function __construct(Block $theBlock, Player $thePlayer, array $theLines){ @@ -48,9 +46,6 @@ class SignChangeEvent extends BlockEvent implements Cancellable{ $this->setLines($theLines); } - /** - * @return Player - */ public function getPlayer() : Player{ return $this->player; } @@ -65,8 +60,6 @@ class SignChangeEvent extends BlockEvent implements Cancellable{ /** * @param int $index 0-3 * - * @return string - * * @throws \InvalidArgumentException if the index is out of bounds */ public function getLine(int $index) : string{ @@ -91,7 +84,6 @@ class SignChangeEvent extends BlockEvent implements Cancellable{ /** * @param int $index 0-3 - * @param string $line * * @throws \InvalidArgumentException if the index is out of bounds */ diff --git a/src/pocketmine/event/entity/EntityBlockChangeEvent.php b/src/pocketmine/event/entity/EntityBlockChangeEvent.php index 4ac9a86244..482d6485c0 100644 --- a/src/pocketmine/event/entity/EntityBlockChangeEvent.php +++ b/src/pocketmine/event/entity/EntityBlockChangeEvent.php @@ -42,16 +42,10 @@ class EntityBlockChangeEvent extends EntityEvent implements Cancellable{ $this->to = $to; } - /** - * @return Block - */ public function getBlock() : Block{ return $this->from; } - /** - * @return Block - */ public function getTo() : Block{ return $this->to; } diff --git a/src/pocketmine/event/entity/EntityCombustByBlockEvent.php b/src/pocketmine/event/entity/EntityCombustByBlockEvent.php index 85f524a94e..9b1d56f5a6 100644 --- a/src/pocketmine/event/entity/EntityCombustByBlockEvent.php +++ b/src/pocketmine/event/entity/EntityCombustByBlockEvent.php @@ -30,19 +30,11 @@ class EntityCombustByBlockEvent extends EntityCombustEvent{ /** @var Block */ protected $combuster; - /** - * @param Block $combuster - * @param Entity $combustee - * @param int $duration - */ public function __construct(Block $combuster, Entity $combustee, int $duration){ parent::__construct($combustee, $duration); $this->combuster = $combuster; } - /** - * @return Block - */ public function getCombuster() : Block{ return $this->combuster; } diff --git a/src/pocketmine/event/entity/EntityCombustByEntityEvent.php b/src/pocketmine/event/entity/EntityCombustByEntityEvent.php index cfa448de29..435ab670a9 100644 --- a/src/pocketmine/event/entity/EntityCombustByEntityEvent.php +++ b/src/pocketmine/event/entity/EntityCombustByEntityEvent.php @@ -29,19 +29,11 @@ class EntityCombustByEntityEvent extends EntityCombustEvent{ /** @var Entity */ protected $combuster; - /** - * @param Entity $combuster - * @param Entity $combustee - * @param int $duration - */ public function __construct(Entity $combuster, Entity $combustee, int $duration){ parent::__construct($combustee, $duration); $this->combuster = $combuster; } - /** - * @return Entity - */ public function getCombuster() : Entity{ return $this->combuster; } diff --git a/src/pocketmine/event/entity/EntityCombustEvent.php b/src/pocketmine/event/entity/EntityCombustEvent.php index 17f7634910..61dea752d4 100644 --- a/src/pocketmine/event/entity/EntityCombustEvent.php +++ b/src/pocketmine/event/entity/EntityCombustEvent.php @@ -27,12 +27,9 @@ use pocketmine\entity\Entity; use pocketmine\event\Cancellable; class EntityCombustEvent extends EntityEvent implements Cancellable{ + /** @var int */ protected $duration; - /** - * @param Entity $combustee - * @param int $duration - */ public function __construct(Entity $combustee, int $duration){ $this->entity = $combustee; $this->duration = $duration; @@ -40,7 +37,6 @@ class EntityCombustEvent extends EntityEvent implements Cancellable{ /** * Returns the duration in seconds the entity will burn for. - * @return int */ public function getDuration() : int{ return $this->duration; diff --git a/src/pocketmine/event/entity/EntityDamageByBlockEvent.php b/src/pocketmine/event/entity/EntityDamageByBlockEvent.php index 044e679edf..d6699ea13f 100644 --- a/src/pocketmine/event/entity/EntityDamageByBlockEvent.php +++ b/src/pocketmine/event/entity/EntityDamageByBlockEvent.php @@ -34,10 +34,6 @@ class EntityDamageByBlockEvent extends EntityDamageEvent{ private $damager; /** - * @param Block $damager - * @param Entity $entity - * @param int $cause - * @param float $damage * @param float[] $modifiers */ public function __construct(Block $damager, Entity $entity, int $cause, float $damage, array $modifiers = []){ @@ -45,9 +41,6 @@ class EntityDamageByBlockEvent extends EntityDamageEvent{ parent::__construct($entity, $cause, $damage, $modifiers); } - /** - * @return Block - */ public function getDamager() : Block{ return $this->damager; } diff --git a/src/pocketmine/event/entity/EntityDamageByChildEntityEvent.php b/src/pocketmine/event/entity/EntityDamageByChildEntityEvent.php index 879af9e684..764d844da0 100644 --- a/src/pocketmine/event/entity/EntityDamageByChildEntityEvent.php +++ b/src/pocketmine/event/entity/EntityDamageByChildEntityEvent.php @@ -33,11 +33,6 @@ class EntityDamageByChildEntityEvent extends EntityDamageByEntityEvent{ private $childEntityEid; /** - * @param Entity $damager - * @param Entity $childEntity - * @param Entity $entity - * @param int $cause - * @param float $damage * @param float[] $modifiers */ public function __construct(Entity $damager, Entity $childEntity, Entity $entity, int $cause, float $damage, array $modifiers = []){ @@ -47,8 +42,6 @@ class EntityDamageByChildEntityEvent extends EntityDamageByEntityEvent{ /** * Returns the entity which caused the damage, or null if the entity has been killed or closed. - * - * @return Entity|null */ public function getChild() : ?Entity{ return $this->getEntity()->getLevel()->getServer()->findEntity($this->childEntityEid); diff --git a/src/pocketmine/event/entity/EntityDamageByEntityEvent.php b/src/pocketmine/event/entity/EntityDamageByEntityEvent.php index 970818aa5b..3bef428ad9 100644 --- a/src/pocketmine/event/entity/EntityDamageByEntityEvent.php +++ b/src/pocketmine/event/entity/EntityDamageByEntityEvent.php @@ -37,12 +37,7 @@ class EntityDamageByEntityEvent extends EntityDamageEvent{ private $knockBack; /** - * @param Entity $damager - * @param Entity $entity - * @param int $cause - * @param float $damage * @param float[] $modifiers - * @param float $knockBack */ public function __construct(Entity $damager, Entity $entity, int $cause, float $damage, array $modifiers = [], float $knockBack = 0.4){ $this->damagerEntityId = $damager->getId(); @@ -65,23 +60,15 @@ class EntityDamageByEntityEvent extends EntityDamageEvent{ /** * Returns the attacking entity, or null if the attacker has been killed or closed. - * - * @return Entity|null */ public function getDamager() : ?Entity{ return $this->getEntity()->getLevel()->getServer()->findEntity($this->damagerEntityId); } - /** - * @return float - */ public function getKnockBack() : float{ return $this->knockBack; } - /** - * @param float $knockBack - */ public function setKnockBack(float $knockBack) : void{ $this->knockBack = $knockBack; } diff --git a/src/pocketmine/event/entity/EntityDamageEvent.php b/src/pocketmine/event/entity/EntityDamageEvent.php index 9792a7d2e1..6e8c5a21e3 100644 --- a/src/pocketmine/event/entity/EntityDamageEvent.php +++ b/src/pocketmine/event/entity/EntityDamageEvent.php @@ -73,11 +73,7 @@ class EntityDamageEvent extends EntityEvent implements Cancellable{ /** @var int */ private $attackCooldown = 10; - /** - * @param Entity $entity - * @param int $cause - * @param float $damage * @param float[] $modifiers */ public function __construct(Entity $entity, int $cause, float $damage, array $modifiers = []){ @@ -89,17 +85,12 @@ class EntityDamageEvent extends EntityEvent implements Cancellable{ $this->originals = $this->modifiers; } - /** - * @return int - */ public function getCause() : int{ return $this->cause; } /** * Returns the base amount of damage applied, before modifiers. - * - * @return float */ public function getBaseDamage() : float{ return $this->baseDamage; @@ -109,8 +100,6 @@ class EntityDamageEvent extends EntityEvent implements Cancellable{ * Sets the base amount of damage applied, optionally recalculating modifiers. * * TODO: add ability to recalculate modifiers when this is set - * - * @param float $damage */ public function setBaseDamage(float $damage) : void{ $this->baseDamage = $damage; @@ -118,8 +107,6 @@ class EntityDamageEvent extends EntityEvent implements Cancellable{ /** * Returns the original base amount of damage applied, before alterations by plugins. - * - * @return float */ public function getOriginalBaseDamage() : float{ return $this->originalBase; @@ -132,11 +119,6 @@ class EntityDamageEvent extends EntityEvent implements Cancellable{ return $this->originals; } - /** - * @param int $type - * - * @return float - */ public function getOriginalModifier(int $type) : float{ return $this->originals[$type] ?? 0.0; } @@ -148,42 +130,24 @@ class EntityDamageEvent extends EntityEvent implements Cancellable{ return $this->modifiers; } - /** - * @param int $type - * - * @return float - */ public function getModifier(int $type) : float{ return $this->modifiers[$type] ?? 0.0; } - /** - * @param float $damage - * @param int $type - */ public function setModifier(float $damage, int $type) : void{ $this->modifiers[$type] = $damage; } - /** - * @param int $type - * - * @return bool - */ public function isApplicable(int $type) : bool{ return isset($this->modifiers[$type]); } - /** - * @return float - */ public function getFinalDamage() : float{ return $this->baseDamage + array_sum($this->modifiers); } /** * Returns whether an entity can use armour points to reduce this type of damage. - * @return bool */ public function canBeReducedByArmor() : bool{ switch($this->cause){ @@ -204,8 +168,6 @@ class EntityDamageEvent extends EntityEvent implements Cancellable{ /** * Returns the cooldown in ticks before the target entity can be attacked again. - * - * @return int */ public function getAttackCooldown() : int{ return $this->attackCooldown; @@ -215,8 +177,6 @@ class EntityDamageEvent extends EntityEvent implements Cancellable{ * Sets the cooldown in ticks before the target entity can be attacked again. * * NOTE: This value is not used in non-Living entities - * - * @param int $attackCooldown */ public function setAttackCooldown(int $attackCooldown) : void{ $this->attackCooldown = $attackCooldown; diff --git a/src/pocketmine/event/entity/EntityDeathEvent.php b/src/pocketmine/event/entity/EntityDeathEvent.php index aeb7e55744..3dfd9cb1a5 100644 --- a/src/pocketmine/event/entity/EntityDeathEvent.php +++ b/src/pocketmine/event/entity/EntityDeathEvent.php @@ -33,7 +33,6 @@ class EntityDeathEvent extends EntityEvent{ private $xp; /** - * @param Living $entity * @param Item[] $drops * @param int $xp */ diff --git a/src/pocketmine/event/entity/EntityDespawnEvent.php b/src/pocketmine/event/entity/EntityDespawnEvent.php index e5d239c39d..ca6850f6cb 100644 --- a/src/pocketmine/event/entity/EntityDespawnEvent.php +++ b/src/pocketmine/event/entity/EntityDespawnEvent.php @@ -37,9 +37,6 @@ class EntityDespawnEvent extends EntityEvent{ /** @var int */ private $entityType; - /** - * @param Entity $entity - */ public function __construct(Entity $entity){ $this->entity = $entity; $this->entityType = $entity::NETWORK_ID; @@ -47,7 +44,6 @@ class EntityDespawnEvent extends EntityEvent{ /** * @deprecated - * @return int */ public function getType() : int{ return $this->entityType; @@ -55,7 +51,6 @@ class EntityDespawnEvent extends EntityEvent{ /** * @deprecated - * @return bool */ public function isCreature() : bool{ return $this->entity instanceof Creature; @@ -63,7 +58,6 @@ class EntityDespawnEvent extends EntityEvent{ /** * @deprecated - * @return bool */ public function isHuman() : bool{ return $this->entity instanceof Human; @@ -71,7 +65,6 @@ class EntityDespawnEvent extends EntityEvent{ /** * @deprecated - * @return bool */ public function isProjectile() : bool{ return $this->entity instanceof Projectile; @@ -79,7 +72,6 @@ class EntityDespawnEvent extends EntityEvent{ /** * @deprecated - * @return bool */ public function isVehicle() : bool{ return $this->entity instanceof Vehicle; @@ -87,7 +79,6 @@ class EntityDespawnEvent extends EntityEvent{ /** * @deprecated - * @return bool */ public function isItem() : bool{ return $this->entity instanceof ItemEntity; diff --git a/src/pocketmine/event/entity/EntityEffectAddEvent.php b/src/pocketmine/event/entity/EntityEffectAddEvent.php index d1a84c03b8..ddc382a778 100644 --- a/src/pocketmine/event/entity/EntityEffectAddEvent.php +++ b/src/pocketmine/event/entity/EntityEffectAddEvent.php @@ -33,11 +33,6 @@ class EntityEffectAddEvent extends EntityEffectEvent{ /** @var EffectInstance|null */ private $oldEffect; - /** - * @param Entity $entity - * @param EffectInstance $effect - * @param EffectInstance $oldEffect - */ public function __construct(Entity $entity, EffectInstance $effect, EffectInstance $oldEffect = null){ parent::__construct($entity, $effect); $this->oldEffect = $oldEffect; @@ -45,23 +40,15 @@ class EntityEffectAddEvent extends EntityEffectEvent{ /** * Returns whether the effect addition will replace an existing effect already applied to the entity. - * - * @return bool */ public function willModify() : bool{ return $this->hasOldEffect(); } - /** - * @return bool - */ public function hasOldEffect() : bool{ return $this->oldEffect instanceof EffectInstance; } - /** - * @return EffectInstance|null - */ public function getOldEffect() : ?EffectInstance{ return $this->oldEffect; } diff --git a/src/pocketmine/event/entity/EntityExplodeEvent.php b/src/pocketmine/event/entity/EntityExplodeEvent.php index 3a7256f310..4d920a3d2e 100644 --- a/src/pocketmine/event/entity/EntityExplodeEvent.php +++ b/src/pocketmine/event/entity/EntityExplodeEvent.php @@ -35,19 +35,14 @@ class EntityExplodeEvent extends EntityEvent implements Cancellable{ /** @var Position */ protected $position; - /** - * @var Block[] - */ + /** @var Block[] */ protected $blocks; /** @var float */ protected $yield; /** - * @param Entity $entity - * @param Position $position * @param Block[] $blocks - * @param float $yield */ public function __construct(Entity $entity, Position $position, array $blocks, float $yield){ $this->entity = $entity; @@ -56,9 +51,6 @@ class EntityExplodeEvent extends EntityEvent implements Cancellable{ $this->yield = $yield; } - /** - * @return Position - */ public function getPosition() : Position{ return $this->position; } @@ -77,16 +69,10 @@ class EntityExplodeEvent extends EntityEvent implements Cancellable{ $this->blocks = $blocks; } - /** - * @return float - */ public function getYield() : float{ return $this->yield; } - /** - * @param float $yield - */ public function setYield(float $yield) : void{ $this->yield = $yield; } diff --git a/src/pocketmine/event/entity/EntityInventoryChangeEvent.php b/src/pocketmine/event/entity/EntityInventoryChangeEvent.php index 0e7c12538e..f5fbb6ea32 100644 --- a/src/pocketmine/event/entity/EntityInventoryChangeEvent.php +++ b/src/pocketmine/event/entity/EntityInventoryChangeEvent.php @@ -47,7 +47,6 @@ class EntityInventoryChangeEvent extends EntityEvent implements Cancellable{ /** * Returns the inventory slot number affected by the event. - * @return int */ public function getSlot() : int{ return $this->slot; @@ -55,22 +54,17 @@ class EntityInventoryChangeEvent extends EntityEvent implements Cancellable{ /** * Returns the item which will be in the slot after the event. - * @return Item */ public function getNewItem() : Item{ return $this->newItem; } - /** - * @param Item $item - */ public function setNewItem(Item $item) : void{ $this->newItem = $item; } /** * Returns the item currently in the slot. - * @return Item */ public function getOldItem() : Item{ return $this->oldItem; diff --git a/src/pocketmine/event/entity/EntityMotionEvent.php b/src/pocketmine/event/entity/EntityMotionEvent.php index 36b9a2d1c0..9b6e81a87c 100644 --- a/src/pocketmine/event/entity/EntityMotionEvent.php +++ b/src/pocketmine/event/entity/EntityMotionEvent.php @@ -36,9 +36,6 @@ class EntityMotionEvent extends EntityEvent implements Cancellable{ $this->mot = $mot; } - /** - * @return Vector3 - */ public function getVector() : Vector3{ return $this->mot; } diff --git a/src/pocketmine/event/entity/EntityRegainHealthEvent.php b/src/pocketmine/event/entity/EntityRegainHealthEvent.php index da8a24b18d..44a86833a1 100644 --- a/src/pocketmine/event/entity/EntityRegainHealthEvent.php +++ b/src/pocketmine/event/entity/EntityRegainHealthEvent.php @@ -38,35 +38,22 @@ class EntityRegainHealthEvent extends EntityEvent implements Cancellable{ /** @var int */ private $reason; - - /** - * @param Entity $entity - * @param float $amount - * @param int $regainReason - */ public function __construct(Entity $entity, float $amount, int $regainReason){ $this->entity = $entity; $this->amount = $amount; $this->reason = $regainReason; } - /** - * @return float - */ public function getAmount() : float{ return $this->amount; } - /** - * @param float $amount - */ public function setAmount(float $amount) : void{ $this->amount = $amount; } /** * Returns one of the CAUSE_* constants to indicate why this regeneration occurred. - * @return int */ public function getRegainReason() : int{ return $this->reason; diff --git a/src/pocketmine/event/entity/EntityShootBowEvent.php b/src/pocketmine/event/entity/EntityShootBowEvent.php index cafede44c0..05e9d43255 100644 --- a/src/pocketmine/event/entity/EntityShootBowEvent.php +++ b/src/pocketmine/event/entity/EntityShootBowEvent.php @@ -38,12 +38,6 @@ class EntityShootBowEvent extends EntityEvent implements Cancellable{ /** @var float */ private $force; - /** - * @param Living $shooter - * @param Item $bow - * @param Projectile $projectile - * @param float $force - */ public function __construct(Living $shooter, Item $bow, Projectile $projectile, float $force){ $this->entity = $shooter; $this->bow = $bow; @@ -58,9 +52,6 @@ class EntityShootBowEvent extends EntityEvent implements Cancellable{ return $this->entity; } - /** - * @return Item - */ public function getBow() : Item{ return $this->bow; } @@ -69,16 +60,11 @@ class EntityShootBowEvent extends EntityEvent implements Cancellable{ * Returns the entity considered as the projectile in this event. * * NOTE: This might not return a Projectile if a plugin modified the target entity. - * - * @return Entity */ public function getProjectile() : Entity{ return $this->projectile; } - /** - * @param Entity $projectile - */ public function setProjectile(Entity $projectile) : void{ if($projectile !== $this->projectile){ if(count($this->projectile->getViewers()) === 0){ @@ -88,16 +74,10 @@ class EntityShootBowEvent extends EntityEvent implements Cancellable{ } } - /** - * @return float - */ public function getForce() : float{ return $this->force; } - /** - * @param float $force - */ public function setForce(float $force) : void{ $this->force = $force; } diff --git a/src/pocketmine/event/entity/EntitySpawnEvent.php b/src/pocketmine/event/entity/EntitySpawnEvent.php index fe1f800ae2..beb00bd329 100644 --- a/src/pocketmine/event/entity/EntitySpawnEvent.php +++ b/src/pocketmine/event/entity/EntitySpawnEvent.php @@ -38,9 +38,6 @@ class EntitySpawnEvent extends EntityEvent{ /** @var int */ private $entityType; - /** - * @param Entity $entity - */ public function __construct(Entity $entity){ $this->entity = $entity; $this->entityType = $entity::NETWORK_ID; @@ -48,7 +45,6 @@ class EntitySpawnEvent extends EntityEvent{ /** * @deprecated - * @return Position */ public function getPosition() : Position{ return $this->entity->getPosition(); @@ -56,7 +52,6 @@ class EntitySpawnEvent extends EntityEvent{ /** * @deprecated - * @return int */ public function getType() : int{ return $this->entityType; @@ -64,7 +59,6 @@ class EntitySpawnEvent extends EntityEvent{ /** * @deprecated - * @return bool */ public function isCreature() : bool{ return $this->entity instanceof Creature; @@ -72,7 +66,6 @@ class EntitySpawnEvent extends EntityEvent{ /** * @deprecated - * @return bool */ public function isHuman() : bool{ return $this->entity instanceof Human; @@ -80,7 +73,6 @@ class EntitySpawnEvent extends EntityEvent{ /** * @deprecated - * @return bool */ public function isProjectile() : bool{ return $this->entity instanceof Projectile; @@ -88,7 +80,6 @@ class EntitySpawnEvent extends EntityEvent{ /** * @deprecated - * @return bool */ public function isVehicle() : bool{ return $this->entity instanceof Vehicle; @@ -96,7 +87,6 @@ class EntitySpawnEvent extends EntityEvent{ /** * @deprecated - * @return bool */ public function isItem() : bool{ return $this->entity instanceof ItemEntity; diff --git a/src/pocketmine/event/entity/EntityTeleportEvent.php b/src/pocketmine/event/entity/EntityTeleportEvent.php index 7b467461a3..5309912702 100644 --- a/src/pocketmine/event/entity/EntityTeleportEvent.php +++ b/src/pocketmine/event/entity/EntityTeleportEvent.php @@ -39,23 +39,14 @@ class EntityTeleportEvent extends EntityEvent implements Cancellable{ $this->to = $to; } - /** - * @return Position - */ public function getFrom() : Position{ return $this->from; } - /** - * @return Position - */ public function getTo() : Position{ return $this->to; } - /** - * @param Position $to - */ public function setTo(Position $to) : void{ $this->to = $to; } diff --git a/src/pocketmine/event/entity/ExplosionPrimeEvent.php b/src/pocketmine/event/entity/ExplosionPrimeEvent.php index db6c734470..d35cf45fda 100644 --- a/src/pocketmine/event/entity/ExplosionPrimeEvent.php +++ b/src/pocketmine/event/entity/ExplosionPrimeEvent.php @@ -35,19 +35,12 @@ class ExplosionPrimeEvent extends EntityEvent implements Cancellable{ /** @var bool */ private $blockBreaking; - /** - * @param Entity $entity - * @param float $force - */ public function __construct(Entity $entity, float $force){ $this->entity = $entity; $this->force = $force; $this->blockBreaking = true; } - /** - * @return float - */ public function getForce() : float{ return $this->force; } @@ -56,16 +49,10 @@ class ExplosionPrimeEvent extends EntityEvent implements Cancellable{ $this->force = $force; } - /** - * @return bool - */ public function isBlockBreaking() : bool{ return $this->blockBreaking; } - /** - * @param bool $affectsBlocks - */ public function setBlockBreaking(bool $affectsBlocks) : void{ $this->blockBreaking = $affectsBlocks; } diff --git a/src/pocketmine/event/entity/ItemDespawnEvent.php b/src/pocketmine/event/entity/ItemDespawnEvent.php index c934dd5653..269e7658d4 100644 --- a/src/pocketmine/event/entity/ItemDespawnEvent.php +++ b/src/pocketmine/event/entity/ItemDespawnEvent.php @@ -28,9 +28,6 @@ use pocketmine\event\Cancellable; class ItemDespawnEvent extends EntityEvent implements Cancellable{ - /** - * @param ItemEntity $item - */ public function __construct(ItemEntity $item){ $this->entity = $item; diff --git a/src/pocketmine/event/entity/ItemSpawnEvent.php b/src/pocketmine/event/entity/ItemSpawnEvent.php index ed76cd0623..3675550376 100644 --- a/src/pocketmine/event/entity/ItemSpawnEvent.php +++ b/src/pocketmine/event/entity/ItemSpawnEvent.php @@ -27,9 +27,6 @@ use pocketmine\entity\object\ItemEntity; class ItemSpawnEvent extends EntityEvent{ - /** - * @param ItemEntity $item - */ public function __construct(ItemEntity $item){ $this->entity = $item; diff --git a/src/pocketmine/event/entity/ProjectileHitBlockEvent.php b/src/pocketmine/event/entity/ProjectileHitBlockEvent.php index 25cd856a48..d1929ed912 100644 --- a/src/pocketmine/event/entity/ProjectileHitBlockEvent.php +++ b/src/pocketmine/event/entity/ProjectileHitBlockEvent.php @@ -39,8 +39,6 @@ class ProjectileHitBlockEvent extends ProjectileHitEvent{ /** * Returns the Block struck by the projectile. * Hint: to get the block face hit, look at the RayTraceResult. - * - * @return Block */ public function getBlockHit() : Block{ return $this->blockHit; diff --git a/src/pocketmine/event/entity/ProjectileHitEntityEvent.php b/src/pocketmine/event/entity/ProjectileHitEntityEvent.php index e8508e3e58..3fe8b42b4c 100644 --- a/src/pocketmine/event/entity/ProjectileHitEntityEvent.php +++ b/src/pocketmine/event/entity/ProjectileHitEntityEvent.php @@ -38,8 +38,6 @@ class ProjectileHitEntityEvent extends ProjectileHitEvent{ /** * Returns the Entity struck by the projectile. - * - * @return Entity */ public function getEntityHit() : Entity{ return $this->entityHit; diff --git a/src/pocketmine/event/entity/ProjectileHitEvent.php b/src/pocketmine/event/entity/ProjectileHitEvent.php index 17025c61bc..b5a800d1cf 100644 --- a/src/pocketmine/event/entity/ProjectileHitEvent.php +++ b/src/pocketmine/event/entity/ProjectileHitEvent.php @@ -33,10 +33,6 @@ abstract class ProjectileHitEvent extends EntityEvent{ /** @var RayTraceResult */ private $rayTraceResult; - /** - * @param Projectile $entity - * @param RayTraceResult $rayTraceResult - */ public function __construct(Projectile $entity, RayTraceResult $rayTraceResult){ $this->entity = $entity; $this->rayTraceResult = $rayTraceResult; @@ -52,8 +48,6 @@ abstract class ProjectileHitEvent extends EntityEvent{ /** * Returns a RayTraceResult object containing information such as the exact position struck, the AABB it hit, and * the face of the AABB that it hit. - * - * @return RayTraceResult */ public function getRayTraceResult() : RayTraceResult{ return $this->rayTraceResult; diff --git a/src/pocketmine/event/entity/ProjectileLaunchEvent.php b/src/pocketmine/event/entity/ProjectileLaunchEvent.php index 6aafb585c3..30cf1149c9 100644 --- a/src/pocketmine/event/entity/ProjectileLaunchEvent.php +++ b/src/pocketmine/event/entity/ProjectileLaunchEvent.php @@ -27,9 +27,6 @@ use pocketmine\entity\projectile\Projectile; use pocketmine\event\Cancellable; class ProjectileLaunchEvent extends EntityEvent implements Cancellable{ - /** - * @param Projectile $entity - */ public function __construct(Projectile $entity){ $this->entity = $entity; diff --git a/src/pocketmine/event/inventory/CraftItemEvent.php b/src/pocketmine/event/inventory/CraftItemEvent.php index 3aaaacede9..263cb5920e 100644 --- a/src/pocketmine/event/inventory/CraftItemEvent.php +++ b/src/pocketmine/event/inventory/CraftItemEvent.php @@ -43,9 +43,6 @@ class CraftItemEvent extends Event implements Cancellable{ private $outputs; /** - * @param CraftingTransaction $transaction - * @param CraftingRecipe $recipe - * @param int $repetitions * @param Item[] $inputs * @param Item[] $outputs */ @@ -59,8 +56,6 @@ class CraftItemEvent extends Event implements Cancellable{ /** * Returns the inventory transaction involved in this crafting event. - * - * @return CraftingTransaction */ public function getTransaction() : CraftingTransaction{ return $this->transaction; @@ -68,8 +63,6 @@ class CraftItemEvent extends Event implements Cancellable{ /** * Returns the recipe crafted. - * - * @return CraftingRecipe */ public function getRecipe() : CraftingRecipe{ return $this->recipe; @@ -78,8 +71,6 @@ class CraftItemEvent extends Event implements Cancellable{ /** * Returns the number of times the recipe was crafted. This is usually 1, but might be more in the case of recipe * book shift-clicks (which craft lots of items in a batch). - * - * @return int */ public function getRepetitions() : int{ return $this->repetitions; @@ -103,9 +94,6 @@ class CraftItemEvent extends Event implements Cancellable{ return $this->outputs; } - /** - * @return Player - */ public function getPlayer() : Player{ return $this->transaction->getSource(); } diff --git a/src/pocketmine/event/inventory/FurnaceBurnEvent.php b/src/pocketmine/event/inventory/FurnaceBurnEvent.php index b0637ccc08..f52ff4185e 100644 --- a/src/pocketmine/event/inventory/FurnaceBurnEvent.php +++ b/src/pocketmine/event/inventory/FurnaceBurnEvent.php @@ -38,11 +38,6 @@ class FurnaceBurnEvent extends BlockEvent implements Cancellable{ /** @var bool */ private $burning = true; - /** - * @param Furnace $furnace - * @param Item $fuel - * @param int $burnTime - */ public function __construct(Furnace $furnace, Item $fuel, int $burnTime){ parent::__construct($furnace->getBlock()); $this->fuel = $fuel; @@ -50,44 +45,26 @@ class FurnaceBurnEvent extends BlockEvent implements Cancellable{ $this->furnace = $furnace; } - /** - * @return Furnace - */ public function getFurnace() : Furnace{ return $this->furnace; } - /** - * @return Item - */ public function getFuel() : Item{ return $this->fuel; } - /** - * @return int - */ public function getBurnTime() : int{ return $this->burnTime; } - /** - * @param int $burnTime - */ public function setBurnTime(int $burnTime) : void{ $this->burnTime = $burnTime; } - /** - * @return bool - */ public function isBurning() : bool{ return $this->burning; } - /** - * @param bool $burning - */ public function setBurning(bool $burning) : void{ $this->burning = $burning; } diff --git a/src/pocketmine/event/inventory/FurnaceSmeltEvent.php b/src/pocketmine/event/inventory/FurnaceSmeltEvent.php index 5b487d1c30..3b44455752 100644 --- a/src/pocketmine/event/inventory/FurnaceSmeltEvent.php +++ b/src/pocketmine/event/inventory/FurnaceSmeltEvent.php @@ -36,11 +36,6 @@ class FurnaceSmeltEvent extends BlockEvent implements Cancellable{ /** @var Item */ private $result; - /** - * @param Furnace $furnace - * @param Item $source - * @param Item $result - */ public function __construct(Furnace $furnace, Item $source, Item $result){ parent::__construct($furnace->getBlock()); $this->source = clone $source; @@ -49,30 +44,18 @@ class FurnaceSmeltEvent extends BlockEvent implements Cancellable{ $this->furnace = $furnace; } - /** - * @return Furnace - */ public function getFurnace() : Furnace{ return $this->furnace; } - /** - * @return Item - */ public function getSource() : Item{ return $this->source; } - /** - * @return Item - */ public function getResult() : Item{ return $this->result; } - /** - * @param Item $result - */ public function setResult(Item $result) : void{ $this->result = $result; } diff --git a/src/pocketmine/event/inventory/InventoryCloseEvent.php b/src/pocketmine/event/inventory/InventoryCloseEvent.php index 929efb8d71..1a862c7184 100644 --- a/src/pocketmine/event/inventory/InventoryCloseEvent.php +++ b/src/pocketmine/event/inventory/InventoryCloseEvent.php @@ -30,18 +30,11 @@ class InventoryCloseEvent extends InventoryEvent{ /** @var Player */ private $who; - /** - * @param Inventory $inventory - * @param Player $who - */ public function __construct(Inventory $inventory, Player $who){ $this->who = $who; parent::__construct($inventory); } - /** - * @return Player - */ public function getPlayer() : Player{ return $this->who; } diff --git a/src/pocketmine/event/inventory/InventoryEvent.php b/src/pocketmine/event/inventory/InventoryEvent.php index 7c103e1a80..7c00c35fe1 100644 --- a/src/pocketmine/event/inventory/InventoryEvent.php +++ b/src/pocketmine/event/inventory/InventoryEvent.php @@ -38,9 +38,6 @@ abstract class InventoryEvent extends Event{ $this->inventory = $inventory; } - /** - * @return Inventory - */ public function getInventory() : Inventory{ return $this->inventory; } diff --git a/src/pocketmine/event/inventory/InventoryOpenEvent.php b/src/pocketmine/event/inventory/InventoryOpenEvent.php index 0b26c9bfb0..c29ab45ff7 100644 --- a/src/pocketmine/event/inventory/InventoryOpenEvent.php +++ b/src/pocketmine/event/inventory/InventoryOpenEvent.php @@ -31,18 +31,11 @@ class InventoryOpenEvent extends InventoryEvent implements Cancellable{ /** @var Player */ private $who; - /** - * @param Inventory $inventory - * @param Player $who - */ public function __construct(Inventory $inventory, Player $who){ $this->who = $who; parent::__construct($inventory); } - /** - * @return Player - */ public function getPlayer() : Player{ return $this->who; } diff --git a/src/pocketmine/event/inventory/InventoryPickupArrowEvent.php b/src/pocketmine/event/inventory/InventoryPickupArrowEvent.php index 0efa7af7b3..eb26b30c1f 100644 --- a/src/pocketmine/event/inventory/InventoryPickupArrowEvent.php +++ b/src/pocketmine/event/inventory/InventoryPickupArrowEvent.php @@ -31,18 +31,11 @@ class InventoryPickupArrowEvent extends InventoryEvent implements Cancellable{ /** @var Arrow */ private $arrow; - /** - * @param Inventory $inventory - * @param Arrow $arrow - */ public function __construct(Inventory $inventory, Arrow $arrow){ $this->arrow = $arrow; parent::__construct($inventory); } - /** - * @return Arrow - */ public function getArrow() : Arrow{ return $this->arrow; } diff --git a/src/pocketmine/event/inventory/InventoryPickupItemEvent.php b/src/pocketmine/event/inventory/InventoryPickupItemEvent.php index f94e6dfeb5..d255b0238c 100644 --- a/src/pocketmine/event/inventory/InventoryPickupItemEvent.php +++ b/src/pocketmine/event/inventory/InventoryPickupItemEvent.php @@ -31,18 +31,11 @@ class InventoryPickupItemEvent extends InventoryEvent implements Cancellable{ /** @var ItemEntity */ private $item; - /** - * @param Inventory $inventory - * @param ItemEntity $item - */ public function __construct(Inventory $inventory, ItemEntity $item){ $this->item = $item; parent::__construct($inventory); } - /** - * @return ItemEntity - */ public function getItem() : ItemEntity{ return $this->item; } diff --git a/src/pocketmine/event/inventory/InventoryTransactionEvent.php b/src/pocketmine/event/inventory/InventoryTransactionEvent.php index 50d7671aea..bd3089fff2 100644 --- a/src/pocketmine/event/inventory/InventoryTransactionEvent.php +++ b/src/pocketmine/event/inventory/InventoryTransactionEvent.php @@ -35,16 +35,10 @@ class InventoryTransactionEvent extends Event implements Cancellable{ /** @var InventoryTransaction */ private $transaction; - /** - * @param InventoryTransaction $transaction - */ public function __construct(InventoryTransaction $transaction){ $this->transaction = $transaction; } - /** - * @return InventoryTransaction - */ public function getTransaction() : InventoryTransaction{ return $this->transaction; } diff --git a/src/pocketmine/event/level/ChunkEvent.php b/src/pocketmine/event/level/ChunkEvent.php index b155a14a10..1a995ac502 100644 --- a/src/pocketmine/event/level/ChunkEvent.php +++ b/src/pocketmine/event/level/ChunkEvent.php @@ -21,7 +21,6 @@ declare(strict_types=1); - namespace pocketmine\event\level; use pocketmine\level\format\Chunk; @@ -34,18 +33,11 @@ abstract class ChunkEvent extends LevelEvent{ /** @var Chunk */ private $chunk; - /** - * @param Level $level - * @param Chunk $chunk - */ public function __construct(Level $level, Chunk $chunk){ parent::__construct($level); $this->chunk = $chunk; } - /** - * @return Chunk - */ public function getChunk() : Chunk{ return $this->chunk; } diff --git a/src/pocketmine/event/level/ChunkLoadEvent.php b/src/pocketmine/event/level/ChunkLoadEvent.php index 660248d7f1..c8c08511ce 100644 --- a/src/pocketmine/event/level/ChunkLoadEvent.php +++ b/src/pocketmine/event/level/ChunkLoadEvent.php @@ -21,7 +21,6 @@ declare(strict_types=1); - namespace pocketmine\event\level; use pocketmine\level\format\Chunk; @@ -39,9 +38,6 @@ class ChunkLoadEvent extends ChunkEvent{ $this->newChunk = $newChunk; } - /** - * @return bool - */ public function isNewChunk() : bool{ return $this->newChunk; } diff --git a/src/pocketmine/event/level/LevelEvent.php b/src/pocketmine/event/level/LevelEvent.php index 7e24f5d281..16d4b01f8d 100644 --- a/src/pocketmine/event/level/LevelEvent.php +++ b/src/pocketmine/event/level/LevelEvent.php @@ -33,16 +33,10 @@ abstract class LevelEvent extends Event{ /** @var Level */ private $level; - /** - * @param Level $level - */ public function __construct(Level $level){ $this->level = $level; } - /** - * @return Level - */ public function getLevel() : Level{ return $this->level; } diff --git a/src/pocketmine/event/level/SpawnChangeEvent.php b/src/pocketmine/event/level/SpawnChangeEvent.php index 5c6476fe6f..4e73669dff 100644 --- a/src/pocketmine/event/level/SpawnChangeEvent.php +++ b/src/pocketmine/event/level/SpawnChangeEvent.php @@ -34,18 +34,11 @@ class SpawnChangeEvent extends LevelEvent{ /** @var Position */ private $previousSpawn; - /** - * @param Level $level - * @param Position $previousSpawn - */ public function __construct(Level $level, Position $previousSpawn){ parent::__construct($level); $this->previousSpawn = $previousSpawn; } - /** - * @return Position - */ public function getPreviousSpawn() : Position{ return $this->previousSpawn; } diff --git a/src/pocketmine/event/player/PlayerAchievementAwardedEvent.php b/src/pocketmine/event/player/PlayerAchievementAwardedEvent.php index 7b2231a9ab..25b83bae72 100644 --- a/src/pocketmine/event/player/PlayerAchievementAwardedEvent.php +++ b/src/pocketmine/event/player/PlayerAchievementAwardedEvent.php @@ -33,18 +33,11 @@ class PlayerAchievementAwardedEvent extends PlayerEvent implements Cancellable{ /** @var string */ protected $achievement; - /** - * @param Player $player - * @param string $achievementId - */ public function __construct(Player $player, string $achievementId){ $this->player = $player; $this->achievement = $achievementId; } - /** - * @return string - */ public function getAchievement() : string{ return $this->achievement; } diff --git a/src/pocketmine/event/player/PlayerAnimationEvent.php b/src/pocketmine/event/player/PlayerAnimationEvent.php index b0650446bf..0c34b648d8 100644 --- a/src/pocketmine/event/player/PlayerAnimationEvent.php +++ b/src/pocketmine/event/player/PlayerAnimationEvent.php @@ -33,18 +33,11 @@ class PlayerAnimationEvent extends PlayerEvent implements Cancellable{ /** @var int */ private $animationType; - /** - * @param Player $player - * @param int $animation - */ public function __construct(Player $player, int $animation){ $this->player = $player; $this->animationType = $animation; } - /** - * @return int - */ public function getAnimationType() : int{ return $this->animationType; } diff --git a/src/pocketmine/event/player/PlayerBedEnterEvent.php b/src/pocketmine/event/player/PlayerBedEnterEvent.php index e25ac35a73..f05c604cb7 100644 --- a/src/pocketmine/event/player/PlayerBedEnterEvent.php +++ b/src/pocketmine/event/player/PlayerBedEnterEvent.php @@ -36,9 +36,6 @@ class PlayerBedEnterEvent extends PlayerEvent implements Cancellable{ $this->bed = $bed; } - /** - * @return Block - */ public function getBed() : Block{ return $this->bed; } diff --git a/src/pocketmine/event/player/PlayerBedLeaveEvent.php b/src/pocketmine/event/player/PlayerBedLeaveEvent.php index 005bc750ce..e1038c970a 100644 --- a/src/pocketmine/event/player/PlayerBedLeaveEvent.php +++ b/src/pocketmine/event/player/PlayerBedLeaveEvent.php @@ -35,9 +35,6 @@ class PlayerBedLeaveEvent extends PlayerEvent{ $this->bed = $bed; } - /** - * @return Block - */ public function getBed() : Block{ return $this->bed; } diff --git a/src/pocketmine/event/player/PlayerBucketEvent.php b/src/pocketmine/event/player/PlayerBucketEvent.php index f207aeef98..81329b348e 100644 --- a/src/pocketmine/event/player/PlayerBucketEvent.php +++ b/src/pocketmine/event/player/PlayerBucketEvent.php @@ -41,13 +41,6 @@ abstract class PlayerBucketEvent extends PlayerEvent implements Cancellable{ /** @var Item */ private $item; - /** - * @param Player $who - * @param Block $blockClicked - * @param int $blockFace - * @param Item $bucket - * @param Item $itemInHand - */ public function __construct(Player $who, Block $blockClicked, int $blockFace, Item $bucket, Item $itemInHand){ $this->player = $who; $this->blockClicked = $blockClicked; @@ -58,8 +51,6 @@ abstract class PlayerBucketEvent extends PlayerEvent implements Cancellable{ /** * Returns the bucket used in this event - * - * @return Item */ public function getBucket() : Item{ return $this->bucket; @@ -67,30 +58,19 @@ abstract class PlayerBucketEvent extends PlayerEvent implements Cancellable{ /** * Returns the item in hand after the event - * - * @return Item */ public function getItem() : Item{ return $this->item; } - /** - * @param Item $item - */ public function setItem(Item $item) : void{ $this->item = $item; } - /** - * @return Block - */ public function getBlockClicked() : Block{ return $this->blockClicked; } - /** - * @return int - */ public function getBlockFace() : int{ return $this->blockFace; } diff --git a/src/pocketmine/event/player/PlayerChangeSkinEvent.php b/src/pocketmine/event/player/PlayerChangeSkinEvent.php index 8ebab4c165..0983c7a0f0 100644 --- a/src/pocketmine/event/player/PlayerChangeSkinEvent.php +++ b/src/pocketmine/event/player/PlayerChangeSkinEvent.php @@ -36,34 +36,21 @@ class PlayerChangeSkinEvent extends PlayerEvent implements Cancellable{ /** @var Skin */ private $newSkin; - /** - * @param Player $player - * @param Skin $oldSkin - * @param Skin $newSkin - */ public function __construct(Player $player, Skin $oldSkin, Skin $newSkin){ $this->player = $player; $this->oldSkin = $oldSkin; $this->newSkin = $newSkin; } - /** - * @return Skin - */ public function getOldSkin() : Skin{ return $this->oldSkin; } - /** - * @return Skin - */ public function getNewSkin() : Skin{ return $this->newSkin; } /** - * @param Skin $skin - * * @throws \InvalidArgumentException if the specified skin is not valid */ public function setNewSkin(Skin $skin) : void{ diff --git a/src/pocketmine/event/player/PlayerChatEvent.php b/src/pocketmine/event/player/PlayerChatEvent.php index 1b8bbcaff5..cc53447b39 100644 --- a/src/pocketmine/event/player/PlayerChatEvent.php +++ b/src/pocketmine/event/player/PlayerChatEvent.php @@ -40,15 +40,10 @@ class PlayerChatEvent extends PlayerEvent implements Cancellable{ /** @var string */ protected $format; - /** - * @var CommandSender[] - */ + /** @var CommandSender[] */ protected $recipients = []; /** - * @param Player $player - * @param string $message - * @param string $format * @param CommandSender[] $recipients */ public function __construct(Player $player, string $message, string $format = "chat.type.text", array $recipients = null){ @@ -68,39 +63,25 @@ class PlayerChatEvent extends PlayerEvent implements Cancellable{ } } - /** - * @return string - */ public function getMessage() : string{ return $this->message; } - /** - * @param string $message - */ public function setMessage(string $message) : void{ $this->message = $message; } /** * Changes the player that is sending the message - * - * @param Player $player */ public function setPlayer(Player $player) : void{ $this->player = $player; } - /** - * @return string - */ public function getFormat() : string{ return $this->format; } - /** - * @param string $format - */ public function setFormat(string $format) : void{ $this->format = $format; } diff --git a/src/pocketmine/event/player/PlayerCommandPreprocessEvent.php b/src/pocketmine/event/player/PlayerCommandPreprocessEvent.php index edeaa847d5..8ad542ecb0 100644 --- a/src/pocketmine/event/player/PlayerCommandPreprocessEvent.php +++ b/src/pocketmine/event/player/PlayerCommandPreprocessEvent.php @@ -38,33 +38,19 @@ class PlayerCommandPreprocessEvent extends PlayerEvent implements Cancellable{ /** @var string */ protected $message; - - /** - * @param Player $player - * @param string $message - */ public function __construct(Player $player, string $message){ $this->player = $player; $this->message = $message; } - /** - * @return string - */ public function getMessage() : string{ return $this->message; } - /** - * @param string $message - */ public function setMessage(string $message) : void{ $this->message = $message; } - /** - * @param Player $player - */ public function setPlayer(Player $player) : void{ $this->player = $player; } diff --git a/src/pocketmine/event/player/PlayerCreationEvent.php b/src/pocketmine/event/player/PlayerCreationEvent.php index f79a3411dc..73c98097b9 100644 --- a/src/pocketmine/event/player/PlayerCreationEvent.php +++ b/src/pocketmine/event/player/PlayerCreationEvent.php @@ -45,11 +45,8 @@ class PlayerCreationEvent extends Event{ private $playerClass; /** - * @param SourceInterface $interface * @param string $baseClass * @param string $playerClass - * @param string $address - * @param int $port */ public function __construct(SourceInterface $interface, $baseClass, $playerClass, string $address, int $port){ $this->interface = $interface; @@ -69,23 +66,14 @@ class PlayerCreationEvent extends Event{ $this->playerClass = $playerClass; } - /** - * @return SourceInterface - */ public function getInterface() : SourceInterface{ return $this->interface; } - /** - * @return string - */ public function getAddress() : string{ return $this->address; } - /** - * @return int - */ public function getPort() : int{ return $this->port; } @@ -99,6 +87,8 @@ class PlayerCreationEvent extends Event{ /** * @param string $class + * + * @return void */ public function setBaseClass($class){ if(!is_a($class, $this->baseClass, true)){ @@ -117,6 +107,8 @@ class PlayerCreationEvent extends Event{ /** * @param string $class + * + * @return void */ public function setPlayerClass($class){ if(!is_a($class, $this->baseClass, true)){ diff --git a/src/pocketmine/event/player/PlayerDataSaveEvent.php b/src/pocketmine/event/player/PlayerDataSaveEvent.php index c3296bdce3..b142fe6d8b 100644 --- a/src/pocketmine/event/player/PlayerDataSaveEvent.php +++ b/src/pocketmine/event/player/PlayerDataSaveEvent.php @@ -45,22 +45,17 @@ class PlayerDataSaveEvent extends Event implements Cancellable{ /** * Returns the data to be written to disk as a CompoundTag - * @return CompoundTag */ public function getSaveData() : CompoundTag{ return $this->data; } - /** - * @param CompoundTag $data - */ public function setSaveData(CompoundTag $data) : void{ $this->data = $data; } /** * Returns the username of the player whose data is being saved. This is not necessarily an online player. - * @return string */ public function getPlayerName() : string{ return $this->playerName; diff --git a/src/pocketmine/event/player/PlayerDeathEvent.php b/src/pocketmine/event/player/PlayerDeathEvent.php index 25e8d12ca2..9d7e65903c 100644 --- a/src/pocketmine/event/player/PlayerDeathEvent.php +++ b/src/pocketmine/event/player/PlayerDeathEvent.php @@ -40,10 +40,10 @@ class PlayerDeathEvent extends EntityDeathEvent{ /** @var TextContainer|string */ private $deathMessage; + /** @var bool */ private $keepInventory = false; /** - * @param Player $entity * @param Item[] $drops * @param string|TextContainer|null $deathMessage Null will cause the default vanilla message to be used * @param int $xp @@ -60,9 +60,6 @@ class PlayerDeathEvent extends EntityDeathEvent{ return $this->entity; } - /** - * @return Player - */ public function getPlayer() : Player{ return $this->entity; } @@ -91,11 +88,6 @@ class PlayerDeathEvent extends EntityDeathEvent{ /** * Returns the vanilla death message for the given death cause. - * - * @param string $name - * @param null|EntityDamageEvent $deathCause - * - * @return TranslationContainer */ public static function deriveMessage(string $name, ?EntityDamageEvent $deathCause) : TranslationContainer{ $message = "death.attack.generic"; diff --git a/src/pocketmine/event/player/PlayerDropItemEvent.php b/src/pocketmine/event/player/PlayerDropItemEvent.php index 5a16af15e6..787528146a 100644 --- a/src/pocketmine/event/player/PlayerDropItemEvent.php +++ b/src/pocketmine/event/player/PlayerDropItemEvent.php @@ -34,18 +34,11 @@ class PlayerDropItemEvent extends PlayerEvent implements Cancellable{ /** @var Item */ private $drop; - /** - * @param Player $player - * @param Item $drop - */ public function __construct(Player $player, Item $drop){ $this->player = $player; $this->drop = $drop; } - /** - * @return Item - */ public function getItem() : Item{ return $this->drop; } diff --git a/src/pocketmine/event/player/PlayerEditBookEvent.php b/src/pocketmine/event/player/PlayerEditBookEvent.php index c0b7c6ad30..c6c29bf391 100644 --- a/src/pocketmine/event/player/PlayerEditBookEvent.php +++ b/src/pocketmine/event/player/PlayerEditBookEvent.php @@ -43,6 +43,9 @@ class PlayerEditBookEvent extends PlayerEvent implements Cancellable{ /** @var int[] */ private $modifiedPages; + /** + * @param int[] $modifiedPages + */ public function __construct(Player $player, WritableBook $oldBook, WritableBook $newBook, int $action, array $modifiedPages){ $this->player = $player; $this->oldBook = $oldBook; @@ -53,8 +56,6 @@ class PlayerEditBookEvent extends PlayerEvent implements Cancellable{ /** * Returns the action of the event. - * - * @return int */ public function getAction() : int{ return $this->action; @@ -62,8 +63,6 @@ class PlayerEditBookEvent extends PlayerEvent implements Cancellable{ /** * Returns the book before it was modified. - * - * @return WritableBook */ public function getOldBook() : WritableBook{ return $this->oldBook; @@ -72,8 +71,6 @@ class PlayerEditBookEvent extends PlayerEvent implements Cancellable{ /** * Returns the book after it was modified. * The new book may be a written book, if the book was signed. - * - * @return WritableBook */ public function getNewBook() : WritableBook{ return $this->newBook; @@ -81,8 +78,6 @@ class PlayerEditBookEvent extends PlayerEvent implements Cancellable{ /** * Sets the new book as the given instance. - * - * @param WritableBook $book */ public function setNewBook(WritableBook $book) : void{ $this->newBook = $book; diff --git a/src/pocketmine/event/player/PlayerExhaustEvent.php b/src/pocketmine/event/player/PlayerExhaustEvent.php index 1e765bdbb9..6a9d5b8cce 100644 --- a/src/pocketmine/event/player/PlayerExhaustEvent.php +++ b/src/pocketmine/event/player/PlayerExhaustEvent.php @@ -72,7 +72,6 @@ class PlayerExhaustEvent extends EntityEvent implements Cancellable{ /** * Returns an int cause of the exhaustion - one of the constants at the top of this class. - * @return int */ public function getCause() : int{ return $this->cause; diff --git a/src/pocketmine/event/player/PlayerExperienceChangeEvent.php b/src/pocketmine/event/player/PlayerExperienceChangeEvent.php index dc72f43714..1bab52257b 100644 --- a/src/pocketmine/event/player/PlayerExperienceChangeEvent.php +++ b/src/pocketmine/event/player/PlayerExperienceChangeEvent.php @@ -51,16 +51,10 @@ class PlayerExperienceChangeEvent extends EntityEvent implements Cancellable{ $this->newProgress = $newProgress; } - /** - * @return int - */ public function getOldLevel() : int{ return $this->oldLevel; } - /** - * @return float - */ public function getOldProgress() : float{ return $this->oldProgress; } @@ -79,16 +73,10 @@ class PlayerExperienceChangeEvent extends EntityEvent implements Cancellable{ return $this->newProgress; } - /** - * @param int|null $newLevel - */ public function setNewLevel(?int $newLevel) : void{ $this->newLevel = $newLevel; } - /** - * @param float|null $newProgress - */ public function setNewProgress(?float $newProgress) : void{ $this->newProgress = $newProgress; } diff --git a/src/pocketmine/event/player/PlayerInteractEvent.php b/src/pocketmine/event/player/PlayerInteractEvent.php index 76acefc151..d8696bbff8 100644 --- a/src/pocketmine/event/player/PlayerInteractEvent.php +++ b/src/pocketmine/event/player/PlayerInteractEvent.php @@ -57,14 +57,6 @@ class PlayerInteractEvent extends PlayerEvent implements Cancellable{ /** @var int */ protected $action; - /** - * @param Player $player - * @param Item $item - * @param Block|null $block - * @param Vector3|null $touchVector - * @param int $face - * @param int $action - */ public function __construct(Player $player, Item $item, ?Block $block, ?Vector3 $touchVector, int $face, int $action = PlayerInteractEvent::RIGHT_CLICK_BLOCK){ assert($block !== null or $touchVector !== null); $this->player = $player; @@ -75,37 +67,22 @@ class PlayerInteractEvent extends PlayerEvent implements Cancellable{ $this->action = $action; } - /** - * @return int - */ public function getAction() : int{ return $this->action; } - /** - * @return Item - */ public function getItem() : Item{ return $this->item; } - /** - * @return Block - */ public function getBlock() : Block{ return $this->blockTouched; } - /** - * @return Vector3 - */ public function getTouchVector() : Vector3{ return $this->touchVector; } - /** - * @return int - */ public function getFace() : int{ return $this->blockFace; } diff --git a/src/pocketmine/event/player/PlayerItemConsumeEvent.php b/src/pocketmine/event/player/PlayerItemConsumeEvent.php index 54a4eecae9..278ec4c33c 100644 --- a/src/pocketmine/event/player/PlayerItemConsumeEvent.php +++ b/src/pocketmine/event/player/PlayerItemConsumeEvent.php @@ -34,18 +34,11 @@ class PlayerItemConsumeEvent extends PlayerEvent implements Cancellable{ /** @var Item */ private $item; - /** - * @param Player $player - * @param Item $item - */ public function __construct(Player $player, Item $item){ $this->player = $player; $this->item = $item; } - /** - * @return Item - */ public function getItem() : Item{ return clone $this->item; } diff --git a/src/pocketmine/event/player/PlayerItemHeldEvent.php b/src/pocketmine/event/player/PlayerItemHeldEvent.php index 9b56f1cbd4..1e1f36535e 100644 --- a/src/pocketmine/event/player/PlayerItemHeldEvent.php +++ b/src/pocketmine/event/player/PlayerItemHeldEvent.php @@ -46,8 +46,6 @@ class PlayerItemHeldEvent extends PlayerEvent implements Cancellable{ * event will result in the **old** slot being changed, not this one. * * To change the item in the slot that the player is attempting to hold, set the slot that this function reports. - * - * @return int */ public function getSlot() : int{ return $this->hotbarSlot; @@ -55,8 +53,6 @@ class PlayerItemHeldEvent extends PlayerEvent implements Cancellable{ /** * Returns the item in the slot that the player is trying to equip. - * - * @return Item */ public function getItem() : Item{ return $this->item; diff --git a/src/pocketmine/event/player/PlayerJoinEvent.php b/src/pocketmine/event/player/PlayerJoinEvent.php index 36609ec820..b05a2858a1 100644 --- a/src/pocketmine/event/player/PlayerJoinEvent.php +++ b/src/pocketmine/event/player/PlayerJoinEvent.php @@ -40,7 +40,6 @@ class PlayerJoinEvent extends PlayerEvent{ /** * PlayerJoinEvent constructor. * - * @param Player $player * @param TextContainer|string $joinMessage */ public function __construct(Player $player, $joinMessage){ diff --git a/src/pocketmine/event/player/PlayerJumpEvent.php b/src/pocketmine/event/player/PlayerJumpEvent.php index 85d8b3a4d5..30c82e5255 100644 --- a/src/pocketmine/event/player/PlayerJumpEvent.php +++ b/src/pocketmine/event/player/PlayerJumpEvent.php @@ -32,8 +32,6 @@ class PlayerJumpEvent extends PlayerEvent{ /** * PlayerJumpEvent constructor. - * - * @param Player $player */ public function __construct(Player $player){ $this->player = $player; diff --git a/src/pocketmine/event/player/PlayerKickEvent.php b/src/pocketmine/event/player/PlayerKickEvent.php index d696825c89..4fc5e736fd 100644 --- a/src/pocketmine/event/player/PlayerKickEvent.php +++ b/src/pocketmine/event/player/PlayerKickEvent.php @@ -40,8 +40,6 @@ class PlayerKickEvent extends PlayerEvent implements Cancellable{ /** * PlayerKickEvent constructor. * - * @param Player $player - * @param string $reason * @param TextContainer|string $quitMessage */ public function __construct(Player $player, string $reason, $quitMessage){ @@ -50,9 +48,6 @@ class PlayerKickEvent extends PlayerEvent implements Cancellable{ $this->reason = $reason; } - /** - * @param string $reason - */ public function setReason(string $reason) : void{ $this->reason = $reason; } diff --git a/src/pocketmine/event/player/PlayerLoginEvent.php b/src/pocketmine/event/player/PlayerLoginEvent.php index 5afbaa061b..0eb24f62a5 100644 --- a/src/pocketmine/event/player/PlayerLoginEvent.php +++ b/src/pocketmine/event/player/PlayerLoginEvent.php @@ -35,25 +35,15 @@ class PlayerLoginEvent extends PlayerEvent implements Cancellable{ /** @var string */ protected $kickMessage; - /** - * @param Player $player - * @param string $kickMessage - */ public function __construct(Player $player, string $kickMessage){ $this->player = $player; $this->kickMessage = $kickMessage; } - /** - * @param string $kickMessage - */ public function setKickMessage(string $kickMessage) : void{ $this->kickMessage = $kickMessage; } - /** - * @return string - */ public function getKickMessage() : string{ return $this->kickMessage; } diff --git a/src/pocketmine/event/player/PlayerMoveEvent.php b/src/pocketmine/event/player/PlayerMoveEvent.php index 0725faf62c..961cb7086a 100644 --- a/src/pocketmine/event/player/PlayerMoveEvent.php +++ b/src/pocketmine/event/player/PlayerMoveEvent.php @@ -33,34 +33,20 @@ class PlayerMoveEvent extends PlayerEvent implements Cancellable{ /** @var Location */ private $to; - /** - * @param Player $player - * @param Location $from - * @param Location $to - */ public function __construct(Player $player, Location $from, Location $to){ $this->player = $player; $this->from = $from; $this->to = $to; } - /** - * @return Location - */ public function getFrom() : Location{ return $this->from; } - /** - * @return Location - */ public function getTo() : Location{ return $this->to; } - /** - * @param Location $to - */ public function setTo(Location $to) : void{ $this->to = $to; } diff --git a/src/pocketmine/event/player/PlayerPreLoginEvent.php b/src/pocketmine/event/player/PlayerPreLoginEvent.php index 6ad2ce22fc..4d9cc4ae97 100644 --- a/src/pocketmine/event/player/PlayerPreLoginEvent.php +++ b/src/pocketmine/event/player/PlayerPreLoginEvent.php @@ -43,25 +43,15 @@ class PlayerPreLoginEvent extends PlayerEvent implements Cancellable{ /** @var string */ protected $kickMessage; - /** - * @param Player $player - * @param string $kickMessage - */ public function __construct(Player $player, string $kickMessage){ $this->player = $player; $this->kickMessage = $kickMessage; } - /** - * @param string $kickMessage - */ public function setKickMessage(string $kickMessage) : void{ $this->kickMessage = $kickMessage; } - /** - * @return string - */ public function getKickMessage() : string{ return $this->kickMessage; } diff --git a/src/pocketmine/event/player/PlayerQuitEvent.php b/src/pocketmine/event/player/PlayerQuitEvent.php index 24460db301..de8608dd05 100644 --- a/src/pocketmine/event/player/PlayerQuitEvent.php +++ b/src/pocketmine/event/player/PlayerQuitEvent.php @@ -37,9 +37,7 @@ class PlayerQuitEvent extends PlayerEvent{ protected $quitReason; /** - * @param Player $player * @param TranslationContainer|string $quitMessage - * @param string $quitReason */ public function __construct(Player $player, $quitMessage, string $quitReason){ $this->player = $player; @@ -61,9 +59,6 @@ class PlayerQuitEvent extends PlayerEvent{ return $this->quitMessage; } - /** - * @return string - */ public function getQuitReason() : string{ return $this->quitReason; } diff --git a/src/pocketmine/event/player/PlayerRespawnEvent.php b/src/pocketmine/event/player/PlayerRespawnEvent.php index 9a9380f2fc..bbf3cf2201 100644 --- a/src/pocketmine/event/player/PlayerRespawnEvent.php +++ b/src/pocketmine/event/player/PlayerRespawnEvent.php @@ -33,25 +33,15 @@ class PlayerRespawnEvent extends PlayerEvent{ /** @var Position */ protected $position; - /** - * @param Player $player - * @param Position $position - */ public function __construct(Player $player, Position $position){ $this->player = $player; $this->position = $position; } - /** - * @return Position - */ public function getRespawnPosition() : Position{ return $this->position; } - /** - * @param Position $position - */ public function setRespawnPosition(Position $position) : void{ $this->position = $position; } diff --git a/src/pocketmine/event/player/PlayerToggleFlightEvent.php b/src/pocketmine/event/player/PlayerToggleFlightEvent.php index de0511e9dc..8c3b292c4f 100644 --- a/src/pocketmine/event/player/PlayerToggleFlightEvent.php +++ b/src/pocketmine/event/player/PlayerToggleFlightEvent.php @@ -30,18 +30,11 @@ class PlayerToggleFlightEvent extends PlayerEvent implements Cancellable{ /** @var bool */ protected $isFlying; - /** - * @param Player $player - * @param bool $isFlying - */ public function __construct(Player $player, bool $isFlying){ $this->player = $player; $this->isFlying = $isFlying; } - /** - * @return bool - */ public function isFlying() : bool{ return $this->isFlying; } diff --git a/src/pocketmine/event/player/PlayerToggleSneakEvent.php b/src/pocketmine/event/player/PlayerToggleSneakEvent.php index 902f5b9c61..d86d775738 100644 --- a/src/pocketmine/event/player/PlayerToggleSneakEvent.php +++ b/src/pocketmine/event/player/PlayerToggleSneakEvent.php @@ -30,18 +30,11 @@ class PlayerToggleSneakEvent extends PlayerEvent implements Cancellable{ /** @var bool */ protected $isSneaking; - /** - * @param Player $player - * @param bool $isSneaking - */ public function __construct(Player $player, bool $isSneaking){ $this->player = $player; $this->isSneaking = $isSneaking; } - /** - * @return bool - */ public function isSneaking() : bool{ return $this->isSneaking; } diff --git a/src/pocketmine/event/player/PlayerToggleSprintEvent.php b/src/pocketmine/event/player/PlayerToggleSprintEvent.php index 96f8c1c0a8..5eeacadd9c 100644 --- a/src/pocketmine/event/player/PlayerToggleSprintEvent.php +++ b/src/pocketmine/event/player/PlayerToggleSprintEvent.php @@ -30,18 +30,11 @@ class PlayerToggleSprintEvent extends PlayerEvent implements Cancellable{ /** @var bool */ protected $isSprinting; - /** - * @param Player $player - * @param bool $isSprinting - */ public function __construct(Player $player, bool $isSprinting){ $this->player = $player; $this->isSprinting = $isSprinting; } - /** - * @return bool - */ public function isSprinting() : bool{ return $this->isSprinting; } diff --git a/src/pocketmine/event/player/PlayerTransferEvent.php b/src/pocketmine/event/player/PlayerTransferEvent.php index 146e08b718..d868aa50de 100644 --- a/src/pocketmine/event/player/PlayerTransferEvent.php +++ b/src/pocketmine/event/player/PlayerTransferEvent.php @@ -34,12 +34,6 @@ class PlayerTransferEvent extends PlayerEvent implements Cancellable{ /** @var string */ protected $message; - /** - * @param Player $player - * @param string $address - * @param int $port - * @param string $message - */ public function __construct(Player $player, string $address, int $port, string $message){ $this->player = $player; $this->address = $address; @@ -47,44 +41,26 @@ class PlayerTransferEvent extends PlayerEvent implements Cancellable{ $this->message = $message; } - /** - * @return string - */ public function getAddress() : string{ return $this->address; } - /** - * @param string $address - */ public function setAddress(string $address) : void{ $this->address = $address; } - /** - * @return int - */ public function getPort() : int{ return $this->port; } - /** - * @param int $port - */ public function setPort(int $port) : void{ $this->port = $port; } - /** - * @return string - */ public function getMessage() : string{ return $this->message; } - /** - * @param string $message - */ public function setMessage(string $message) : void{ $this->message = $message; } diff --git a/src/pocketmine/event/player/cheat/PlayerIllegalMoveEvent.php b/src/pocketmine/event/player/cheat/PlayerIllegalMoveEvent.php index 5beae2a4ab..c46e91a410 100644 --- a/src/pocketmine/event/player/cheat/PlayerIllegalMoveEvent.php +++ b/src/pocketmine/event/player/cheat/PlayerIllegalMoveEvent.php @@ -21,7 +21,6 @@ declare(strict_types=1); - namespace pocketmine\event\player\cheat; use pocketmine\event\Cancellable; @@ -40,11 +39,6 @@ class PlayerIllegalMoveEvent extends PlayerCheatEvent implements Cancellable{ /** @var Vector3 */ private $expectedPosition; - /** - * @param Player $player - * @param Vector3 $attemptedPosition - * @param Vector3 $originalPosition - */ public function __construct(Player $player, Vector3 $attemptedPosition, Vector3 $originalPosition){ $this->player = $player; $this->attemptedPosition = $attemptedPosition; @@ -54,22 +48,15 @@ class PlayerIllegalMoveEvent extends PlayerCheatEvent implements Cancellable{ /** * Returns the position the player attempted to move to. - * @return Vector3 */ public function getAttemptedPosition() : Vector3{ return $this->attemptedPosition; } - /** - * @return Vector3 - */ public function getOriginalPosition() : Vector3{ return $this->originalPosition; } - /** - * @return Vector3 - */ public function getExpectedPosition() : Vector3{ return $this->expectedPosition; } diff --git a/src/pocketmine/event/plugin/PluginDisableEvent.php b/src/pocketmine/event/plugin/PluginDisableEvent.php index e551f7f3ac..6f847b7a44 100644 --- a/src/pocketmine/event/plugin/PluginDisableEvent.php +++ b/src/pocketmine/event/plugin/PluginDisableEvent.php @@ -21,7 +21,6 @@ declare(strict_types=1); - namespace pocketmine\event\plugin; class PluginDisableEvent extends PluginEvent{ diff --git a/src/pocketmine/event/plugin/PluginEnableEvent.php b/src/pocketmine/event/plugin/PluginEnableEvent.php index f00dd249e7..7496be1f35 100644 --- a/src/pocketmine/event/plugin/PluginEnableEvent.php +++ b/src/pocketmine/event/plugin/PluginEnableEvent.php @@ -21,7 +21,6 @@ declare(strict_types=1); - namespace pocketmine\event\plugin; class PluginEnableEvent extends PluginEvent{ diff --git a/src/pocketmine/event/plugin/PluginEvent.php b/src/pocketmine/event/plugin/PluginEvent.php index 2263d78f5f..82faa06380 100644 --- a/src/pocketmine/event/plugin/PluginEvent.php +++ b/src/pocketmine/event/plugin/PluginEvent.php @@ -37,9 +37,6 @@ abstract class PluginEvent extends Event{ $this->plugin = $plugin; } - /** - * @return Plugin - */ public function getPlugin() : Plugin{ return $this->plugin; } diff --git a/src/pocketmine/event/server/CommandEvent.php b/src/pocketmine/event/server/CommandEvent.php index d5dd422a3e..aaecf75f38 100644 --- a/src/pocketmine/event/server/CommandEvent.php +++ b/src/pocketmine/event/server/CommandEvent.php @@ -41,32 +41,19 @@ class CommandEvent extends ServerEvent implements Cancellable{ /** @var CommandSender */ protected $sender; - /** - * @param CommandSender $sender - * @param string $command - */ public function __construct(CommandSender $sender, string $command){ $this->sender = $sender; $this->command = $command; } - /** - * @return CommandSender - */ public function getSender() : CommandSender{ return $this->sender; } - /** - * @return string - */ public function getCommand() : string{ return $this->command; } - /** - * @param string $command - */ public function setCommand(string $command) : void{ $this->command = $command; } diff --git a/src/pocketmine/event/server/DataPacketReceiveEvent.php b/src/pocketmine/event/server/DataPacketReceiveEvent.php index 1766c0d7f4..7ae6e2a84e 100644 --- a/src/pocketmine/event/server/DataPacketReceiveEvent.php +++ b/src/pocketmine/event/server/DataPacketReceiveEvent.php @@ -33,25 +33,15 @@ class DataPacketReceiveEvent extends ServerEvent implements Cancellable{ /** @var Player */ private $player; - /** - * @param Player $player - * @param DataPacket $packet - */ public function __construct(Player $player, DataPacket $packet){ $this->packet = $packet; $this->player = $player; } - /** - * @return DataPacket - */ public function getPacket() : DataPacket{ return $this->packet; } - /** - * @return Player - */ public function getPlayer() : Player{ return $this->player; } diff --git a/src/pocketmine/event/server/DataPacketSendEvent.php b/src/pocketmine/event/server/DataPacketSendEvent.php index fbbef6362f..9ec1a4822b 100644 --- a/src/pocketmine/event/server/DataPacketSendEvent.php +++ b/src/pocketmine/event/server/DataPacketSendEvent.php @@ -33,25 +33,15 @@ class DataPacketSendEvent extends ServerEvent implements Cancellable{ /** @var Player */ private $player; - /** - * @param Player $player - * @param DataPacket $packet - */ public function __construct(Player $player, DataPacket $packet){ $this->packet = $packet; $this->player = $player; } - /** - * @return DataPacket - */ public function getPacket() : DataPacket{ return $this->packet; } - /** - * @return Player - */ public function getPlayer() : Player{ return $this->player; } diff --git a/src/pocketmine/event/server/LowMemoryEvent.php b/src/pocketmine/event/server/LowMemoryEvent.php index aaaaded625..46f0c8022c 100644 --- a/src/pocketmine/event/server/LowMemoryEvent.php +++ b/src/pocketmine/event/server/LowMemoryEvent.php @@ -25,7 +25,6 @@ namespace pocketmine\event\server; use pocketmine\utils\Process; - /** * Called when the server is in a low-memory state as defined by the properties * Plugins should free caches or other non-essential data. @@ -49,8 +48,6 @@ class LowMemoryEvent extends ServerEvent{ /** * Returns the memory usage at the time of the event call (in bytes) - * - * @return int */ public function getMemory() : int{ return $this->memory; @@ -58,8 +55,6 @@ class LowMemoryEvent extends ServerEvent{ /** * Returns the memory limit defined (in bytes) - * - * @return int */ public function getMemoryLimit() : int{ return $this->memoryLimit; @@ -67,24 +62,17 @@ class LowMemoryEvent extends ServerEvent{ /** * Returns the times this event has been called in the current low-memory state - * - * @return int */ public function getTriggerCount() : int{ return $this->triggerCount; } - /** - * @return bool - */ public function isGlobal() : bool{ return $this->global; } /** * Amount of memory already freed - * - * @return int */ public function getMemoryFreed() : int{ return $this->getMemory() - ($this->isGlobal() ? Process::getMemoryUsage(true)[1] : Process::getMemoryUsage(true)[0]); diff --git a/src/pocketmine/event/server/NetworkInterfaceCrashEvent.php b/src/pocketmine/event/server/NetworkInterfaceCrashEvent.php index f9c796afa5..6f54a5a44c 100644 --- a/src/pocketmine/event/server/NetworkInterfaceCrashEvent.php +++ b/src/pocketmine/event/server/NetworkInterfaceCrashEvent.php @@ -30,9 +30,7 @@ use pocketmine\network\SourceInterface; * @deprecated */ class NetworkInterfaceCrashEvent extends NetworkInterfaceEvent{ - /** - * @var \Throwable - */ + /** @var \Throwable */ private $exception; public function __construct(SourceInterface $interface, \Throwable $throwable){ @@ -40,9 +38,6 @@ class NetworkInterfaceCrashEvent extends NetworkInterfaceEvent{ $this->exception = $throwable; } - /** - * @return \Throwable - */ public function getCrashInformation() : \Throwable{ return $this->exception; } diff --git a/src/pocketmine/event/server/NetworkInterfaceEvent.php b/src/pocketmine/event/server/NetworkInterfaceEvent.php index 6269394c0f..720f1404ef 100644 --- a/src/pocketmine/event/server/NetworkInterfaceEvent.php +++ b/src/pocketmine/event/server/NetworkInterfaceEvent.php @@ -29,16 +29,10 @@ class NetworkInterfaceEvent extends ServerEvent{ /** @var SourceInterface */ protected $interface; - /** - * @param SourceInterface $interface - */ public function __construct(SourceInterface $interface){ $this->interface = $interface; } - /** - * @return SourceInterface - */ public function getInterface() : SourceInterface{ return $this->interface; } diff --git a/src/pocketmine/event/server/QueryRegenerateEvent.php b/src/pocketmine/event/server/QueryRegenerateEvent.php index 811622af07..fb6693a473 100644 --- a/src/pocketmine/event/server/QueryRegenerateEvent.php +++ b/src/pocketmine/event/server/QueryRegenerateEvent.php @@ -63,7 +63,10 @@ class QueryRegenerateEvent extends ServerEvent{ /** @var string */ private $ip; - /** @var array */ + /** + * @var string[] + * @phpstan-var array + */ private $extraData = []; /** @var string|null */ @@ -71,10 +74,6 @@ class QueryRegenerateEvent extends ServerEvent{ /** @var string|null */ private $shortQueryCache = null; - - /** - * @param Server $server - */ public function __construct(Server $server){ $this->serverName = $server->getMotd(); $this->listPlugins = $server->getProperty("settings.query-plugins", true); @@ -100,8 +99,6 @@ class QueryRegenerateEvent extends ServerEvent{ /** * @deprecated - * - * @return int */ public function getTimeout() : int{ return 0; @@ -109,7 +106,6 @@ class QueryRegenerateEvent extends ServerEvent{ /** * @deprecated - * @param int $timeout */ public function setTimeout(int $timeout) : void{ @@ -120,31 +116,19 @@ class QueryRegenerateEvent extends ServerEvent{ $this->shortQueryCache = null; } - /** - * @return string - */ public function getServerName() : string{ return $this->serverName; } - /** - * @param string $serverName - */ public function setServerName(string $serverName) : void{ $this->serverName = $serverName; $this->destroyCache(); } - /** - * @return bool - */ public function canListPlugins() : bool{ return $this->listPlugins; } - /** - * @param bool $value - */ public function setListPlugins(bool $value) : void{ $this->listPlugins = $value; $this->destroyCache(); @@ -180,46 +164,28 @@ class QueryRegenerateEvent extends ServerEvent{ $this->destroyCache(); } - /** - * @return int - */ public function getPlayerCount() : int{ return $this->numPlayers; } - /** - * @param int $count - */ public function setPlayerCount(int $count) : void{ $this->numPlayers = $count; $this->destroyCache(); } - /** - * @return int - */ public function getMaxPlayerCount() : int{ return $this->maxPlayers; } - /** - * @param int $count - */ public function setMaxPlayerCount(int $count) : void{ $this->maxPlayers = $count; $this->destroyCache(); } - /** - * @return string - */ public function getWorld() : string{ return $this->map; } - /** - * @param string $world - */ public function setWorld(string $world) : void{ $this->map = $world; $this->destroyCache(); @@ -228,23 +194,22 @@ class QueryRegenerateEvent extends ServerEvent{ /** * Returns the extra Query data in key => value form * - * @return array + * @return string[] + * @phpstan-return array */ public function getExtraData() : array{ return $this->extraData; } /** - * @param array $extraData + * @param string[] $extraData + * @phpstan-param array $extraData */ public function setExtraData(array $extraData) : void{ $this->extraData = $extraData; $this->destroyCache(); } - /** - * @return string - */ public function getLongQuery() : string{ if($this->longQueryCache !== null){ return $this->longQueryCache; @@ -294,9 +259,6 @@ class QueryRegenerateEvent extends ServerEvent{ return $this->longQueryCache = $query; } - /** - * @return string - */ public function getShortQuery() : string{ return $this->shortQueryCache ?? ($this->shortQueryCache = $this->serverName . "\x00" . $this->gametype . "\x00" . $this->map . "\x00" . $this->numPlayers . "\x00" . $this->maxPlayers . "\x00" . Binary::writeLShort($this->port) . $this->ip . "\x00"); } diff --git a/src/pocketmine/event/server/RemoteServerCommandEvent.php b/src/pocketmine/event/server/RemoteServerCommandEvent.php index 9b1039104c..f73c1d46ef 100644 --- a/src/pocketmine/event/server/RemoteServerCommandEvent.php +++ b/src/pocketmine/event/server/RemoteServerCommandEvent.php @@ -32,10 +32,6 @@ use pocketmine\command\CommandSender; */ class RemoteServerCommandEvent extends ServerCommandEvent{ - /** - * @param CommandSender $sender - * @param string $command - */ public function __construct(CommandSender $sender, string $command){ parent::__construct($sender, $command); } diff --git a/src/pocketmine/event/server/ServerCommandEvent.php b/src/pocketmine/event/server/ServerCommandEvent.php index 803ce1f625..9e0767036b 100644 --- a/src/pocketmine/event/server/ServerCommandEvent.php +++ b/src/pocketmine/event/server/ServerCommandEvent.php @@ -43,32 +43,19 @@ class ServerCommandEvent extends ServerEvent implements Cancellable{ /** @var CommandSender */ protected $sender; - /** - * @param CommandSender $sender - * @param string $command - */ public function __construct(CommandSender $sender, string $command){ $this->sender = $sender; $this->command = $command; } - /** - * @return CommandSender - */ public function getSender() : CommandSender{ return $this->sender; } - /** - * @return string - */ public function getCommand() : string{ return $this->command; } - /** - * @param string $command - */ public function setCommand(string $command) : void{ $this->command = $command; } diff --git a/src/pocketmine/form/Form.php b/src/pocketmine/form/Form.php index e4a2fcc5ad..80004c25ef 100644 --- a/src/pocketmine/form/Form.php +++ b/src/pocketmine/form/Form.php @@ -34,7 +34,6 @@ interface Form extends \JsonSerializable{ /** * Handles a form response from a player. * - * @param Player $player * @param mixed $data * * @throws FormValidationException if the data could not be processed diff --git a/src/pocketmine/inventory/BaseInventory.php b/src/pocketmine/inventory/BaseInventory.php index cf2b7c0f7c..f4c7f80ac9 100644 --- a/src/pocketmine/inventory/BaseInventory.php +++ b/src/pocketmine/inventory/BaseInventory.php @@ -46,7 +46,10 @@ abstract class BaseInventory implements Inventory{ protected $name; /** @var string */ protected $title; - /** @var \SplFixedArray|(Item|null)[] */ + /** + * @var \SplFixedArray|(Item|null)[] + * @phpstan-var \SplFixedArray + */ protected $slots; /** @var Player[] */ protected $viewers = []; @@ -55,8 +58,6 @@ abstract class BaseInventory implements Inventory{ /** * @param Item[] $items - * @param int $size - * @param string $title */ public function __construct(array $items = [], int $size = null, string $title = null){ $this->slots = new \SplFixedArray($size ?? $this->getDefaultSize()); @@ -73,7 +74,6 @@ abstract class BaseInventory implements Inventory{ /** * Returns the size of the inventory. - * @return int */ public function getSize() : int{ return $this->slots->getSize(); @@ -83,7 +83,7 @@ abstract class BaseInventory implements Inventory{ * Sets the new size of the inventory. * WARNING: If the size is smaller, any items past the new size will be lost. * - * @param int $size + * @return void */ public function setSize(int $size){ $this->slots->setSize($size); @@ -100,8 +100,6 @@ abstract class BaseInventory implements Inventory{ } /** - * @param bool $includeEmpty - * * @return Item[] */ public function getContents(bool $includeEmpty = false) : array{ @@ -121,7 +119,6 @@ abstract class BaseInventory implements Inventory{ /** * @param Item[] $items - * @param bool $send */ public function setContents(array $items, bool $send = true) : void{ if(count($items) > $this->getSize()){ @@ -148,9 +145,6 @@ abstract class BaseInventory implements Inventory{ /** * Drops the contents of the inventory into the specified Level at the specified position and clears the inventory * contents. - * - * @param Level $level - * @param Vector3 $position */ public function dropContents(Level $level, Vector3 $position) : void{ foreach($this->getContents() as $item){ @@ -437,7 +431,6 @@ abstract class BaseInventory implements Inventory{ } } - /** * @param Player|Player[] $target */ @@ -460,7 +453,6 @@ abstract class BaseInventory implements Inventory{ } /** - * @param int $index * @param Player|Player[] $target */ public function sendSlot(int $index, $target) : void{ diff --git a/src/pocketmine/inventory/ChestInventory.php b/src/pocketmine/inventory/ChestInventory.php index feb079d5f1..b7cd3765e1 100644 --- a/src/pocketmine/inventory/ChestInventory.php +++ b/src/pocketmine/inventory/ChestInventory.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace pocketmine\inventory; +use pocketmine\level\Position; use pocketmine\network\mcpe\protocol\BlockEventPacket; use pocketmine\network\mcpe\protocol\LevelSoundEventPacket; use pocketmine\network\mcpe\protocol\types\WindowTypes; @@ -35,9 +36,6 @@ class ChestInventory extends ContainerInventory{ /** @var Chest */ protected $holder; - /** - * @param Chest $tile - */ public function __construct(Chest $tile){ parent::__construct($tile); } @@ -56,7 +54,7 @@ class ChestInventory extends ContainerInventory{ /** * This override is here for documentation and code completion purposes only. - * @return Chest + * @return Chest|Position */ public function getHolder(){ return $this->holder; diff --git a/src/pocketmine/inventory/ContainerInventory.php b/src/pocketmine/inventory/ContainerInventory.php index 1a2c4c4eae..747c4c3790 100644 --- a/src/pocketmine/inventory/ContainerInventory.php +++ b/src/pocketmine/inventory/ContainerInventory.php @@ -50,7 +50,7 @@ abstract class ContainerInventory extends BaseInventory{ if($holder instanceof Entity){ $pk->entityUniqueId = $holder->getId(); - }elseif($holder instanceof Vector3){ + }else{ $pk->x = $holder->getFloorX(); $pk->y = $holder->getFloorY(); $pk->z = $holder->getFloorZ(); @@ -70,7 +70,6 @@ abstract class ContainerInventory extends BaseInventory{ /** * Returns the Minecraft PE inventory type used to show the inventory window to clients. - * @return int */ abstract public function getNetworkType() : int; diff --git a/src/pocketmine/inventory/CraftingGrid.php b/src/pocketmine/inventory/CraftingGrid.php index 4beb9ed71a..5b9f7e52fd 100644 --- a/src/pocketmine/inventory/CraftingGrid.php +++ b/src/pocketmine/inventory/CraftingGrid.php @@ -129,11 +129,6 @@ class CraftingGrid extends BaseInventory{ /** * Returns the item at offset x,y, offset by where the starts of the recipe rectangle are. - * - * @param int $x - * @param int $y - * - * @return Item */ public function getIngredient(int $x, int $y) : Item{ if($this->startX !== null and $this->startY !== null){ @@ -145,8 +140,6 @@ class CraftingGrid extends BaseInventory{ /** * Returns the width of the recipe we're trying to craft, based on items currently in the grid. - * - * @return int */ public function getRecipeWidth() : int{ return $this->xLen ?? 0; @@ -154,7 +147,6 @@ class CraftingGrid extends BaseInventory{ /** * Returns the height of the recipe we're trying to craft, based on items currently in the grid. - * @return int */ public function getRecipeHeight() : int{ return $this->yLen ?? 0; diff --git a/src/pocketmine/inventory/CraftingManager.php b/src/pocketmine/inventory/CraftingManager.php index bec35765aa..41e1f2a636 100644 --- a/src/pocketmine/inventory/CraftingManager.php +++ b/src/pocketmine/inventory/CraftingManager.php @@ -128,8 +128,6 @@ class CraftingManager{ /** * Returns a pre-compressed CraftingDataPacket for sending to players. Rebuilds the cache if it is not found. - * - * @return BatchPacket */ public function getCraftingDataPacket() : BatchPacket{ if($this->craftingDataCache === null){ @@ -142,14 +140,11 @@ class CraftingManager{ /** * Function used to arrange Shapeless Recipe ingredient lists into a consistent order. * - * @param Item $i1 - * @param Item $i2 - * * @return int */ public static function sort(Item $i1, Item $i2){ //Use spaceship operator to compare each property, then try the next one if they are equivalent. - ($retval = $i1->getId() <=> $i2->getId()) === 0 && ($retval = $i1->getDamage() <=> $i2->getDamage()) === 0 && ($retval = $i1->getCount() <=> $i2->getCount()); + ($retval = $i1->getId() <=> $i2->getId()) === 0 && ($retval = $i1->getDamage() <=> $i2->getDamage()) === 0 && ($retval = $i1->getCount() <=> $i2->getCount()) === 0; return $retval; } @@ -178,6 +173,9 @@ class CraftingManager{ return $result; } + /** + * @param Item[] $outputs + */ private static function hashOutputs(array $outputs) : string{ $outputs = self::pack($outputs); usort($outputs, [self::class, "sort"]); @@ -210,27 +208,18 @@ class CraftingManager{ return $this->furnaceRecipes; } - /** - * @param ShapedRecipe $recipe - */ public function registerShapedRecipe(ShapedRecipe $recipe) : void{ $this->shapedRecipes[self::hashOutputs($recipe->getResults())][] = $recipe; $this->craftingDataCache = null; } - /** - * @param ShapelessRecipe $recipe - */ public function registerShapelessRecipe(ShapelessRecipe $recipe) : void{ $this->shapelessRecipes[self::hashOutputs($recipe->getResults())][] = $recipe; $this->craftingDataCache = null; } - /** - * @param FurnaceRecipe $recipe - */ public function registerFurnaceRecipe(FurnaceRecipe $recipe) : void{ $input = $recipe->getInput(); $this->furnaceRecipes[$input->getId() . ":" . ($input->hasAnyDamageValue() ? "?" : $input->getDamage())] = $recipe; @@ -238,10 +227,7 @@ class CraftingManager{ } /** - * @param CraftingGrid $grid * @param Item[] $outputs - * - * @return CraftingRecipe|null */ public function matchRecipe(CraftingGrid $grid, array $outputs) : ?CraftingRecipe{ //TODO: try to match special recipes before anything else (first they need to be implemented!) @@ -271,6 +257,7 @@ class CraftingManager{ * @param Item[] $outputs * * @return CraftingRecipe[]|\Generator + * @phpstan-return \Generator */ public function matchRecipeByOutputs(array $outputs) : \Generator{ //TODO: try to match special recipes before anything else (first they need to be implemented!) @@ -290,19 +277,12 @@ class CraftingManager{ } } - /** - * @param Item $input - * - * @return FurnaceRecipe|null - */ public function matchFurnaceRecipe(Item $input) : ?FurnaceRecipe{ return $this->furnaceRecipes[$input->getId() . ":" . $input->getDamage()] ?? $this->furnaceRecipes[$input->getId() . ":?"] ?? null; } /** * @deprecated - * - * @param Recipe $recipe */ public function registerRecipe(Recipe $recipe) : void{ $recipe->registerToCraftingManager($this); diff --git a/src/pocketmine/inventory/CraftingRecipe.php b/src/pocketmine/inventory/CraftingRecipe.php index df37ca6e64..9e8cba8f31 100644 --- a/src/pocketmine/inventory/CraftingRecipe.php +++ b/src/pocketmine/inventory/CraftingRecipe.php @@ -36,18 +36,12 @@ interface CraftingRecipe extends Recipe{ /** * Returns a list of results this recipe will produce when the inputs in the given crafting grid are consumed. * - * @param CraftingGrid $grid - * * @return Item[] */ public function getResultsFor(CraftingGrid $grid) : array; /** * Returns whether the given crafting grid meets the requirements to craft this recipe. - * - * @param CraftingGrid $grid - * - * @return bool */ public function matchesCraftingGrid(CraftingGrid $grid) : bool; } diff --git a/src/pocketmine/inventory/DoubleChestInventory.php b/src/pocketmine/inventory/DoubleChestInventory.php index 45df2d92d1..bf91477dbe 100644 --- a/src/pocketmine/inventory/DoubleChestInventory.php +++ b/src/pocketmine/inventory/DoubleChestInventory.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace pocketmine\inventory; use pocketmine\item\Item; +use pocketmine\level\Position; use pocketmine\Player; use pocketmine\tile\Chest; use function array_merge; @@ -56,7 +57,7 @@ class DoubleChestInventory extends ChestInventory implements InventoryHolder{ } /** - * @return Chest + * @return Chest|Position */ public function getHolder(){ return $this->left->getHolder(); @@ -88,7 +89,6 @@ class DoubleChestInventory extends ChestInventory implements InventoryHolder{ /** * @param Item[] $items - * @param bool $send */ public function setContents(array $items, bool $send = true) : void{ $size = $this->getSize(); @@ -128,20 +128,17 @@ class DoubleChestInventory extends ChestInventory implements InventoryHolder{ parent::onClose($who); } - /** - * @return ChestInventory - */ public function getLeftSide() : ChestInventory{ return $this->left; } - /** - * @return ChestInventory - */ public function getRightSide() : ChestInventory{ return $this->right; } + /** + * @return void + */ public function invalidate(){ $this->left = null; $this->right = null; diff --git a/src/pocketmine/inventory/EnderChestInventory.php b/src/pocketmine/inventory/EnderChestInventory.php index ce0f1e51e0..5203a589e4 100644 --- a/src/pocketmine/inventory/EnderChestInventory.php +++ b/src/pocketmine/inventory/EnderChestInventory.php @@ -52,7 +52,7 @@ class EnderChestInventory extends ChestInventory{ /** * Set the holder's position to that of a tile * - * @param EnderChest $enderChest + * @return void */ public function setHolderPosition(EnderChest $enderChest){ $this->holder->setComponents($enderChest->getFloorX(), $enderChest->getFloorY(), $enderChest->getFloorZ()); diff --git a/src/pocketmine/inventory/FurnaceInventory.php b/src/pocketmine/inventory/FurnaceInventory.php index 00f876b761..761d14514d 100644 --- a/src/pocketmine/inventory/FurnaceInventory.php +++ b/src/pocketmine/inventory/FurnaceInventory.php @@ -55,50 +55,26 @@ class FurnaceInventory extends ContainerInventory{ return $this->holder; } - /** - * @return Item - */ public function getResult() : Item{ return $this->getItem(2); } - /** - * @return Item - */ public function getFuel() : Item{ return $this->getItem(1); } - /** - * @return Item - */ public function getSmelting() : Item{ return $this->getItem(0); } - /** - * @param Item $item - * - * @return bool - */ public function setResult(Item $item) : bool{ return $this->setItem(2, $item); } - /** - * @param Item $item - * - * @return bool - */ public function setFuel(Item $item) : bool{ return $this->setItem(1, $item); } - /** - * @param Item $item - * - * @return bool - */ public function setSmelting(Item $item) : bool{ return $this->setItem(0, $item); } diff --git a/src/pocketmine/inventory/FurnaceRecipe.php b/src/pocketmine/inventory/FurnaceRecipe.php index 8e81fe03f3..5e1175e44e 100644 --- a/src/pocketmine/inventory/FurnaceRecipe.php +++ b/src/pocketmine/inventory/FurnaceRecipe.php @@ -33,32 +33,22 @@ class FurnaceRecipe implements Recipe{ /** @var Item */ private $ingredient; - /** - * @param Item $result - * @param Item $ingredient - */ public function __construct(Item $result, Item $ingredient){ $this->output = clone $result; $this->ingredient = clone $ingredient; } /** - * @param Item $item + * @return void */ public function setInput(Item $item){ $this->ingredient = clone $item; } - /** - * @return Item - */ public function getInput() : Item{ return clone $this->ingredient; } - /** - * @return Item - */ public function getResult() : Item{ return clone $this->output; } diff --git a/src/pocketmine/inventory/Inventory.php b/src/pocketmine/inventory/Inventory.php index 1bf84060f0..0fba616d4e 100644 --- a/src/pocketmine/inventory/Inventory.php +++ b/src/pocketmine/inventory/Inventory.php @@ -34,47 +34,21 @@ use pocketmine\Player; interface Inventory{ public const MAX_STACK = 64; - /** - * @return int - */ public function getSize() : int; - /** - * @return int - */ public function getMaxStackSize() : int; - /** - * @param int $size - */ public function setMaxStackSize(int $size) : void; - /** - * @return string - */ public function getName() : string; - /** - * @return string - */ public function getTitle() : string; - /** - * @param int $index - * - * @return Item - */ public function getItem(int $index) : Item; /** * Puts an Item in a slot. * If a plugin refuses the update or $index is invalid, it'll return false - * - * @param int $index - * @param Item $item - * @param bool $send - * - * @return bool */ public function setItem(int $index, Item $item, bool $send = true) : bool; @@ -92,10 +66,6 @@ interface Inventory{ /** * Checks if a given Item can be added to the inventory - * - * @param Item $item - * - * @return bool */ public function canAddItem(Item $item) : bool; @@ -110,24 +80,18 @@ interface Inventory{ public function removeItem(Item ...$slots) : array; /** - * @param bool $includeEmpty - * * @return Item[] */ public function getContents(bool $includeEmpty = false) : array; /** * @param Item[] $items - * @param bool $send */ public function setContents(array $items, bool $send = true) : void; /** * Drops the contents of the inventory into the specified Level at the specified position and clears the inventory * contents. - * - * @param Level $level - * @param Vector3 $position */ public function dropContents(Level $level, Vector3 $position) : void; @@ -137,7 +101,6 @@ interface Inventory{ public function sendContents($target) : void; /** - * @param int $index * @param Player|Player[] $target */ public function sendSlot(int $index, $target) : void; @@ -145,10 +108,6 @@ interface Inventory{ /** * Checks if the inventory contains any Item with the same material data. * It will check id, amount, and metadata (if not null) - * - * @param Item $item - * - * @return bool */ public function contains(Item $item) : bool; @@ -156,8 +115,6 @@ interface Inventory{ * Will return all the Items that has the same id and metadata (if not null). * Won't check amount * - * @param Item $item - * * @return Item[] */ public function all(Item $item) : array; @@ -167,51 +124,31 @@ interface Inventory{ * and count >= to the count of the specified item stack. * * If $exact is true, only items with equal ID, damage, NBT and count will match. - * - * @param Item $item - * @param bool $exact - * - * @return int */ public function first(Item $item, bool $exact = false) : int; /** * Returns the first empty slot, or -1 if not found - * - * @return int */ public function firstEmpty() : int; /** * Returns whether the given slot is empty. - * - * @param int $index - * - * @return bool */ public function isSlotEmpty(int $index) : bool; /** * Will remove all the Items that has the same id and metadata (if not null) - * - * @param Item $item */ public function remove(Item $item) : void; /** * Will clear a specific slot - * - * @param int $index - * @param bool $send - * - * @return bool */ public function clear(int $index, bool $send = true) : bool; /** * Clears all the slots - * - * @param bool $send */ public function clearAll(bool $send = true) : void; @@ -231,50 +168,25 @@ interface Inventory{ */ public function getViewers() : array; - /** - * @param Player $who - */ public function onOpen(Player $who) : void; /** * Tries to open the inventory to a player - * - * @param Player $who - * - * @return bool */ public function open(Player $who) : bool; public function close(Player $who) : void; - /** - * @param Player $who - */ public function onClose(Player $who) : void; - /** - * @param int $index - * @param Item $before - * @param bool $send - */ public function onSlotChange(int $index, Item $before, bool $send) : void; /** * Returns whether the specified slot exists in the inventory. - * - * @param int $slot - * - * @return bool */ public function slotExists(int $slot) : bool; - /** - * @return null|InventoryEventProcessor - */ public function getEventProcessor() : ?InventoryEventProcessor; - /** - * @param null|InventoryEventProcessor $eventProcessor - */ public function setEventProcessor(?InventoryEventProcessor $eventProcessor) : void; } diff --git a/src/pocketmine/inventory/InventoryEventProcessor.php b/src/pocketmine/inventory/InventoryEventProcessor.php index 0ecafec3c2..da7a650d3c 100644 --- a/src/pocketmine/inventory/InventoryEventProcessor.php +++ b/src/pocketmine/inventory/InventoryEventProcessor.php @@ -37,11 +37,6 @@ interface InventoryEventProcessor{ * Called prior to a slot in the given inventory changing. This is called by inventories that this listener is * attached to. * - * @param Inventory $inventory - * @param int $slot - * @param Item $oldItem - * @param Item $newItem - * * @return Item|null that should be used in place of $newItem, or null if the slot change should not proceed. */ public function onSlotChange(Inventory $inventory, int $slot, Item $oldItem, Item $newItem) : ?Item; diff --git a/src/pocketmine/inventory/MultiRecipe.php b/src/pocketmine/inventory/MultiRecipe.php index d9e6674648..8309c821f9 100644 --- a/src/pocketmine/inventory/MultiRecipe.php +++ b/src/pocketmine/inventory/MultiRecipe.php @@ -39,6 +39,7 @@ class MultiRecipe{ public const TYPE_FIREWORKS = "00000000-0000-0000-0000-000000000002"; public const TYPE_MAP_LOCKING_CARTOGRAPHY = "602234E4-CAC1-4353-8BB7-B1EBFF70024B"; + /** @var UUID */ private $uuid; public function __construct(UUID $uuid){ diff --git a/src/pocketmine/inventory/PlayerInventory.php b/src/pocketmine/inventory/PlayerInventory.php index 6ffca62df3..4fa1ebed72 100644 --- a/src/pocketmine/inventory/PlayerInventory.php +++ b/src/pocketmine/inventory/PlayerInventory.php @@ -41,9 +41,6 @@ class PlayerInventory extends BaseInventory{ /** @var int */ protected $itemInHandIndex = 0; - /** - * @param Human $player - */ public function __construct(Human $player){ $this->holder = $player; parent::__construct(); @@ -93,11 +90,9 @@ class PlayerInventory extends BaseInventory{ } /** - * @param int $slot - * * @throws \InvalidArgumentException */ - private function throwIfNotHotbarSlot(int $slot){ + private function throwIfNotHotbarSlot(int $slot) : void{ if(!$this->isHotbarSlot($slot)){ throw new \InvalidArgumentException("$slot is not a valid hotbar slot index (expected 0 - " . ($this->getHotbarSize() - 1) . ")"); } @@ -106,10 +101,6 @@ class PlayerInventory extends BaseInventory{ /** * Returns the item in the specified hotbar slot. * - * @param int $hotbarSlot - * - * @return Item - * * @throws \InvalidArgumentException if the hotbar slot index is out of range */ public function getHotbarSlotItem(int $hotbarSlot) : Item{ @@ -119,7 +110,6 @@ class PlayerInventory extends BaseInventory{ /** * Returns the hotbar slot number the holder is currently holding. - * @return int */ public function getHeldItemIndex() : int{ return $this->itemInHandIndex; @@ -132,6 +122,7 @@ class PlayerInventory extends BaseInventory{ * @param bool $send Whether to send updates back to the inventory holder. This should usually be true for plugin calls. * It should only be false to prevent feedback loops of equipment packets between client and server. * + * @return void * @throws \InvalidArgumentException if the hotbar slot is out of range */ public function setHeldItemIndex(int $hotbarSlot, bool $send = true){ @@ -148,8 +139,6 @@ class PlayerInventory extends BaseInventory{ /** * Returns the currently-held item. - * - * @return Item */ public function getItemInHand() : Item{ return $this->getHotbarSlotItem($this->itemInHandIndex); @@ -157,10 +146,6 @@ class PlayerInventory extends BaseInventory{ /** * Sets the item in the currently-held slot to the specified item. - * - * @param Item $item - * - * @return bool */ public function setItemInHand(Item $item) : bool{ return $this->setItem($this->getHeldItemIndex(), $item); @@ -170,6 +155,8 @@ class PlayerInventory extends BaseInventory{ * Sends the currently-held item to specified targets. * * @param Player|Player[] $target + * + * @return void */ public function sendHeldItem($target){ $item = $this->getItemInHand(); @@ -195,12 +182,14 @@ class PlayerInventory extends BaseInventory{ /** * Returns the number of slots in the hotbar. - * @return int */ public function getHotbarSize() : int{ return 9; } + /** + * @return void + */ public function sendCreativeContents(){ //TODO: this mess shouldn't be in here $holder = $this->getHolder(); diff --git a/src/pocketmine/inventory/ShapedRecipe.php b/src/pocketmine/inventory/ShapedRecipe.php index 536451017e..beb2930267 100644 --- a/src/pocketmine/inventory/ShapedRecipe.php +++ b/src/pocketmine/inventory/ShapedRecipe.php @@ -110,8 +110,6 @@ class ShapedRecipe implements CraftingRecipe{ } /** - * @param CraftingGrid $grid - * * @return Item[] */ public function getResultsFor(CraftingGrid $grid) : array{ @@ -119,9 +117,6 @@ class ShapedRecipe implements CraftingRecipe{ } /** - * @param string $key - * @param Item $item - * * @return $this * @throws \InvalidArgumentException */ @@ -168,12 +163,6 @@ class ShapedRecipe implements CraftingRecipe{ return $ingredients; } - /** - * @param int $x - * @param int $y - * - * @return Item - */ public function getIngredient(int $x, int $y) : Item{ $exists = $this->ingredientList[$this->shape[$y]{$x}] ?? null; return $exists !== null ? clone $exists : ItemFactory::get(Item::AIR, 0, 0); @@ -196,12 +185,6 @@ class ShapedRecipe implements CraftingRecipe{ $manager->registerShapedRecipe($this); } - /** - * @param CraftingGrid $grid - * @param bool $reverse - * - * @return bool - */ private function matchInputMap(CraftingGrid $grid, bool $reverse) : bool{ for($y = 0; $y < $this->height; ++$y){ for($x = 0; $x < $this->width; ++$x){ @@ -217,11 +200,6 @@ class ShapedRecipe implements CraftingRecipe{ return true; } - /** - * @param CraftingGrid $grid - * - * @return bool - */ public function matchesCraftingGrid(CraftingGrid $grid) : bool{ if($this->width !== $grid->getRecipeWidth() or $this->height !== $grid->getRecipeHeight()){ return false; diff --git a/src/pocketmine/inventory/ShapelessRecipe.php b/src/pocketmine/inventory/ShapelessRecipe.php index 170faab541..aa3e8c38ef 100644 --- a/src/pocketmine/inventory/ShapelessRecipe.php +++ b/src/pocketmine/inventory/ShapelessRecipe.php @@ -46,6 +46,9 @@ class ShapelessRecipe implements CraftingRecipe{ $this->results = array_map(function(Item $item) : Item{ return clone $item; }, $results); } + /** + * @return Item[] + */ public function getResults() : array{ return array_map(function(Item $item) : Item{ return clone $item; }, $this->results); } @@ -55,10 +58,6 @@ class ShapelessRecipe implements CraftingRecipe{ } /** - * @param Item $item - * - * @return ShapelessRecipe - * * @throws \InvalidArgumentException */ public function addIngredient(Item $item) : ShapelessRecipe{ @@ -74,8 +73,6 @@ class ShapelessRecipe implements CraftingRecipe{ } /** - * @param Item $item - * * @return $this */ public function removeIngredient(Item $item){ @@ -99,9 +96,6 @@ class ShapelessRecipe implements CraftingRecipe{ return array_map(function(Item $item) : Item{ return clone $item; }, $this->ingredients); } - /** - * @return int - */ public function getIngredientCount() : int{ $count = 0; foreach($this->ingredients as $ingredient){ @@ -120,11 +114,6 @@ class ShapelessRecipe implements CraftingRecipe{ $manager->registerShapelessRecipe($this); } - /** - * @param CraftingGrid $grid - * - * @return bool - */ public function matchesCraftingGrid(CraftingGrid $grid) : bool{ //don't pack the ingredients - shapeless recipes require that each ingredient be in a separate slot $input = $grid->getContents(); @@ -140,6 +129,6 @@ class ShapelessRecipe implements CraftingRecipe{ return false; //failed to match the needed item to a given item } - return empty($input); //crafting grid should be empty apart from the given ingredient stacks + return count($input) === 0; //crafting grid should be empty apart from the given ingredient stacks } } diff --git a/src/pocketmine/inventory/transaction/CraftingTransaction.php b/src/pocketmine/inventory/transaction/CraftingTransaction.php index 52d5f8c606..8787e32c1b 100644 --- a/src/pocketmine/inventory/transaction/CraftingTransaction.php +++ b/src/pocketmine/inventory/transaction/CraftingTransaction.php @@ -61,21 +61,18 @@ class CraftingTransaction extends InventoryTransaction{ /** * @param Item[] $txItems * @param Item[] $recipeItems - * @param bool $wildcards - * @param int $iterations * - * @return int * @throws TransactionValidationException */ protected function matchRecipeItems(array $txItems, array $recipeItems, bool $wildcards, int $iterations = 0) : int{ - if(empty($recipeItems)){ + if(count($recipeItems) === 0){ throw new TransactionValidationException("No recipe items given"); } - if(empty($txItems)){ + if(count($txItems) === 0){ throw new TransactionValidationException("No transaction items given"); } - while(!empty($recipeItems)){ + while(count($recipeItems) > 0){ /** @var Item $recipeItem */ $recipeItem = array_pop($recipeItems); $needCount = $recipeItem->getCount(); @@ -114,7 +111,7 @@ class CraftingTransaction extends InventoryTransaction{ if($iterations < 1){ throw new TransactionValidationException("Tried to craft zero times"); } - if(!empty($txItems)){ + if(count($txItems) > 0){ //all items should be destroyed in this process throw new TransactionValidationException("Expected 0 ingredients left over, have " . count($txItems)); } diff --git a/src/pocketmine/inventory/transaction/InventoryTransaction.php b/src/pocketmine/inventory/transaction/InventoryTransaction.php index 6f0f7b238f..75a37acedf 100644 --- a/src/pocketmine/inventory/transaction/InventoryTransaction.php +++ b/src/pocketmine/inventory/transaction/InventoryTransaction.php @@ -53,6 +53,7 @@ use function spl_object_hash; * @see InventoryAction */ class InventoryTransaction{ + /** @var bool */ protected $hasExecuted = false; /** @var Player */ protected $source; @@ -64,7 +65,6 @@ class InventoryTransaction{ protected $actions = []; /** - * @param Player $source * @param InventoryAction[] $actions */ public function __construct(Player $source, array $actions = []){ @@ -74,9 +74,6 @@ class InventoryTransaction{ } } - /** - * @return Player - */ public function getSource() : Player{ return $this->source; } @@ -100,9 +97,6 @@ class InventoryTransaction{ return $this->actions; } - /** - * @param InventoryAction $action - */ public function addAction(InventoryAction $action) : void{ if(!isset($this->actions[$hash = spl_object_hash($action)])){ $this->actions[$hash] = $action; @@ -128,8 +122,6 @@ class InventoryTransaction{ /** * @internal This method should not be used by plugins, it's used to add tracked inventories for InventoryActions * involving inventories. - * - * @param Inventory $inventory */ public function addInventory(Inventory $inventory) : void{ if(!isset($this->inventories[$hash = spl_object_hash($inventory)])){ @@ -231,19 +223,16 @@ class InventoryTransaction{ } /** - * @param Item $needOrigin * @param SlotChangeAction[] $possibleActions - * - * @return null|Item */ protected function findResultItem(Item $needOrigin, array $possibleActions) : ?Item{ - assert(!empty($possibleActions)); + assert(count($possibleActions) > 0); foreach($possibleActions as $i => $action){ if($action->getSourceItem()->equalsExact($needOrigin)){ $newList = $possibleActions; unset($newList[$i]); - if(empty($newList)){ + if(count($newList) === 0){ return $action->getTargetItem(); } $result = $this->findResultItem($action->getTargetItem(), $newList); @@ -293,7 +282,6 @@ class InventoryTransaction{ /** * Executes the group of actions, returning whether the transaction executed successfully or not. - * @return bool * * @throws TransactionValidationException */ @@ -332,9 +320,6 @@ class InventoryTransaction{ return true; } - /** - * @return bool - */ public function hasExecuted() : bool{ return $this->hasExecuted; } diff --git a/src/pocketmine/inventory/transaction/action/CreativeInventoryAction.php b/src/pocketmine/inventory/transaction/action/CreativeInventoryAction.php index af861c00f9..91cb1d7a8b 100644 --- a/src/pocketmine/inventory/transaction/action/CreativeInventoryAction.php +++ b/src/pocketmine/inventory/transaction/action/CreativeInventoryAction.php @@ -37,6 +37,7 @@ class CreativeInventoryAction extends InventoryAction{ */ public const TYPE_CREATE_ITEM = 1; + /** @var int */ protected $actionType; public function __construct(Item $sourceItem, Item $targetItem, int $actionType){ @@ -46,10 +47,6 @@ class CreativeInventoryAction extends InventoryAction{ /** * Checks that the player is in creative, and (if creating an item) that the item exists in the creative inventory. - * - * @param Player $source - * - * @return bool */ public function isValid(Player $source) : bool{ return $source->isCreative(true) and @@ -65,10 +62,6 @@ class CreativeInventoryAction extends InventoryAction{ /** * No need to do anything extra here: this type just provides a place for items to disappear or appear from. - * - * @param Player $source - * - * @return bool */ public function execute(Player $source) : bool{ return true; diff --git a/src/pocketmine/inventory/transaction/action/DropItemAction.php b/src/pocketmine/inventory/transaction/action/DropItemAction.php index c039f6e2b3..5dbe496072 100644 --- a/src/pocketmine/inventory/transaction/action/DropItemAction.php +++ b/src/pocketmine/inventory/transaction/action/DropItemAction.php @@ -53,10 +53,6 @@ class DropItemAction extends InventoryAction{ /** * Drops the target item in front of the player. - * - * @param Player $source - * - * @return bool */ public function execute(Player $source) : bool{ return $source->dropItem($this->targetItem); diff --git a/src/pocketmine/inventory/transaction/action/InventoryAction.php b/src/pocketmine/inventory/transaction/action/InventoryAction.php index 7ca2a2afaa..5a60521c47 100644 --- a/src/pocketmine/inventory/transaction/action/InventoryAction.php +++ b/src/pocketmine/inventory/transaction/action/InventoryAction.php @@ -43,7 +43,6 @@ abstract class InventoryAction{ /** * Returns the item that was present before the action took place. - * @return Item */ public function getSourceItem() : Item{ return clone $this->sourceItem; @@ -51,7 +50,6 @@ abstract class InventoryAction{ /** * Returns the item that the action attempted to replace the source item with. - * @return Item */ public function getTargetItem() : Item{ return clone $this->targetItem; @@ -59,17 +57,11 @@ abstract class InventoryAction{ /** * Returns whether this action is currently valid. This should perform any necessary sanity checks. - * - * @param Player $source - * - * @return bool */ abstract public function isValid(Player $source) : bool; /** * Called when the action is added to the specified InventoryTransaction. - * - * @param InventoryTransaction $transaction */ public function onAddToTransaction(InventoryTransaction $transaction) : void{ @@ -78,10 +70,6 @@ abstract class InventoryAction{ /** * Called by inventory transactions before any actions are processed. If this returns false, the transaction will * be cancelled. - * - * @param Player $source - * - * @return bool */ public function onPreExecute(Player $source) : bool{ return true; @@ -91,24 +79,16 @@ abstract class InventoryAction{ * Performs actions needed to complete the inventory-action server-side. Returns if it was successful. Will return * false if plugins cancelled events. This will only be called if the transaction which it is part of is considered * valid. - * - * @param Player $source - * - * @return bool */ abstract public function execute(Player $source) : bool; /** * Performs additional actions when this inventory-action completed successfully. - * - * @param Player $source */ abstract public function onExecuteSuccess(Player $source) : void; /** * Performs additional actions when this inventory-action did not complete successfully. - * - * @param Player $source */ abstract public function onExecuteFail(Player $source) : void; diff --git a/src/pocketmine/inventory/transaction/action/SlotChangeAction.php b/src/pocketmine/inventory/transaction/action/SlotChangeAction.php index 8b2a1812c8..4f8de5d328 100644 --- a/src/pocketmine/inventory/transaction/action/SlotChangeAction.php +++ b/src/pocketmine/inventory/transaction/action/SlotChangeAction.php @@ -39,12 +39,6 @@ class SlotChangeAction extends InventoryAction{ /** @var int */ private $inventorySlot; - /** - * @param Inventory $inventory - * @param int $inventorySlot - * @param Item $sourceItem - * @param Item $targetItem - */ public function __construct(Inventory $inventory, int $inventorySlot, Item $sourceItem, Item $targetItem){ parent::__construct($sourceItem, $targetItem); $this->inventory = $inventory; @@ -53,8 +47,6 @@ class SlotChangeAction extends InventoryAction{ /** * Returns the inventory involved in this action. - * - * @return Inventory */ public function getInventory() : Inventory{ return $this->inventory; @@ -62,7 +54,6 @@ class SlotChangeAction extends InventoryAction{ /** * Returns the slot in the inventory which this action modified. - * @return int */ public function getSlot() : int{ return $this->inventorySlot; @@ -70,10 +61,6 @@ class SlotChangeAction extends InventoryAction{ /** * Checks if the item in the inventory at the specified slot is the same as this action's source item. - * - * @param Player $source - * - * @return bool */ public function isValid(Player $source) : bool{ return ( @@ -84,9 +71,6 @@ class SlotChangeAction extends InventoryAction{ /** * Adds this action's target inventory to the transaction's inventory list. - * - * @param InventoryTransaction $transaction - * */ public function onAddToTransaction(InventoryTransaction $transaction) : void{ $transaction->addInventory($this->inventory); @@ -94,10 +78,6 @@ class SlotChangeAction extends InventoryAction{ /** * Sets the item into the target inventory. - * - * @param Player $source - * - * @return bool */ public function execute(Player $source) : bool{ return $this->inventory->setItem($this->inventorySlot, $this->targetItem, false); @@ -105,8 +85,6 @@ class SlotChangeAction extends InventoryAction{ /** * Sends slot changes to other viewers of the inventory. This will not send any change back to the source Player. - * - * @param Player $source */ public function onExecuteSuccess(Player $source) : void{ $viewers = $this->inventory->getViewers(); @@ -116,8 +94,6 @@ class SlotChangeAction extends InventoryAction{ /** * Sends the original slot contents to the source player to revert the action. - * - * @param Player $source */ public function onExecuteFail(Player $source) : void{ $this->inventory->sendSlot($this->inventorySlot, $source); diff --git a/src/pocketmine/item/Apple.php b/src/pocketmine/item/Apple.php index b0c4ccd125..ea212087a8 100644 --- a/src/pocketmine/item/Apple.php +++ b/src/pocketmine/item/Apple.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class Apple extends Food{ public function __construct(int $meta = 0){ parent::__construct(self::APPLE, $meta, "Apple"); diff --git a/src/pocketmine/item/Armor.php b/src/pocketmine/item/Armor.php index 076a5f8158..ba6b15e575 100644 --- a/src/pocketmine/item/Armor.php +++ b/src/pocketmine/item/Armor.php @@ -21,7 +21,6 @@ declare(strict_types=1); - namespace pocketmine\item; use pocketmine\event\entity\EntityDamageEvent; @@ -43,7 +42,6 @@ abstract class Armor extends Durable{ /** * Returns the dyed colour of this armour piece. This generally only applies to leather armour. - * @return Color|null */ public function getCustomColor() : ?Color{ if($this->getNamedTag()->hasTag(self::TAG_CUSTOM_COLOR, IntTag::class)){ @@ -55,8 +53,6 @@ abstract class Armor extends Durable{ /** * Sets the dyed colour of this armour piece. This generally only applies to leather armour. - * - * @param Color $color */ public function setCustomColor(Color $color) : void{ $this->setNamedTagEntry(new IntTag(self::TAG_CUSTOM_COLOR, Binary::signInt($color->toARGB()))); @@ -65,10 +61,6 @@ abstract class Armor extends Durable{ /** * Returns the total enchantment protection factor this armour piece offers from all applicable protection * enchantments on the item. - * - * @param EntityDamageEvent $event - * - * @return int */ public function getEnchantmentProtectionFactor(EntityDamageEvent $event) : int{ $epf = 0; diff --git a/src/pocketmine/item/Banner.php b/src/pocketmine/item/Banner.php index ef2b40d2ba..4af379872d 100644 --- a/src/pocketmine/item/Banner.php +++ b/src/pocketmine/item/Banner.php @@ -52,8 +52,6 @@ class Banner extends Item{ /** * Returns the color of the banner base. - * - * @return int */ public function getBaseColor() : int{ return $this->getNamedTag()->getInt(self::TAG_BASE, 0); @@ -62,8 +60,6 @@ class Banner extends Item{ /** * Sets the color of the banner base. * Banner items have to be resent to see the changes in the inventory. - * - * @param int $color */ public function setBaseColor(int $color) : void{ $namedTag = $this->getNamedTag(); @@ -75,9 +71,6 @@ class Banner extends Item{ * Applies a new pattern on the banner with the given color. * Banner items have to be resent to see the changes in the inventory. * - * @param string $pattern - * @param int $color - * * @return int ID of pattern. */ public function addPattern(string $pattern, int $color) : int{ @@ -96,10 +89,6 @@ class Banner extends Item{ /** * Returns whether a pattern with the given ID exists on the banner or not. - * - * @param int $patternId - * - * @return bool */ public function patternExists(int $patternId) : bool{ $this->correctNBT(); @@ -109,9 +98,8 @@ class Banner extends Item{ /** * Returns the data of a pattern with the given ID. * - * @param int $patternId - * - * @return array + * @return mixed[] + * @phpstan-return array{Color?: int, Pattern?: string} */ public function getPatternData(int $patternId) : array{ if(!$this->patternExists($patternId)){ @@ -133,10 +121,6 @@ class Banner extends Item{ * Changes the pattern of a previously existing pattern. * Banner items have to be resent to see the changes in the inventory. * - * @param int $patternId - * @param string $pattern - * @param int $color - * * @return bool indicating success. */ public function changePattern(int $patternId, string $pattern, int $color) : bool{ @@ -160,8 +144,6 @@ class Banner extends Item{ * Deletes a pattern from the banner with the given ID. * Banner items have to be resent to see the changes in the inventory. * - * @param int $patternId - * * @return bool indicating whether the pattern existed or not. */ public function deletePattern(int $patternId) : bool{ @@ -200,8 +182,6 @@ class Banner extends Item{ /** * Returns the total count of patterns on this banner. - * - * @return int */ public function getPatternCount() : int{ return $this->getNamedTag()->getListTag(self::TAG_PATTERNS)->count(); diff --git a/src/pocketmine/item/BeetrootSoup.php b/src/pocketmine/item/BeetrootSoup.php index 294698d266..75c5747c8c 100644 --- a/src/pocketmine/item/BeetrootSoup.php +++ b/src/pocketmine/item/BeetrootSoup.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class BeetrootSoup extends Food{ public function __construct(int $meta = 0){ parent::__construct(self::BEETROOT_SOUP, $meta, "Beetroot Soup"); diff --git a/src/pocketmine/item/Bow.php b/src/pocketmine/item/Bow.php index 48428b5765..c904afb5e0 100644 --- a/src/pocketmine/item/Bow.php +++ b/src/pocketmine/item/Bow.php @@ -65,7 +65,6 @@ class Bow extends Tool{ $p = $diff / 20; $baseForce = min((($p ** 2) + $p * 2) / 3, 1); - $entity = Entity::createEntity("Arrow", $player->getLevel(), $nbt, $player, $baseForce >= 1); if($entity instanceof Projectile){ $infinity = $this->hasEnchantment(Enchantment::INFINITY); diff --git a/src/pocketmine/item/Bowl.php b/src/pocketmine/item/Bowl.php index 67a81ae406..3d54d6ac16 100644 --- a/src/pocketmine/item/Bowl.php +++ b/src/pocketmine/item/Bowl.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class Bowl extends Item{ public function __construct(int $meta = 0){ parent::__construct(self::BOWL, $meta, "Bowl"); diff --git a/src/pocketmine/item/ChainBoots.php b/src/pocketmine/item/ChainBoots.php index 141aefc8cb..8b39921050 100644 --- a/src/pocketmine/item/ChainBoots.php +++ b/src/pocketmine/item/ChainBoots.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class ChainBoots extends Armor{ public function __construct(int $meta = 0){ parent::__construct(self::CHAIN_BOOTS, $meta, "Chainmail Boots"); diff --git a/src/pocketmine/item/ChainChestplate.php b/src/pocketmine/item/ChainChestplate.php index 2f1453fc97..5952d8386f 100644 --- a/src/pocketmine/item/ChainChestplate.php +++ b/src/pocketmine/item/ChainChestplate.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class ChainChestplate extends Armor{ public function __construct(int $meta = 0){ parent::__construct(self::CHAIN_CHESTPLATE, $meta, "Chain Chestplate"); diff --git a/src/pocketmine/item/ChainHelmet.php b/src/pocketmine/item/ChainHelmet.php index b949a72ffd..e23cdbde19 100644 --- a/src/pocketmine/item/ChainHelmet.php +++ b/src/pocketmine/item/ChainHelmet.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class ChainHelmet extends Armor{ public function __construct(int $meta = 0){ parent::__construct(self::CHAIN_HELMET, $meta, "Chainmail Helmet"); diff --git a/src/pocketmine/item/ChainLeggings.php b/src/pocketmine/item/ChainLeggings.php index e4882f06b6..bbbfd85536 100644 --- a/src/pocketmine/item/ChainLeggings.php +++ b/src/pocketmine/item/ChainLeggings.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class ChainLeggings extends Armor{ public function __construct(int $meta = 0){ parent::__construct(self::CHAIN_LEGGINGS, $meta, "Chain Leggings"); diff --git a/src/pocketmine/item/Coal.php b/src/pocketmine/item/Coal.php index 89c214b3bd..9f12c963d9 100644 --- a/src/pocketmine/item/Coal.php +++ b/src/pocketmine/item/Coal.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class Coal extends Item{ public function __construct(int $meta = 0){ parent::__construct(self::COAL, $meta, "Coal"); diff --git a/src/pocketmine/item/Consumable.php b/src/pocketmine/item/Consumable.php index 5977c37f44..1ba7d939a9 100644 --- a/src/pocketmine/item/Consumable.php +++ b/src/pocketmine/item/Consumable.php @@ -48,7 +48,7 @@ interface Consumable{ /** * Called when this Consumable is consumed by mob, after standard resulting effects have been applied. * - * @param Living $consumer + * @return void */ public function onConsume(Living $consumer); } diff --git a/src/pocketmine/item/DiamondBoots.php b/src/pocketmine/item/DiamondBoots.php index 25b79761da..17dd406126 100644 --- a/src/pocketmine/item/DiamondBoots.php +++ b/src/pocketmine/item/DiamondBoots.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class DiamondBoots extends Armor{ public function __construct(int $meta = 0){ parent::__construct(self::DIAMOND_BOOTS, $meta, "Diamond Boots"); diff --git a/src/pocketmine/item/DiamondChestplate.php b/src/pocketmine/item/DiamondChestplate.php index 778aa6ba92..d064cae209 100644 --- a/src/pocketmine/item/DiamondChestplate.php +++ b/src/pocketmine/item/DiamondChestplate.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class DiamondChestplate extends Armor{ public function __construct(int $meta = 0){ parent::__construct(self::DIAMOND_CHESTPLATE, $meta, "Diamond Chestplate"); diff --git a/src/pocketmine/item/DiamondHelmet.php b/src/pocketmine/item/DiamondHelmet.php index c5f652cc68..05dc04c922 100644 --- a/src/pocketmine/item/DiamondHelmet.php +++ b/src/pocketmine/item/DiamondHelmet.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class DiamondHelmet extends Armor{ public function __construct(int $meta = 0){ parent::__construct(self::DIAMOND_HELMET, $meta, "Diamond Helmet"); diff --git a/src/pocketmine/item/DiamondLeggings.php b/src/pocketmine/item/DiamondLeggings.php index 6f7613c6fb..5855ec0e23 100644 --- a/src/pocketmine/item/DiamondLeggings.php +++ b/src/pocketmine/item/DiamondLeggings.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class DiamondLeggings extends Armor{ public function __construct(int $meta = 0){ parent::__construct(self::DIAMOND_LEGGINGS, $meta, "Diamond Leggings"); diff --git a/src/pocketmine/item/Durable.php b/src/pocketmine/item/Durable.php index 07fa510024..026a35bfb4 100644 --- a/src/pocketmine/item/Durable.php +++ b/src/pocketmine/item/Durable.php @@ -32,7 +32,6 @@ abstract class Durable extends Item{ /** * Returns whether this item will take damage when used. - * @return bool */ public function isUnbreakable() : bool{ return $this->getNamedTag()->getByte("Unbreakable", 0) !== 0; @@ -41,7 +40,7 @@ abstract class Durable extends Item{ /** * Sets whether the item will take damage when used. * - * @param bool $value + * @return void */ public function setUnbreakable(bool $value = true){ $this->setNamedTagEntry(new ByteTag("Unbreakable", $value ? 1 : 0)); @@ -50,8 +49,6 @@ abstract class Durable extends Item{ /** * Applies damage to the item. * - * @param int $amount - * * @return bool if any damage was applied to the item */ public function applyDamage(int $amount) : bool{ @@ -95,14 +92,11 @@ abstract class Durable extends Item{ /** * Returns the maximum amount of damage this item can take before it breaks. - * - * @return int */ abstract public function getMaxDurability() : int; /** * Returns whether the item is broken. - * @return bool */ public function isBroken() : bool{ return $this->meta >= $this->getMaxDurability(); diff --git a/src/pocketmine/item/FoodSource.php b/src/pocketmine/item/FoodSource.php index 0e5b553355..ddddb4a943 100644 --- a/src/pocketmine/item/FoodSource.php +++ b/src/pocketmine/item/FoodSource.php @@ -34,7 +34,6 @@ interface FoodSource extends Consumable{ /** * Returns whether a Human eating this FoodSource must have a non-full hunger bar. - * @return bool */ public function requiresHunger() : bool; } diff --git a/src/pocketmine/item/GoldBoots.php b/src/pocketmine/item/GoldBoots.php index cb039b52df..91c7301cc5 100644 --- a/src/pocketmine/item/GoldBoots.php +++ b/src/pocketmine/item/GoldBoots.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class GoldBoots extends Armor{ public function __construct(int $meta = 0){ parent::__construct(self::GOLD_BOOTS, $meta, "Gold Boots"); diff --git a/src/pocketmine/item/GoldChestplate.php b/src/pocketmine/item/GoldChestplate.php index 74bed00ac7..c60dabfd98 100644 --- a/src/pocketmine/item/GoldChestplate.php +++ b/src/pocketmine/item/GoldChestplate.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class GoldChestplate extends Armor{ public function __construct(int $meta = 0){ parent::__construct(self::GOLD_CHESTPLATE, $meta, "Gold Chestplate"); diff --git a/src/pocketmine/item/GoldHelmet.php b/src/pocketmine/item/GoldHelmet.php index 043c363a2f..db047a81c0 100644 --- a/src/pocketmine/item/GoldHelmet.php +++ b/src/pocketmine/item/GoldHelmet.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class GoldHelmet extends Armor{ public function __construct(int $meta = 0){ parent::__construct(self::GOLD_HELMET, $meta, "Gold Helmet"); diff --git a/src/pocketmine/item/GoldLeggings.php b/src/pocketmine/item/GoldLeggings.php index 47b675259b..e1b43ece3b 100644 --- a/src/pocketmine/item/GoldLeggings.php +++ b/src/pocketmine/item/GoldLeggings.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class GoldLeggings extends Armor{ public function __construct(int $meta = 0){ parent::__construct(self::GOLD_LEGGINGS, $meta, "Gold Leggings"); diff --git a/src/pocketmine/item/IronBoots.php b/src/pocketmine/item/IronBoots.php index a116394684..edbe6b9e0b 100644 --- a/src/pocketmine/item/IronBoots.php +++ b/src/pocketmine/item/IronBoots.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class IronBoots extends Armor{ public function __construct(int $meta = 0){ parent::__construct(self::IRON_BOOTS, $meta, "Iron Boots"); diff --git a/src/pocketmine/item/IronChestplate.php b/src/pocketmine/item/IronChestplate.php index 2cb8814788..599ff93179 100644 --- a/src/pocketmine/item/IronChestplate.php +++ b/src/pocketmine/item/IronChestplate.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class IronChestplate extends Armor{ public function __construct(int $meta = 0){ parent::__construct(self::IRON_CHESTPLATE, $meta, "Iron Chestplate"); diff --git a/src/pocketmine/item/IronHelmet.php b/src/pocketmine/item/IronHelmet.php index 74875d29e2..ada867f77a 100644 --- a/src/pocketmine/item/IronHelmet.php +++ b/src/pocketmine/item/IronHelmet.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class IronHelmet extends Armor{ public function __construct(int $meta = 0){ parent::__construct(self::IRON_HELMET, $meta, "Iron Helmet"); diff --git a/src/pocketmine/item/IronLeggings.php b/src/pocketmine/item/IronLeggings.php index 655248f99d..83a10b1ed4 100644 --- a/src/pocketmine/item/IronLeggings.php +++ b/src/pocketmine/item/IronLeggings.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class IronLeggings extends Armor{ public function __construct(int $meta = 0){ parent::__construct(self::IRON_LEGGINGS, $meta, "Iron Leggings"); diff --git a/src/pocketmine/item/Item.php b/src/pocketmine/item/Item.php index 664e07bbae..da1759252c 100644 --- a/src/pocketmine/item/Item.php +++ b/src/pocketmine/item/Item.php @@ -49,7 +49,9 @@ use function base64_encode; use function file_get_contents; use function get_class; use function hex2bin; +use function is_string; use function json_decode; +use function strlen; use const DIRECTORY_SEPARATOR; class Item implements ItemIds, \JsonSerializable{ @@ -60,8 +62,7 @@ class Item implements ItemIds, \JsonSerializable{ public const TAG_DISPLAY_NAME = "Name"; public const TAG_DISPLAY_LORE = "Lore"; - - /** @var LittleEndianNBTStream */ + /** @var LittleEndianNBTStream|null */ private static $cachedParser = null; private static function parseCompoundTag(string $tag) : CompoundTag{ @@ -94,12 +95,7 @@ class Item implements ItemIds, \JsonSerializable{ * * This function redirects to {@link ItemFactory#get}. * - * @param int $id - * @param int $meta - * @param int $count * @param CompoundTag|string $tags - * - * @return Item */ public static function get(int $id, int $meta = 0, int $count = 1, $tags = "") : Item{ return ItemFactory::get($id, $meta, $count, $tags); @@ -110,19 +106,18 @@ class Item implements ItemIds, \JsonSerializable{ * * This function redirects to {@link ItemFactory#fromString}. * - * @param string $str - * @param bool $multiple - * * @return Item[]|Item */ public static function fromString(string $str, bool $multiple = false){ return ItemFactory::fromString($str, $multiple); } - /** @var Item[] */ private static $creative = []; + /** + * @return void + */ public static function initCreativeItems(){ self::clearCreativeItems(); @@ -140,11 +135,16 @@ class Item implements ItemIds, \JsonSerializable{ /** * Removes all previously added items from the creative menu. * Note: Players who are already online when this is called will not see this change. + * + * @return void */ public static function clearCreativeItems(){ Item::$creative = []; } + /** + * @return Item[] + */ public static function getCreativeItems() : array{ return Item::$creative; } @@ -153,7 +153,7 @@ class Item implements ItemIds, \JsonSerializable{ * Adds an item to the creative menu. * Note: Players who are already online when this is called will not see this change. * - * @param Item $item + * @return void */ public static function addCreativeItem(Item $item){ Item::$creative[] = clone $item; @@ -163,7 +163,7 @@ class Item implements ItemIds, \JsonSerializable{ * Removes an item from the creative menu. * Note: Players who are already online when this is called will not see this change. * - * @param Item $item + * @return void */ public static function removeCreativeItem(Item $item){ $index = self::getCreativeItemIndex($item); @@ -177,8 +177,6 @@ class Item implements ItemIds, \JsonSerializable{ } /** - * @param int $index - * * @return Item|null */ public static function getCreativeItem(int $index){ @@ -199,10 +197,8 @@ class Item implements ItemIds, \JsonSerializable{ protected $id; /** @var int */ protected $meta; - /** @var string */ - private $tags = ""; /** @var CompoundTag|null */ - private $cachedNBT = null; + private $nbt = null; /** @var int */ public $count = 1; /** @var string */ @@ -214,10 +210,6 @@ class Item implements ItemIds, \JsonSerializable{ * * NOTE: This should NOT BE USED for creating items to set into an inventory. Use {@link ItemFactory#get} for that * purpose. - * - * @param int $id - * @param int $meta - * @param string $name */ public function __construct(int $id, int $meta = 0, string $name = "Unknown"){ if($id < -0x8000 or $id > 0x7fff){ //signed short range @@ -229,18 +221,20 @@ class Item implements ItemIds, \JsonSerializable{ } /** - * Sets the Item's NBT + * @deprecated This method accepts NBT serialized in a network-dependent format. + * @see Item::setNamedTag() * * @param CompoundTag|string|null $tags * - * @return Item + * @return $this */ public function setCompoundTag($tags) : Item{ if($tags instanceof CompoundTag){ $this->setNamedTag($tags); + }elseif(is_string($tags) and strlen($tags) > 0){ + $this->setNamedTag(self::parseCompoundTag($tags)); }else{ - $this->tags = $tags === null ? "" : (string) $tags; - $this->cachedNBT = null; + $this->clearNamedTag(); } return $this; @@ -251,36 +245,32 @@ class Item implements ItemIds, \JsonSerializable{ * @see Item::getNamedTag() * * Returns the serialized NBT of the Item - * @return string */ public function getCompoundTag() : string{ - return $this->tags; + return $this->nbt !== null ? self::writeCompoundTag($this->nbt) : ""; } /** * Returns whether this Item has a non-empty NBT. - * @return bool */ public function hasCompoundTag() : bool{ - return $this->tags !== ""; + return $this->nbt !== null and $this->nbt->getCount() > 0; } - /** - * @return bool - */ public function hasCustomBlockData() : bool{ return $this->getNamedTagEntry(self::TAG_BLOCK_ENTITY_TAG) instanceof CompoundTag; } + /** + * @return $this + */ public function clearCustomBlockData(){ $this->removeNamedTagEntry(self::TAG_BLOCK_ENTITY_TAG); return $this; } /** - * @param CompoundTag $compound - * - * @return Item + * @return $this */ public function setCustomBlockData(CompoundTag $compound) : Item{ $tags = clone $compound; @@ -290,27 +280,15 @@ class Item implements ItemIds, \JsonSerializable{ return $this; } - /** - * @return CompoundTag|null - */ public function getCustomBlockData() : ?CompoundTag{ $tag = $this->getNamedTagEntry(self::TAG_BLOCK_ENTITY_TAG); return $tag instanceof CompoundTag ? $tag : null; } - /** - * @return bool - */ public function hasEnchantments() : bool{ return $this->getNamedTagEntry(self::TAG_ENCH) instanceof ListTag; } - /** - * @param int $id - * @param int $level - * - * @return bool - */ public function hasEnchantment(int $id, int $level = -1) : bool{ $ench = $this->getNamedTagEntry(self::TAG_ENCH); if(!($ench instanceof ListTag)){ @@ -327,11 +305,6 @@ class Item implements ItemIds, \JsonSerializable{ return false; } - /** - * @param int $id - * - * @return EnchantmentInstance|null - */ public function getEnchantment(int $id) : ?EnchantmentInstance{ $ench = $this->getNamedTagEntry(self::TAG_ENCH); if(!($ench instanceof ListTag)){ @@ -351,10 +324,6 @@ class Item implements ItemIds, \JsonSerializable{ return null; } - /** - * @param int $id - * @param int $level - */ public function removeEnchantment(int $id, int $level = -1) : void{ $ench = $this->getNamedTagEntry(self::TAG_ENCH); if(!($ench instanceof ListTag)){ @@ -376,9 +345,6 @@ class Item implements ItemIds, \JsonSerializable{ $this->removeNamedTagEntry(self::TAG_ENCH); } - /** - * @param EnchantmentInstance $enchantment - */ public function addEnchantment(EnchantmentInstance $enchantment) : void{ $found = false; @@ -433,10 +399,6 @@ class Item implements ItemIds, \JsonSerializable{ /** * Returns the level of the enchantment on this item with the specified ID, or 0 if the item does not have the * enchantment. - * - * @param int $enchantmentId - * - * @return int */ public function getEnchantmentLevel(int $enchantmentId) : int{ $ench = $this->getNamedTag()->getListTag(self::TAG_ENCH); @@ -452,9 +414,6 @@ class Item implements ItemIds, \JsonSerializable{ return 0; } - /** - * @return bool - */ public function hasCustomName() : bool{ $display = $this->getNamedTagEntry(self::TAG_DISPLAY); if($display instanceof CompoundTag){ @@ -464,9 +423,6 @@ class Item implements ItemIds, \JsonSerializable{ return false; } - /** - * @return string - */ public function getCustomName() : string{ $display = $this->getNamedTagEntry(self::TAG_DISPLAY); if($display instanceof CompoundTag){ @@ -477,16 +433,13 @@ class Item implements ItemIds, \JsonSerializable{ } /** - * @param string $name - * - * @return Item + * @return $this */ public function setCustomName(string $name) : Item{ if($name === ""){ return $this->clearCustomName(); } - /** @var CompoundTag $display */ $display = $this->getNamedTagEntry(self::TAG_DISPLAY); if(!($display instanceof CompoundTag)){ $display = new CompoundTag(self::TAG_DISPLAY); @@ -499,7 +452,7 @@ class Item implements ItemIds, \JsonSerializable{ } /** - * @return Item + * @return $this */ public function clearCustomName() : Item{ $display = $this->getNamedTagEntry(self::TAG_DISPLAY); @@ -531,7 +484,7 @@ class Item implements ItemIds, \JsonSerializable{ /** * @param string[] $lines * - * @return Item + * @return $this */ public function setLore(array $lines) : Item{ $display = $this->getNamedTagEntry(self::TAG_DISPLAY); @@ -548,11 +501,6 @@ class Item implements ItemIds, \JsonSerializable{ return $this; } - /** - * @param string $name - * - * @return NamedTag|null - */ public function getNamedTagEntry(string $name) : ?NamedTag{ return $this->getNamedTag()->getTag($name); } @@ -572,54 +520,41 @@ class Item implements ItemIds, \JsonSerializable{ /** * Returns a tree of Tag objects representing the Item's NBT. If the item does not have any NBT, an empty CompoundTag * object is returned to allow the caller to manipulate and apply back to the item. - * - * @return CompoundTag */ public function getNamedTag() : CompoundTag{ - if(!$this->hasCompoundTag() and $this->cachedNBT === null){ - $this->cachedNBT = new CompoundTag(); - } - - return $this->cachedNBT ?? ($this->cachedNBT = self::parseCompoundTag($this->tags)); + return $this->nbt ?? ($this->nbt = new CompoundTag()); } /** * Sets the Item's NBT from the supplied CompoundTag object. * - * @param CompoundTag $tag - * - * @return Item + * @return $this */ public function setNamedTag(CompoundTag $tag) : Item{ if($tag->getCount() === 0){ return $this->clearNamedTag(); } - $this->cachedNBT = $tag; - $this->tags = self::writeCompoundTag($tag); + $this->nbt = clone $tag; return $this; } /** * Removes the Item's NBT. - * @return Item + * @return $this */ public function clearNamedTag() : Item{ - return $this->setCompoundTag(""); + $this->nbt = null; + return $this; } - /** - * @return int - */ public function getCount() : int{ return $this->count; } /** - * @param int $count - * - * @return Item + * @return $this */ public function setCount(int $count) : Item{ $this->count = $count; @@ -630,9 +565,7 @@ class Item implements ItemIds, \JsonSerializable{ /** * Pops an item from the stack and returns it, decreasing the stack count of this item stack by one. * - * @param int $count - * - * @return Item + * @return $this * @throws \InvalidArgumentException if trying to pop more items than are on the stack */ public function pop(int $count = 1) : Item{ @@ -654,7 +587,6 @@ class Item implements ItemIds, \JsonSerializable{ /** * Returns the name of the item, or the custom name if it is set. - * @return string */ final public function getName() : string{ return $this->hasCustomName() ? $this->getCustomName() : $this->getVanillaName(); @@ -662,45 +594,32 @@ class Item implements ItemIds, \JsonSerializable{ /** * Returns the vanilla name of the item, disregarding custom names. - * @return string */ public function getVanillaName() : string{ return $this->name; } - /** - * @return bool - */ final public function canBePlaced() : bool{ return $this->getBlock()->canBePlaced(); } /** * Returns the block corresponding to this Item. - * @return Block */ public function getBlock() : Block{ return BlockFactory::get(self::AIR); } - /** - * @return int - */ final public function getId() : int{ return $this->id; } - /** - * @return int - */ final public function getDamage() : int{ return $this->meta; } /** - * @param int $meta - * - * @return Item + * @return $this */ public function setDamage(int $meta) : Item{ $this->meta = $meta !== -1 ? $meta & 0x7FFF : -1; @@ -711,8 +630,6 @@ class Item implements ItemIds, \JsonSerializable{ /** * Returns whether this item can match any item with an equivalent ID with any meta value. * Used in crafting recipes which accept multiple variants of the same item, for example crafting tables recipes. - * - * @return bool */ public function hasAnyDamageValue() : bool{ return $this->meta === -1; @@ -720,7 +637,6 @@ class Item implements ItemIds, \JsonSerializable{ /** * Returns the highest amount of this item which will fit into one inventory slot. - * @return int */ public function getMaxStackSize() : int{ return 64; @@ -728,7 +644,6 @@ class Item implements ItemIds, \JsonSerializable{ /** * Returns the time in ticks which the item will fuel a furnace for. - * @return int */ public function getFuelTime() : int{ return 0; @@ -736,7 +651,6 @@ class Item implements ItemIds, \JsonSerializable{ /** * Returns how many points of damage this item will deal to an entity when used as a weapon. - * @return int */ public function getAttackPoints() : int{ return 1; @@ -744,7 +658,6 @@ class Item implements ItemIds, \JsonSerializable{ /** * Returns how many armor points can be gained by wearing this item. - * @return int */ public function getDefensePoints() : int{ return 0; @@ -753,8 +666,6 @@ class Item implements ItemIds, \JsonSerializable{ /** * Returns what type of block-breaking tool this is. Blocks requiring the same tool type as the item will break * faster (except for blocks requiring no tool, which break at the same speed regardless of the tool used) - * - * @return int */ public function getBlockToolType() : int{ return BlockToolType::TYPE_NONE; @@ -766,8 +677,6 @@ class Item implements ItemIds, \JsonSerializable{ * This should return 1 for non-tiered tools, and the tool tier for tiered tools. * * @see Block::getToolHarvestLevel() - * - * @return int */ public function getBlockToolHarvestLevel() : int{ return 0; @@ -779,14 +688,6 @@ class Item implements ItemIds, \JsonSerializable{ /** * Called when a player uses this item on a block. - * - * @param Player $player - * @param Block $blockReplace - * @param Block $blockClicked - * @param int $face - * @param Vector3 $clickVector - * - * @return bool */ public function onActivate(Player $player, Block $blockReplace, Block $blockClicked, int $face, Vector3 $clickVector) : bool{ return false; @@ -795,11 +696,6 @@ class Item implements ItemIds, \JsonSerializable{ /** * Called when a player uses the item on air, for example throwing a projectile. * Returns whether the item was changed, for example count decrease or durability change. - * - * @param Player $player - * @param Vector3 $directionVector - * - * @return bool */ public function onClickAir(Player $player, Vector3 $directionVector) : bool{ return false; @@ -808,10 +704,6 @@ class Item implements ItemIds, \JsonSerializable{ /** * Called when a player is using this item and releases it. Used to handle bow shoot actions. * Returns whether the item was changed, for example count decrease or durability change. - * - * @param Player $player - * - * @return bool */ public function onReleaseUsing(Player $player) : bool{ return false; @@ -819,10 +711,6 @@ class Item implements ItemIds, \JsonSerializable{ /** * Called when this item is used to destroy a block. Usually used to update durability. - * - * @param Block $block - * - * @return bool */ public function onDestroyBlock(Block $block) : bool{ return false; @@ -830,10 +718,6 @@ class Item implements ItemIds, \JsonSerializable{ /** * Called when this item is used to attack an entity. Usually used to update durability. - * - * @param Entity $victim - * - * @return bool */ public function onAttackEntity(Entity $victim) : bool{ return false; @@ -841,8 +725,6 @@ class Item implements ItemIds, \JsonSerializable{ /** * Returns the number of ticks a player must wait before activating this item again. - * - * @return int */ public function getCooldownTicks() : int{ return 0; @@ -851,43 +733,22 @@ class Item implements ItemIds, \JsonSerializable{ /** * Compares an Item to this Item and check if they match. * - * @param Item $item * @param bool $checkDamage Whether to verify that the damage values match. * @param bool $checkCompound Whether to verify that the items' NBT match. - * - * @return bool */ final public function equals(Item $item, bool $checkDamage = true, bool $checkCompound = true) : bool{ - if($this->id === $item->getId() and (!$checkDamage or $this->getDamage() === $item->getDamage())){ - if($checkCompound){ - if($item->getCompoundTag() === $this->getCompoundTag()){ - return true; - }elseif($this->hasCompoundTag() and $item->hasCompoundTag()){ - //Serialized NBT didn't match, check the cached object tree. - return $this->getNamedTag()->equals($item->getNamedTag()); - } - }else{ - return true; - } - } - - return false; + return $this->id === $item->getId() and + (!$checkDamage or $this->getDamage() === $item->getDamage()) and + (!$checkCompound or $this->getNamedTag()->equals($item->getNamedTag())); } /** * Returns whether the specified item stack has the same ID, damage, NBT and count as this item stack. - * - * @param Item $other - * - * @return bool */ final public function equalsExact(Item $other) : bool{ return $this->equals($other, true, true) and $this->count === $other->count; } - /** - * @return string - */ final public function __toString() : string{ return "Item " . $this->name . " (" . $this->id . ":" . ($this->hasAnyDamageValue() ? "?" : $this->meta) . ")x" . $this->count . ($this->hasCompoundTag() ? " tags:" . base64_encode($this->getCompoundTag()) : ""); } @@ -895,7 +756,8 @@ class Item implements ItemIds, \JsonSerializable{ /** * Returns an array of item stack properties that can be serialized to json. * - * @return array + * @return mixed[] + * @phpstan-return array{id: int, damage?: int, count?: int, nbt_b64?: string} */ final public function jsonSerialize() : array{ $data = [ @@ -919,10 +781,15 @@ class Item implements ItemIds, \JsonSerializable{ /** * Returns an Item from properties created in an array by {@link Item#jsonSerialize} - * - * @param array $data - * - * @return Item + * @param mixed[] $data + * @phpstan-param array{ + * id: int, + * damage?: int, + * count?: int, + * nbt?: string, + * nbt_hex?: string, + * nbt_b64?: string + * } $data */ final public static function jsonDeserialize(array $data) : Item{ $nbt = ""; @@ -948,8 +815,6 @@ class Item implements ItemIds, \JsonSerializable{ * * @param int $slot optional, the inventory slot of the item * @param string $tagName the name to assign to the CompoundTag object - * - * @return CompoundTag */ public function nbtSerialize(int $slot = -1, string $tagName = "") : CompoundTag{ $result = new CompoundTag($tagName, [ @@ -973,10 +838,6 @@ class Item implements ItemIds, \JsonSerializable{ /** * Deserializes an Item from an NBT CompoundTag - * - * @param CompoundTag $tag - * - * @return Item */ public static function nbtDeserialize(CompoundTag $tag) : Item{ if(!$tag->hasTag("id") or !$tag->hasTag("Count")){ @@ -1014,6 +875,8 @@ class Item implements ItemIds, \JsonSerializable{ } public function __clone(){ - $this->cachedNBT = null; + if($this->nbt !== null){ + $this->nbt = clone $this->nbt; + } } } diff --git a/src/pocketmine/item/ItemBlock.php b/src/pocketmine/item/ItemBlock.php index 865c0470d4..4e93ee8dd2 100644 --- a/src/pocketmine/item/ItemBlock.php +++ b/src/pocketmine/item/ItemBlock.php @@ -34,9 +34,7 @@ class ItemBlock extends Item{ protected $blockId; /** - * @param int $blockId * @param int $meta usually 0-15 (placed blocks may only have meta values 0-15) - * @param int|null $itemId */ public function __construct(int $blockId, int $meta = 0, int $itemId = null){ $this->blockId = $blockId; diff --git a/src/pocketmine/item/ItemFactory.php b/src/pocketmine/item/ItemFactory.php index 3c51f3173f..cf1c637748 100644 --- a/src/pocketmine/item/ItemFactory.php +++ b/src/pocketmine/item/ItemFactory.php @@ -43,9 +43,15 @@ use function trim; */ class ItemFactory{ - /** @var \SplFixedArray */ - private static $list = null; + /** + * @var \SplFixedArray|Item[] + * @phpstan-var \SplFixedArray + */ + private static $list; + /** + * @return void + */ public static function init(){ self::$list = new \SplFixedArray(65536); @@ -282,9 +288,7 @@ class ItemFactory{ * NOTE: If you are registering a new item type, you will need to add it to the creative inventory yourself - it * will not automatically appear there. * - * @param Item $item - * @param bool $override - * + * @return void * @throws \RuntimeException if something attempted to override an already-registered item without specifying the * $override parameter. */ @@ -300,12 +304,8 @@ class ItemFactory{ /** * Returns an instance of the Item with the specified id, meta, count and NBT. * - * @param int $id - * @param int $meta - * @param int $count * @param CompoundTag|string|null $tags * - * @return Item * @throws \TypeError */ public static function get(int $id, int $meta = 0, int $count = 1, $tags = null) : Item{ @@ -346,9 +346,6 @@ class ItemFactory{ * If multiple item instances are to be created, their identifiers must be comma-separated, for example: * `diamond_pickaxe,wooden_shovel:18,iron_ingot` * - * @param string $str - * @param bool $multiple - * * @return Item[]|Item * * @throws \InvalidArgumentException if the given string cannot be parsed as an item identifier @@ -385,9 +382,6 @@ class ItemFactory{ /** * Returns whether the specified item ID is already registered in the item factory. - * - * @param int $id - * @return bool */ public static function isRegistered(int $id) : bool{ if($id < 256){ diff --git a/src/pocketmine/item/LeatherBoots.php b/src/pocketmine/item/LeatherBoots.php index 4c93de806d..d188fa2793 100644 --- a/src/pocketmine/item/LeatherBoots.php +++ b/src/pocketmine/item/LeatherBoots.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class LeatherBoots extends Armor{ public function __construct(int $meta = 0){ parent::__construct(self::LEATHER_BOOTS, $meta, "Leather Boots"); diff --git a/src/pocketmine/item/LeatherCap.php b/src/pocketmine/item/LeatherCap.php index 3b2c0653dd..7355790b52 100644 --- a/src/pocketmine/item/LeatherCap.php +++ b/src/pocketmine/item/LeatherCap.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class LeatherCap extends Armor{ public function __construct(int $meta = 0){ parent::__construct(self::LEATHER_CAP, $meta, "Leather Cap"); diff --git a/src/pocketmine/item/LeatherPants.php b/src/pocketmine/item/LeatherPants.php index 05ee76ca74..f3510959c9 100644 --- a/src/pocketmine/item/LeatherPants.php +++ b/src/pocketmine/item/LeatherPants.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class LeatherPants extends Armor{ public function __construct(int $meta = 0){ parent::__construct(self::LEATHER_PANTS, $meta, "Leather Pants"); diff --git a/src/pocketmine/item/LeatherTunic.php b/src/pocketmine/item/LeatherTunic.php index d587f2eaa2..c3f6285b2b 100644 --- a/src/pocketmine/item/LeatherTunic.php +++ b/src/pocketmine/item/LeatherTunic.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class LeatherTunic extends Armor{ public function __construct(int $meta = 0){ parent::__construct(self::LEATHER_TUNIC, $meta, "Leather Tunic"); diff --git a/src/pocketmine/item/PaintingItem.php b/src/pocketmine/item/PaintingItem.php index 9e98cce12b..89ec034ead 100644 --- a/src/pocketmine/item/PaintingItem.php +++ b/src/pocketmine/item/PaintingItem.php @@ -31,6 +31,7 @@ use pocketmine\math\Vector3; use pocketmine\network\mcpe\protocol\LevelEventPacket; use pocketmine\Player; use function array_rand; +use function count; class PaintingItem extends Item{ public function __construct(int $meta = 0){ @@ -66,7 +67,7 @@ class PaintingItem extends Item{ } } - if(empty($motives)){ //No space available + if(count($motives) === 0){ //No space available return false; } diff --git a/src/pocketmine/item/Potion.php b/src/pocketmine/item/Potion.php index b2b927d54d..d971446953 100644 --- a/src/pocketmine/item/Potion.php +++ b/src/pocketmine/item/Potion.php @@ -70,8 +70,6 @@ class Potion extends Item implements Consumable{ /** * Returns a list of effects applied by potions with the specified ID. * - * @param int $id - * * @return EffectInstance[] */ public static function getPotionEffectsById(int $id) : array{ diff --git a/src/pocketmine/item/ProjectileItem.php b/src/pocketmine/item/ProjectileItem.php index 88bebf3e1f..79a4378112 100644 --- a/src/pocketmine/item/ProjectileItem.php +++ b/src/pocketmine/item/ProjectileItem.php @@ -40,8 +40,6 @@ abstract class ProjectileItem extends Item{ /** * Helper function to apply extra NBT tags to pass to the created projectile. - * - * @param CompoundTag $tag */ protected function addExtraTags(CompoundTag $tag) : void{ diff --git a/src/pocketmine/item/Stick.php b/src/pocketmine/item/Stick.php index b3dd1c92c1..c6972114db 100644 --- a/src/pocketmine/item/Stick.php +++ b/src/pocketmine/item/Stick.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item; - class Stick extends Item{ public function __construct(int $meta = 0){ parent::__construct(self::STICK, $meta, "Stick"); diff --git a/src/pocketmine/item/WritableBook.php b/src/pocketmine/item/WritableBook.php index 8b965b787b..25585040d1 100644 --- a/src/pocketmine/item/WritableBook.php +++ b/src/pocketmine/item/WritableBook.php @@ -40,10 +40,6 @@ class WritableBook extends Item{ /** * Returns whether the given page exists in this book. - * - * @param int $pageId - * - * @return bool */ public function pageExists(int $pageId) : bool{ return $this->getPagesTag()->isset($pageId); @@ -51,10 +47,6 @@ class WritableBook extends Item{ /** * Returns a string containing the content of a page (which could be empty), or null if the page doesn't exist. - * - * @param int $pageId - * - * @return string|null */ public function getPageText(int $pageId) : ?string{ $pages = $this->getNamedTag()->getListTag(self::TAG_PAGES); @@ -73,9 +65,6 @@ class WritableBook extends Item{ /** * Sets the text of a page in the book. Adds the page if the page does not yet exist. * - * @param int $pageId - * @param string $pageText - * * @return bool indicating whether the page was created or not. */ public function setPageText(int $pageId, string $pageText) : bool{ @@ -99,8 +88,6 @@ class WritableBook extends Item{ /** * Adds a new page with the given page ID. * Creates a new page for every page between the given ID and existing pages that doesn't yet exist. - * - * @param int $pageId */ public function addPage(int $pageId) : void{ if($pageId < 0){ @@ -122,8 +109,6 @@ class WritableBook extends Item{ /** * Deletes an existing page with the given page ID. * - * @param int $pageId - * * @return bool indicating success */ public function deletePage(int $pageId) : bool{ @@ -137,9 +122,6 @@ class WritableBook extends Item{ /** * Inserts a new page with the given text and moves other pages upwards. * - * @param int $pageId - * @param string $pageText - * * @return bool indicating success */ public function insertPage(int $pageId, string $pageText = "") : bool{ @@ -158,9 +140,6 @@ class WritableBook extends Item{ /** * Switches the text of two pages with each other. * - * @param int $pageId1 - * @param int $pageId2 - * * @return bool indicating success */ public function swapPages(int $pageId1, int $pageId2) : bool{ @@ -201,7 +180,6 @@ class WritableBook extends Item{ } /** - * * @param CompoundTag[] $pages */ public function setPages(array $pages) : void{ diff --git a/src/pocketmine/item/WrittenBook.php b/src/pocketmine/item/WrittenBook.php index 5666e6c6be..13137ab052 100644 --- a/src/pocketmine/item/WrittenBook.php +++ b/src/pocketmine/item/WrittenBook.php @@ -45,8 +45,6 @@ class WrittenBook extends WritableBook{ /** * Returns the generation of the book. * Generations higher than 1 can not be copied. - * - * @return int */ public function getGeneration() : int{ return $this->getNamedTag()->getInt(self::TAG_GENERATION, -1); @@ -54,8 +52,6 @@ class WrittenBook extends WritableBook{ /** * Sets the generation of a book. - * - * @param int $generation */ public function setGeneration(int $generation) : void{ if($generation < 0 or $generation > 3){ @@ -70,8 +66,6 @@ class WrittenBook extends WritableBook{ * Returns the author of this book. * This is not a reliable way to get the name of the player who signed this book. * The author can be set to anything when signing a book. - * - * @return string */ public function getAuthor() : string{ return $this->getNamedTag()->getString(self::TAG_AUTHOR, ""); @@ -79,8 +73,6 @@ class WrittenBook extends WritableBook{ /** * Sets the author of this book. - * - * @param string $authorName */ public function setAuthor(string $authorName) : void{ $namedTag = $this->getNamedTag(); @@ -90,8 +82,6 @@ class WrittenBook extends WritableBook{ /** * Returns the title of this book. - * - * @return string */ public function getTitle() : string{ return $this->getNamedTag()->getString(self::TAG_TITLE, ""); @@ -99,8 +89,6 @@ class WrittenBook extends WritableBook{ /** * Sets the author of this book. - * - * @param string $title */ public function setTitle(string $title) : void{ $namedTag = $this->getNamedTag(); diff --git a/src/pocketmine/item/enchantment/Enchantment.php b/src/pocketmine/item/enchantment/Enchantment.php index 58dfba8418..4ba5e5d321 100644 --- a/src/pocketmine/item/enchantment/Enchantment.php +++ b/src/pocketmine/item/enchantment/Enchantment.php @@ -94,7 +94,10 @@ class Enchantment{ public const SLOT_ELYTRA = 0x4000; public const SLOT_TRIDENT = 0x8000; - /** @var \SplFixedArray|Enchantment[] */ + /** + * @var \SplFixedArray|Enchantment[] + * @phpstan-var \SplFixedArray + */ protected static $enchantments; public static function init() : void{ @@ -142,27 +145,18 @@ class Enchantment{ /** * Registers an enchantment type. - * - * @param Enchantment $enchantment */ public static function registerEnchantment(Enchantment $enchantment) : void{ self::$enchantments[$enchantment->getId()] = clone $enchantment; } - /** - * @param int $id - * - * @return Enchantment|null - */ public static function getEnchantment(int $id) : ?Enchantment{ + if($id < 0 or $id >= self::$enchantments->getSize()){ + return null; + } return self::$enchantments[$id] ?? null; } - /** - * @param string $name - * - * @return Enchantment|null - */ public static function getEnchantmentByName(string $name) : ?Enchantment{ $const = Enchantment::class . "::" . strtoupper($name); if(defined($const)){ @@ -184,14 +178,6 @@ class Enchantment{ /** @var int */ private $maxLevel; - /** - * @param int $id - * @param string $name - * @param int $rarity - * @param int $primaryItemFlags - * @param int $secondaryItemFlags - * @param int $maxLevel - */ public function __construct(int $id, string $name, int $rarity, int $primaryItemFlags, int $secondaryItemFlags, int $maxLevel){ $this->id = $id; $this->name = $name; @@ -203,7 +189,6 @@ class Enchantment{ /** * Returns the ID of this enchantment as per Minecraft PE - * @return int */ public function getId() : int{ return $this->id; @@ -211,7 +196,6 @@ class Enchantment{ /** * Returns a translation key for this enchantment's name. - * @return string */ public function getName() : string{ return $this->name; @@ -219,7 +203,6 @@ class Enchantment{ /** * Returns an int constant indicating how rare this enchantment type is. - * @return int */ public function getRarity() : int{ return $this->rarity; @@ -227,8 +210,6 @@ class Enchantment{ /** * Returns a bitset indicating what item types can have this item applied from an enchanting table. - * - * @return int */ public function getPrimaryItemFlags() : int{ return $this->primaryItemFlags; @@ -237,8 +218,6 @@ class Enchantment{ /** * Returns a bitset indicating what item types cannot have this item applied from an enchanting table, but can from * an anvil. - * - * @return int */ public function getSecondaryItemFlags() : int{ return $this->secondaryItemFlags; @@ -246,10 +225,6 @@ class Enchantment{ /** * Returns whether this enchantment can apply to the item type from an enchanting table. - * - * @param int $flag - * - * @return bool */ public function hasPrimaryItemType(int $flag) : bool{ return ($this->primaryItemFlags & $flag) !== 0; @@ -257,10 +232,6 @@ class Enchantment{ /** * Returns whether this enchantment can apply to the item type from an anvil, if it is not a primary item. - * - * @param int $flag - * - * @return bool */ public function hasSecondaryItemType(int $flag) : bool{ return ($this->secondaryItemFlags & $flag) !== 0; @@ -268,7 +239,6 @@ class Enchantment{ /** * Returns the maximum level of this enchantment that can be found on an enchantment table. - * @return int */ public function getMaxLevel() : int{ return $this->maxLevel; diff --git a/src/pocketmine/item/enchantment/EnchantmentEntry.php b/src/pocketmine/item/enchantment/EnchantmentEntry.php index edd2dffb88..50fd4301e2 100644 --- a/src/pocketmine/item/enchantment/EnchantmentEntry.php +++ b/src/pocketmine/item/enchantment/EnchantmentEntry.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\item\enchantment; - class EnchantmentEntry{ /** @var Enchantment[] */ @@ -35,8 +34,6 @@ class EnchantmentEntry{ /** * @param Enchantment[] $enchantments - * @param int $cost - * @param string $randomName */ public function __construct(array $enchantments, int $cost, string $randomName){ $this->enchantments = $enchantments; @@ -44,6 +41,9 @@ class EnchantmentEntry{ $this->randomName = $randomName; } + /** + * @return Enchantment[] + */ public function getEnchantments() : array{ return $this->enchantments; } diff --git a/src/pocketmine/item/enchantment/EnchantmentInstance.php b/src/pocketmine/item/enchantment/EnchantmentInstance.php index 2434ba5b87..33a44f4ac3 100644 --- a/src/pocketmine/item/enchantment/EnchantmentInstance.php +++ b/src/pocketmine/item/enchantment/EnchantmentInstance.php @@ -45,7 +45,6 @@ class EnchantmentInstance{ /** * Returns the type of this enchantment. - * @return Enchantment */ public function getType() : Enchantment{ return $this->enchantment; @@ -53,7 +52,6 @@ class EnchantmentInstance{ /** * Returns the type identifier of this enchantment instance. - * @return int */ public function getId() : int{ return $this->enchantment->getId(); @@ -61,7 +59,6 @@ class EnchantmentInstance{ /** * Returns the level of the enchantment. - * @return int */ public function getLevel() : int{ return $this->level; @@ -70,8 +67,6 @@ class EnchantmentInstance{ /** * Sets the level of the enchantment. * - * @param int $level - * * @return $this */ public function setLevel(int $level){ diff --git a/src/pocketmine/item/enchantment/EnchantmentList.php b/src/pocketmine/item/enchantment/EnchantmentList.php index ebec0a3f45..103d3c1a63 100644 --- a/src/pocketmine/item/enchantment/EnchantmentList.php +++ b/src/pocketmine/item/enchantment/EnchantmentList.php @@ -23,29 +23,22 @@ declare(strict_types=1); namespace pocketmine\item\enchantment; - class EnchantmentList{ - /** @var \SplFixedArray|EnchantmentEntry[] */ + /** + * @var \SplFixedArray|EnchantmentEntry[] + * @phpstan-var \SplFixedArray + */ private $enchantments; public function __construct(int $size){ $this->enchantments = new \SplFixedArray($size); } - /** - * @param int $slot - * @param EnchantmentEntry $entry - */ public function setSlot(int $slot, EnchantmentEntry $entry) : void{ $this->enchantments[$slot] = $entry; } - /** - * @param int $slot - * - * @return EnchantmentEntry - */ public function getSlot(int $slot) : EnchantmentEntry{ return $this->enchantments[$slot]; } diff --git a/src/pocketmine/item/enchantment/MeleeWeaponEnchantment.php b/src/pocketmine/item/enchantment/MeleeWeaponEnchantment.php index 6d2c8a6317..9b61b16640 100644 --- a/src/pocketmine/item/enchantment/MeleeWeaponEnchantment.php +++ b/src/pocketmine/item/enchantment/MeleeWeaponEnchantment.php @@ -34,28 +34,16 @@ abstract class MeleeWeaponEnchantment extends Enchantment{ /** * Returns whether this melee enchantment has an effect on the target entity. For example, Smite only applies to * undead mobs. - * - * @param Entity $victim - * - * @return bool */ abstract public function isApplicableTo(Entity $victim) : bool; /** * Returns the amount of additional damage caused by this enchantment to applicable targets. - * - * @param int $enchantmentLevel - * - * @return float */ abstract public function getDamageBonus(int $enchantmentLevel) : float; /** * Called after damaging the entity to apply any post damage effects to the target. - * - * @param Entity $attacker - * @param Entity $victim - * @param int $enchantmentLevel */ public function onPostAttack(Entity $attacker, Entity $victim, int $enchantmentLevel) : void{ diff --git a/src/pocketmine/item/enchantment/ProtectionEnchantment.php b/src/pocketmine/item/enchantment/ProtectionEnchantment.php index 9793f795ca..8fc603aa97 100644 --- a/src/pocketmine/item/enchantment/ProtectionEnchantment.php +++ b/src/pocketmine/item/enchantment/ProtectionEnchantment.php @@ -36,13 +36,6 @@ class ProtectionEnchantment extends Enchantment{ /** * ProtectionEnchantment constructor. * - * @param int $id - * @param string $name - * @param int $rarity - * @param int $primaryItemFlags - * @param int $secondaryItemFlags - * @param int $maxLevel - * @param float $typeModifier * @param int[]|null $applicableDamageTypes EntityDamageEvent::CAUSE_* constants which this enchantment type applies to, or null if it applies to all types of damage. */ public function __construct(int $id, string $name, int $rarity, int $primaryItemFlags, int $secondaryItemFlags, int $maxLevel, float $typeModifier, ?array $applicableDamageTypes){ @@ -56,7 +49,6 @@ class ProtectionEnchantment extends Enchantment{ /** * Returns the multiplier by which this enchantment type's EPF increases with each enchantment level. - * @return float */ public function getTypeModifier() : float{ return $this->typeModifier; @@ -64,10 +56,6 @@ class ProtectionEnchantment extends Enchantment{ /** * Returns the base EPF this enchantment type offers for the given enchantment level. - * - * @param int $level - * - * @return int */ public function getProtectionFactor(int $level) : int{ return (int) floor((6 + $level ** 2) * $this->typeModifier / 3); @@ -75,10 +63,6 @@ class ProtectionEnchantment extends Enchantment{ /** * Returns whether this enchantment type offers protection from the specified damage source's cause. - * - * @param EntityDamageEvent $event - * - * @return bool */ public function isApplicable(EntityDamageEvent $event) : bool{ return $this->applicableDamageTypes === null or isset($this->applicableDamageTypes[$event->getCause()]); diff --git a/src/pocketmine/lang/BaseLang.php b/src/pocketmine/lang/BaseLang.php index 0ec3a68f25..c869909f5b 100644 --- a/src/pocketmine/lang/BaseLang.php +++ b/src/pocketmine/lang/BaseLang.php @@ -43,6 +43,10 @@ class BaseLang{ public const FALLBACK_LANGUAGE = "eng"; + /** + * @return string[] + * @phpstan-return array + */ public static function getLanguageList(string $path = "") : array{ if($path === ""){ $path = \pocketmine\PATH . "src/pocketmine/lang/locale/"; @@ -52,7 +56,7 @@ class BaseLang{ $allFiles = scandir($path, SCANDIR_SORT_NONE); if($allFiles !== false){ - $files = array_filter($allFiles, function($filename){ + $files = array_filter($allFiles, function(string $filename) : bool{ return substr($filename, -4) === ".ini"; }); @@ -105,6 +109,11 @@ class BaseLang{ return $this->langName; } + /** + * @param string[] $d reference parameter + * + * @return bool + */ protected static function loadLang(string $path, array &$d){ if(file_exists($path)){ $d = array_map('\stripcslashes', parse_ini_file($path, false, INI_SCANNER_RAW)); @@ -115,15 +124,11 @@ class BaseLang{ } /** - * @param string $str * @param (float|int|string)[] $params - * @param string|null $onlyPrefix - * - * @return string */ public function translateString(string $str, array $params = [], string $onlyPrefix = null) : string{ $baseText = $this->get($str); - $baseText = $this->parseTranslation(($baseText !== null and ($onlyPrefix === null or strpos($str, $onlyPrefix) === 0)) ? $baseText : $str, $onlyPrefix); + $baseText = $this->parseTranslation(($onlyPrefix === null or strpos($str, $onlyPrefix) === 0) ? $baseText : $str, $onlyPrefix); foreach($params as $i => $p){ $baseText = str_replace("{%$i}", $this->parseTranslation((string) $p), $baseText, $onlyPrefix); @@ -132,6 +137,9 @@ class BaseLang{ return $baseText; } + /** + * @return string + */ public function translate(TextContainer $c){ if($c instanceof TranslationContainer){ $baseText = $this->internalGet($c->getText()); @@ -148,8 +156,6 @@ class BaseLang{ } /** - * @param string $id - * * @return string|null */ public function internalGet(string $id){ @@ -162,11 +168,6 @@ class BaseLang{ return null; } - /** - * @param string $id - * - * @return string - */ public function get(string $id) : string{ if(isset($this->lang[$id])){ return $this->lang[$id]; @@ -177,12 +178,6 @@ class BaseLang{ return $id; } - /** - * @param string $text - * @param string|null $onlyPrefix - * - * @return string - */ protected function parseTranslation(string $text, string $onlyPrefix = null) : string{ $newString = ""; diff --git a/src/pocketmine/lang/TextContainer.php b/src/pocketmine/lang/TextContainer.php index 99504d0aea..e0a32acc92 100644 --- a/src/pocketmine/lang/TextContainer.php +++ b/src/pocketmine/lang/TextContainer.php @@ -28,30 +28,21 @@ class TextContainer{ /** @var string $text */ protected $text; - /** - * @param string $text - */ public function __construct(string $text){ $this->text = $text; } /** - * @param string $text + * @return void */ public function setText(string $text){ $this->text = $text; } - /** - * @return string - */ public function getText() : string{ return $this->text; } - /** - * @return string - */ public function __toString() : string{ return $this->getText(); } diff --git a/src/pocketmine/lang/TranslationContainer.php b/src/pocketmine/lang/TranslationContainer.php index 69461b281d..b540d058e6 100644 --- a/src/pocketmine/lang/TranslationContainer.php +++ b/src/pocketmine/lang/TranslationContainer.php @@ -31,7 +31,6 @@ class TranslationContainer extends TextContainer{ protected $params = []; /** - * @param string $text * @param (float|int|string)[] $params */ public function __construct(string $text, array $params = []){ @@ -48,8 +47,6 @@ class TranslationContainer extends TextContainer{ } /** - * @param int $i - * * @return string|null */ public function getParameter(int $i){ @@ -57,8 +54,7 @@ class TranslationContainer extends TextContainer{ } /** - * @param int $i - * @param string $str + * @return void */ public function setParameter(int $i, string $str){ if($i < 0 or $i > count($this->params)){ //Intended, allow to set the last @@ -69,7 +65,9 @@ class TranslationContainer extends TextContainer{ } /** - * @param string[] $params + * @param (float|int|string)[] $params + * + * @return void */ public function setParameters(array $params){ $i = 0; diff --git a/src/pocketmine/level/ChunkLoader.php b/src/pocketmine/level/ChunkLoader.php index 144b551927..da3baff0b8 100644 --- a/src/pocketmine/level/ChunkLoader.php +++ b/src/pocketmine/level/ChunkLoader.php @@ -42,15 +42,11 @@ interface ChunkLoader{ /** * Returns the ChunkLoader id. * Call Level::generateChunkLoaderId($this) to generate and save it - * - * @return int */ public function getLoaderId() : int; /** * Returns if the chunk loader is currently active - * - * @return bool */ public function isLoaderActive() : bool; @@ -77,22 +73,21 @@ interface ChunkLoader{ /** * This method will be called when a Chunk is replaced by a new one * - * @param Chunk $chunk + * @return void */ public function onChunkChanged(Chunk $chunk); /** * This method will be called when a registered chunk is loaded * - * @param Chunk $chunk + * @return void */ public function onChunkLoaded(Chunk $chunk); - /** * This method will be called when a registered chunk is unloaded * - * @param Chunk $chunk + * @return void */ public function onChunkUnloaded(Chunk $chunk); @@ -100,7 +95,7 @@ interface ChunkLoader{ * This method will be called when a registered chunk is populated * Usually it'll be sent with another call to onChunkChanged() * - * @param Chunk $chunk + * @return void */ public function onChunkPopulated(Chunk $chunk); @@ -108,6 +103,8 @@ interface ChunkLoader{ * This method will be called when a block changes in a registered chunk * * @param Block|Vector3 $block + * + * @return void */ public function onBlockChanged(Vector3 $block); diff --git a/src/pocketmine/level/ChunkManager.php b/src/pocketmine/level/ChunkManager.php index ce17eec12e..ea526e0bcc 100644 --- a/src/pocketmine/level/ChunkManager.php +++ b/src/pocketmine/level/ChunkManager.php @@ -29,10 +29,6 @@ interface ChunkManager{ /** * Gets the raw block id. * - * @param int $x - * @param int $y - * @param int $z - * * @return int 0-255 */ public function getBlockIdAt(int $x, int $y, int $z) : int; @@ -40,20 +36,15 @@ interface ChunkManager{ /** * Sets the raw block id. * - * @param int $x - * @param int $y - * @param int $z * @param int $id 0-255 + * + * @return void */ public function setBlockIdAt(int $x, int $y, int $z, int $id); /** * Gets the raw block metadata * - * @param int $x - * @param int $y - * @param int $z - * * @return int 0-15 */ public function getBlockDataAt(int $x, int $y, int $z) : int; @@ -61,92 +52,59 @@ interface ChunkManager{ /** * Sets the raw block metadata. * - * @param int $x - * @param int $y - * @param int $z * @param int $data 0-15 + * + * @return void */ public function setBlockDataAt(int $x, int $y, int $z, int $data); /** * Returns the raw block light level - * - * @param int $x - * @param int $y - * @param int $z - * - * @return int */ public function getBlockLightAt(int $x, int $y, int $z) : int; /** * Sets the raw block light level * - * @param int $x - * @param int $y - * @param int $z - * @param int $level + * @return void */ public function setBlockLightAt(int $x, int $y, int $z, int $level); /** * Returns the highest amount of sky light can reach the specified coordinates. - * - * @param int $x - * @param int $y - * @param int $z - * - * @return int */ public function getBlockSkyLightAt(int $x, int $y, int $z) : int; /** * Sets the raw block sky light level. * - * @param int $x - * @param int $y - * @param int $z - * @param int $level + * @return void */ public function setBlockSkyLightAt(int $x, int $y, int $z, int $level); /** - * @param int $chunkX - * @param int $chunkZ - * * @return Chunk|null */ public function getChunk(int $chunkX, int $chunkZ); /** - * @param int $chunkX - * @param int $chunkZ - * @param Chunk|null $chunk + * @return void */ public function setChunk(int $chunkX, int $chunkZ, Chunk $chunk = null); /** * Gets the level seed - * - * @return int */ public function getSeed() : int; /** * Returns the height of the world - * @return int */ public function getWorldHeight() : int; /** * Returns whether the specified coordinates are within the valid world boundaries, taking world format limitations * into account. - * - * @param int $x - * @param int $y - * @param int $z - * - * @return bool */ public function isInWorld(int $x, int $y, int $z) : bool; } diff --git a/src/pocketmine/level/Explosion.php b/src/pocketmine/level/Explosion.php index d3906790eb..4af9743650 100644 --- a/src/pocketmine/level/Explosion.php +++ b/src/pocketmine/level/Explosion.php @@ -60,16 +60,14 @@ class Explosion{ public $affectedBlocks = []; /** @var float */ public $stepLen = 0.3; - /** @var Entity|Block */ + /** @var Entity|Block|null */ private $what; /** @var SubChunkIteratorManager */ private $subChunkHandler; /** - * @param Position $center - * @param float $size - * @param Entity|Block $what + * @param Entity|Block|null $what */ public function __construct(Position $center, float $size, $what = null){ if(!$center->isValid()){ @@ -88,10 +86,8 @@ class Explosion{ } /** - * Calculates which blocks will be destroyed by this explosion. If explodeB() is called without calling this, no blocks + * Calculates which blocks will be destroyed by this explosion. If explodeB() is called without calling this, no blocks * will be destroyed. - * - * @return bool */ public function explodeA() : bool{ if($this->size < 0.1){ @@ -104,7 +100,7 @@ class Explosion{ $currentChunk = null; $currentSubChunk = null; - $mRays = (int) ($this->rays - 1); + $mRays = $this->rays - 1; for($i = 0; $i < $this->rays; ++$i){ for($j = 0; $j < $this->rays; ++$j){ for($k = 0; $k < $this->rays; ++$k){ @@ -123,6 +119,10 @@ class Explosion{ $vBlock->y = $pointerY >= $y ? $y : $y - 1; $vBlock->z = $pointerZ >= $z ? $z : $z - 1; + $pointerX += $vector->x; + $pointerY += $vector->y; + $pointerZ += $vector->z; + if(!$this->subChunkHandler->moveTo($vBlock->x, $vBlock->y, $vBlock->z)){ continue; } @@ -137,10 +137,6 @@ class Explosion{ } } } - - $pointerX += $vector->x; - $pointerY += $vector->y; - $pointerZ += $vector->z; } } } @@ -153,8 +149,6 @@ class Explosion{ /** * Executes the explosion's effects on the world. This includes destroying blocks (if any), harming and knocking back entities, * and creating sounds and particles. - * - * @return bool */ public function explodeB() : bool{ $send = []; @@ -208,7 +202,6 @@ class Explosion{ } } - $air = ItemFactory::get(Item::AIR); foreach($this->affectedBlocks as $block){ diff --git a/src/pocketmine/level/Level.php b/src/pocketmine/level/Level.php index 3bd9c5a45c..c298ec4b87 100644 --- a/src/pocketmine/level/Level.php +++ b/src/pocketmine/level/Level.php @@ -120,7 +120,9 @@ use const PHP_INT_MIN; class Level implements ChunkManager, Metadatable{ + /** @var int */ private static $levelIdCounter = 1; + /** @var int */ private static $chunkLoaderCounter = 1; public const Y_MASK = 0xFF; @@ -245,7 +247,10 @@ class Level implements ChunkManager, Metadatable{ /** @var Vector3 */ private $temporalVector; - /** @var \SplFixedArray */ + /** + * @var \SplFixedArray + * @phpstan-var \SplFixedArray + */ private $blockStates; /** @var int */ @@ -260,7 +265,7 @@ class Level implements ChunkManager, Metadatable{ /** @var bool */ private $clearChunksOnTick; /** @var \SplFixedArray */ - private $randomTickBlocks = null; + private $randomTickBlocks; /** @var LevelTimings */ public $timings; @@ -300,12 +305,6 @@ class Level implements ChunkManager, Metadatable{ /** * Computes a small index relative to chunk base from the given coordinates. - * - * @param int $x - * @param int $y - * @param int $z - * - * @return int */ public static function chunkBlockHash(int $x, int $y, int $z) : int{ return ($y << 8) | (($z & 0xf) << 4) | ($x & 0xf); @@ -317,11 +316,6 @@ class Level implements ChunkManager, Metadatable{ $z = ($hash & 0xFFFFFFF) << 36 >> 36; } - /** - * @param int $hash - * @param int|null $x - * @param int|null $z - */ public static function getXZ(int $hash, ?int &$x, ?int &$z) : void{ $x = $hash >> 32; $z = ($hash & 0xFFFFFFFF) << 32 >> 32; @@ -335,11 +329,6 @@ class Level implements ChunkManager, Metadatable{ } } - /** - * @param string $str - * - * @return int - */ public static function getDifficultyFromString(string $str) : int{ switch(strtolower(trim($str))){ case "0": @@ -368,10 +357,6 @@ class Level implements ChunkManager, Metadatable{ /** * Init the default level data - * - * @param Server $server - * @param string $name - * @param LevelProvider $provider */ public function __construct(Server $server, string $name, LevelProvider $provider){ $this->blockStates = BlockFactory::getBlockStatesArray(); @@ -420,7 +405,6 @@ class Level implements ChunkManager, Metadatable{ /** * @deprecated - * @return int */ public function getTickRate() : int{ return 1; @@ -432,7 +416,8 @@ class Level implements ChunkManager, Metadatable{ /** * @deprecated does nothing - * @param int $tickRate + * + * @return void */ public function setTickRate(int $tickRate){ @@ -443,6 +428,9 @@ class Level implements ChunkManager, Metadatable{ $this->server->getAsyncPool()->submitTaskToWorker(new GeneratorRegisterTask($this, $this->generator, $this->provider->getGeneratorOptions()), $worker); } + /** + * @return void + */ public function unregisterGenerator(){ $pool = $this->server->getAsyncPool(); foreach($pool->getRunningWorkers() as $i){ @@ -476,6 +464,9 @@ class Level implements ChunkManager, Metadatable{ return $this->closed; } + /** + * @return void + */ public function close(){ if($this->closed){ throw new \InvalidStateException("Tried to close a world which is already closed"); @@ -498,12 +489,17 @@ class Level implements ChunkManager, Metadatable{ $this->closed = true; } + /** + * @param Player[]|null $players + * + * @return void + */ public function addSound(Sound $sound, array $players = null){ $pk = $sound->encode(); if(!is_array($pk)){ $pk = [$pk]; } - if(!empty($pk)){ + if(count($pk) > 0){ if($players === null){ foreach($pk as $e){ $this->broadcastPacketToViewers($sound, $e); @@ -514,12 +510,17 @@ class Level implements ChunkManager, Metadatable{ } } + /** + * @param Player[]|null $players + * + * @return void + */ public function addParticle(Particle $particle, array $players = null){ $pk = $particle->encode(); if(!is_array($pk)){ $pk = [$pk]; } - if(!empty($pk)){ + if(count($pk) > 0){ if($players === null){ foreach($pk as $e){ $this->broadcastPacketToViewers($particle, $e); @@ -534,8 +535,8 @@ class Level implements ChunkManager, Metadatable{ * Broadcasts a LevelEvent to players in the area. This could be sound, particles, weather changes, etc. * * @param Vector3|null $pos If null, broadcasts to every player in the Level - * @param int $evid - * @param int $data + * + * @return void */ public function broadcastLevelEvent(?Vector3 $pos, int $evid, int $data = 0){ $pk = new LevelEventPacket(); @@ -553,12 +554,9 @@ class Level implements ChunkManager, Metadatable{ /** * Broadcasts a LevelSoundEvent to players in the area. * - * @param Vector3 $pos - * @param int $soundId - * @param int $extraData - * @param int $entityTypeId - * @param bool $isBabyMob * @param bool $disableRelativeVolume If true, all players receiving this sound-event will hear the sound at full volume regardless of distance + * + * @return void */ public function broadcastLevelSoundEvent(Vector3 $pos, int $soundId, int $extraData = -1, int $entityTypeId = -1, bool $isBabyMob = false, bool $disableRelativeVolume = false){ $pk = new LevelSoundEventPacket(); @@ -575,6 +573,9 @@ class Level implements ChunkManager, Metadatable{ return $this->autoSave; } + /** + * @return void + */ public function setAutoSave(bool $value){ $this->autoSave = $value; } @@ -587,7 +588,6 @@ class Level implements ChunkManager, Metadatable{ * * @param bool $force default false, force unload of default level * - * @return bool * @throws \InvalidStateException if trying to unload a level during level tick */ public function unload(bool $force = false) : bool{ @@ -612,8 +612,8 @@ class Level implements ChunkManager, Metadatable{ foreach($this->getPlayers() as $player){ if($this === $defaultLevel or $defaultLevel === null){ $player->close($player->getLeaveMessage(), "Forced default world unload"); - }elseif($defaultLevel instanceof Level){ - $player->teleport($this->server->getDefaultLevel()->getSafeSpawn()); + }else{ + $player->teleport($defaultLevel->getSafeSpawn()); } } @@ -634,9 +634,6 @@ class Level implements ChunkManager, Metadatable{ * * Returns a list of players who have the target chunk within their view distance. * - * @param int $chunkX - * @param int $chunkZ - * * @return Player[] */ public function getChunkPlayers(int $chunkX, int $chunkZ) : array{ @@ -646,9 +643,6 @@ class Level implements ChunkManager, Metadatable{ /** * Gets the chunk loaders being used in a specific chunk * - * @param int $chunkX - * @param int $chunkZ - * * @return ChunkLoader[] */ public function getChunkLoaders(int $chunkX, int $chunkZ) : array{ @@ -657,7 +651,6 @@ class Level implements ChunkManager, Metadatable{ /** * Returns an array of players who have the target position within their view distance. - * @param Vector3 $pos * * @return Player[] */ @@ -669,9 +662,7 @@ class Level implements ChunkManager, Metadatable{ * Queues a DataPacket to be sent to all players using the chunk at the specified X/Z coordinates at the end of the * current tick. * - * @param int $chunkX - * @param int $chunkZ - * @param DataPacket $packet + * @return void */ public function addChunkPacket(int $chunkX, int $chunkZ, DataPacket $packet){ if(!isset($this->chunkPackets[$index = Level::chunkHash($chunkX, $chunkZ)])){ @@ -683,9 +674,6 @@ class Level implements ChunkManager, Metadatable{ /** * Broadcasts a packet to every player who has the target position within their view distance. - * - * @param Vector3 $pos - * @param DataPacket $packet */ public function broadcastPacketToViewers(Vector3 $pos, DataPacket $packet) : void{ $this->addChunkPacket($pos->getFloorX() >> 4, $pos->getFloorZ() >> 4, $packet); @@ -693,8 +681,6 @@ class Level implements ChunkManager, Metadatable{ /** * Broadcasts a packet to every player in the level. - * - * @param DataPacket $packet */ public function broadcastGlobalPacket(DataPacket $packet) : void{ $this->globalPackets[] = $packet; @@ -703,13 +689,14 @@ class Level implements ChunkManager, Metadatable{ /** * @deprecated * @see Level::broadcastGlobalPacket() - * - * @param DataPacket $packet */ public function addGlobalPacket(DataPacket $packet) : void{ $this->globalPackets[] = $packet; } + /** + * @return void + */ public function registerChunkLoader(ChunkLoader $loader, int $chunkX, int $chunkZ, bool $autoLoad = true){ $loaderId = $loader->getLoaderId(); @@ -739,6 +726,9 @@ class Level implements ChunkManager, Metadatable{ } } + /** + * @return void + */ public function unregisterChunkLoader(ChunkLoader $loader, int $chunkX, int $chunkZ){ $chunkHash = Level::chunkHash($chunkX, $chunkZ); $loaderId = $loader->getLoaderId(); @@ -762,6 +752,8 @@ class Level implements ChunkManager, Metadatable{ * @internal * * @param Player ...$targets If empty, will send to all players in the level. + * + * @return void */ public function sendTime(Player ...$targets){ $pk = new SetTimePacket(); @@ -773,8 +765,7 @@ class Level implements ChunkManager, Metadatable{ /** * @internal * - * @param int $currentTick - * + * @return void */ public function doTick(int $currentTick){ if($this->closed){ @@ -881,7 +872,7 @@ class Level implements ChunkManager, Metadatable{ if(count($this->changedBlocks) > 0){ if(count($this->players) > 0){ foreach($this->changedBlocks as $index => $blocks){ - if(empty($blocks)){ //blocks can be set normally and then later re-set with direct send + if(count($blocks) === 0){ //blocks can be set normally and then later re-set with direct send continue; } unset($this->chunkCache[$index]); @@ -909,8 +900,8 @@ class Level implements ChunkManager, Metadatable{ $this->checkSleep(); } - if(!empty($this->globalPackets)){ - if(!empty($this->players)){ + if(count($this->globalPackets) > 0){ + if(count($this->players) > 0){ $this->server->batchPackets($this->players, $this->globalPackets); } $this->globalPackets = []; @@ -927,6 +918,9 @@ class Level implements ChunkManager, Metadatable{ $this->chunkPackets = []; } + /** + * @return void + */ public function checkSleep(){ if(count($this->players) === 0){ return; @@ -960,8 +954,8 @@ class Level implements ChunkManager, Metadatable{ /** * @param Player[] $target * @param Vector3[] $blocks - * @param int $flags - * @param bool $optimizeRebuilds + * + * @return void */ public function sendBlocks(array $target, array $blocks, int $flags = UpdateBlockPacket::FLAG_NONE, bool $optimizeRebuilds = false){ $packets = []; @@ -1021,6 +1015,9 @@ class Level implements ChunkManager, Metadatable{ $this->server->batchPackets($target, $packets, false, false); } + /** + * @return void + */ public function clearCache(bool $force = false){ if($force){ $this->chunkCache = []; @@ -1037,23 +1034,35 @@ class Level implements ChunkManager, Metadatable{ } } + /** + * @return void + */ public function clearChunkCache(int $chunkX, int $chunkZ){ unset($this->chunkCache[Level::chunkHash($chunkX, $chunkZ)]); } + /** + * @phpstan-return \SplFixedArray + */ public function getRandomTickedBlocks() : \SplFixedArray{ return $this->randomTickBlocks; } + /** + * @return void + */ public function addRandomTickedBlock(int $id){ $this->randomTickBlocks[$id] = BlockFactory::get($id); } + /** + * @return void + */ public function removeRandomTickedBlock(int $id){ $this->randomTickBlocks[$id] = null; } - private function tickChunks(){ + private function tickChunks() : void{ if($this->chunksPerTick <= 0 or count($this->loaders) === 0){ $this->chunkTickList = []; return; @@ -1101,7 +1110,6 @@ class Level implements ChunkManager, Metadatable{ $entity->scheduleUpdate(); } - foreach($chunk->getSubChunks() as $Y => $subChunk){ if(!($subChunk instanceof EmptySubChunk)){ $k = mt_rand(0, 0xfffffffff); //36 bits @@ -1135,15 +1143,13 @@ class Level implements ChunkManager, Metadatable{ } } + /** + * @return mixed[] + */ public function __debugInfo() : array{ return []; } - /** - * @param bool $force - * - * @return bool - */ public function save(bool $force = false) : bool{ if(!$this->getAutoSave() and !$force){ @@ -1161,6 +1167,9 @@ class Level implements ChunkManager, Metadatable{ return true; } + /** + * @return void + */ public function saveChunks(){ $this->timings->syncChunkSaveTimer->startTiming(); try{ @@ -1179,8 +1188,7 @@ class Level implements ChunkManager, Metadatable{ * Schedules a block update to be executed after the specified number of ticks. * Blocks will be updated with the scheduled update type. * - * @param Vector3 $pos - * @param int $delay + * @return void */ public function scheduleDelayedBlockUpdate(Vector3 $pos, int $delay){ if( @@ -1197,7 +1205,7 @@ class Level implements ChunkManager, Metadatable{ * Schedules the blocks around the specified position to be updated at the end of this tick. * Blocks will be updated with the normal update type. * - * @param Vector3 $pos + * @return void */ public function scheduleNeighbourBlockUpdates(Vector3 $pos){ $pos = $pos->floor(); @@ -1211,9 +1219,6 @@ class Level implements ChunkManager, Metadatable{ } /** - * @param AxisAlignedBB $bb - * @param bool $targetFirst - * * @return Block[] */ public function getCollisionBlocks(AxisAlignedBB $bb, bool $targetFirst = false) : array{ @@ -1250,15 +1255,9 @@ class Level implements ChunkManager, Metadatable{ } } - return $collides; } - /** - * @param Vector3 $pos - * - * @return bool - */ public function isFullBlock(Vector3 $pos) : bool{ if($pos instanceof Block){ if($pos->isSolid()){ @@ -1273,10 +1272,6 @@ class Level implements ChunkManager, Metadatable{ } /** - * @param Entity $entity - * @param AxisAlignedBB $bb - * @param bool $entities - * * @return AxisAlignedBB[] */ public function getCollisionCubes(Entity $entity, AxisAlignedBB $bb, bool $entities = true) : array{ @@ -1329,8 +1324,6 @@ class Level implements ChunkManager, Metadatable{ /** * Computes the percentage of a circle away from noon the sun is currently at. This can be multiplied by 2 * M_PI to * get an angle in radians, or by 360 to get an angle in degrees. - * - * @return float */ public function computeSunAnglePercentage() : float{ $timeProgress = ($this->time % 24000) / 24000; @@ -1347,7 +1340,6 @@ class Level implements ChunkManager, Metadatable{ /** * Returns the percentage of a circle away from noon the sun is currently at. - * @return float */ public function getSunAnglePercentage() : float{ return $this->sunAnglePercentage; @@ -1355,7 +1347,6 @@ class Level implements ChunkManager, Metadatable{ /** * Returns the current sun angle in radians. - * @return float */ public function getSunAngleRadians() : float{ return $this->sunAnglePercentage * 2 * M_PI; @@ -1363,7 +1354,6 @@ class Level implements ChunkManager, Metadatable{ /** * Returns the current sun angle in degrees. - * @return float */ public function getSunAngleDegrees() : float{ return $this->sunAnglePercentage * 360.0; @@ -1372,8 +1362,6 @@ class Level implements ChunkManager, Metadatable{ /** * Computes how many points of sky light is subtracted based on the current time. Used to offset raw chunk sky light * to get a real light value. - * - * @return int */ public function computeSkyLightReduction() : int{ $percentage = max(0, min(1, -(cos($this->getSunAngleRadians()) * 2 - 0.5))); @@ -1385,7 +1373,6 @@ class Level implements ChunkManager, Metadatable{ /** * Returns how many points of sky light is subtracted based on the current time. - * @return int */ public function getSkyLightReduction() : int{ return $this->skyLightReduction; @@ -1394,10 +1381,6 @@ class Level implements ChunkManager, Metadatable{ /** * Returns the sky light level at the specified coordinates, offset by the current time and weather. * - * @param int $x - * @param int $y - * @param int $z - * * @return int 0-15 */ public function getRealBlockSkyLightAt(int $x, int $y, int $z) : int{ @@ -1406,10 +1389,6 @@ class Level implements ChunkManager, Metadatable{ } /** - * @param int $x - * @param int $y - * @param int $z - * * @return int bitmap, (id << 4) | data */ public function getFullBlock(int $x, int $y, int $z) : int{ @@ -1431,11 +1410,8 @@ class Level implements ChunkManager, Metadatable{ * Note: If you're using this for performance-sensitive code, and you're guaranteed to be supplying ints in the * specified vector, consider using {@link getBlockAt} instead for better performance. * - * @param Vector3 $pos * @param bool $cached Whether to use the block cache for getting the block (faster, but may be inaccurate) * @param bool $addToCache Whether to cache the block object created by this method call. - * - * @return Block */ public function getBlock(Vector3 $pos, bool $cached = true, bool $addToCache = true) : Block{ return $this->getBlockAt((int) floor($pos->x), (int) floor($pos->y), (int) floor($pos->z), $cached, $addToCache); @@ -1447,13 +1423,8 @@ class Level implements ChunkManager, Metadatable{ * Note for plugin developers: If you are using this method a lot (thousands of times for many positions for * example), you may want to set addToCache to false to avoid using excessive amounts of memory. * - * @param int $x - * @param int $y - * @param int $z * @param bool $cached Whether to use the block cache for getting the block (faster, but may be inaccurate) * @param bool $addToCache Whether to cache the block object created by this method call. - * - * @return Block */ public function getBlockAt(int $x, int $y, int $z, bool $cached = true, bool $addToCache = true) : Block{ $fullState = 0; @@ -1489,6 +1460,9 @@ class Level implements ChunkManager, Metadatable{ return $block; } + /** + * @return void + */ public function updateAllLight(Vector3 $pos){ $this->updateBlockSkyLight($pos->x, $pos->y, $pos->z); $this->updateBlockLight($pos->x, $pos->y, $pos->z); @@ -1496,12 +1470,6 @@ class Level implements ChunkManager, Metadatable{ /** * Returns the highest block light level available in the positions adjacent to the specified block coordinates. - * - * @param int $x - * @param int $y - * @param int $z - * - * @return int */ public function getHighestAdjacentBlockSkyLight(int $x, int $y, int $z) : int{ return max([ @@ -1514,6 +1482,9 @@ class Level implements ChunkManager, Metadatable{ ]); } + /** + * @return void + */ public function updateBlockSkyLight(int $x, int $y, int $z){ $this->timings->doBlockSkyLightUpdates->startTiming(); @@ -1556,12 +1527,6 @@ class Level implements ChunkManager, Metadatable{ /** * Returns the highest block light level available in the positions adjacent to the specified block coordinates. - * - * @param int $x - * @param int $y - * @param int $z - * - * @return int */ public function getHighestAdjacentBlockLight(int $x, int $y, int $z) : int{ return max([ @@ -1574,6 +1539,9 @@ class Level implements ChunkManager, Metadatable{ ]); } + /** + * @return void + */ public function updateBlockLight(int $x, int $y, int $z){ $this->timings->doBlockLightUpdates->startTiming(); @@ -1615,10 +1583,7 @@ class Level implements ChunkManager, Metadatable{ * If $update is true, it'll get the neighbour blocks (6 sides) and update them. * If you are doing big changes, you might want to set this to false, then update manually. * - * @param Vector3 $pos - * @param Block $block * @param bool $direct @deprecated - * @param bool $update * * @return bool Whether the block has been updated or not */ @@ -1685,11 +1650,6 @@ class Level implements ChunkManager, Metadatable{ } /** - * @param Vector3 $source - * @param Item $item - * @param Vector3 $motion - * @param int $delay - * * @return ItemEntity|null */ public function dropItem(Vector3 $source, Item $item, Vector3 $motion = null, int $delay = 10){ @@ -1716,9 +1676,6 @@ class Level implements ChunkManager, Metadatable{ /** * Drops XP orbs into the world for the specified amount, splitting the amount into several orbs if necessary. * - * @param Vector3 $pos - * @param int $amount - * * @return ExperienceOrb[] */ public function dropExperience(Vector3 $pos, int $amount) : array{ @@ -1752,9 +1709,6 @@ class Level implements ChunkManager, Metadatable{ * Checks if the level spawn protection radius will prevent the player from using items or building at the specified * Vector3 position. * - * @param Player $player - * @param Vector3 $vector - * * @return bool true if spawn protection cancelled the action, false if not. */ public function checkSpawnProtection(Player $player, Vector3 $vector) : bool{ @@ -1775,12 +1729,7 @@ class Level implements ChunkManager, Metadatable{ * Tries to break a block using a item, including Player time checks if available * It'll try to lower the durability if Item is a tool, and set it to Air if broken. * - * @param Vector3 $vector - * @param Item &$item (if null, can break anything) - * @param Player $player - * @param bool $createParticles - * - * @return bool + * @param Item $item reference parameter (if null, can break anything) */ public function useBreakOn(Vector3 $vector, Item &$item = null, Player $player = null, bool $createParticles = false) : bool{ $target = $this->getBlock($vector); @@ -1845,7 +1794,7 @@ class Level implements ChunkManager, Metadatable{ $item->onDestroyBlock($target); - if(!empty($drops)){ + if(count($drops) > 0){ $dropPos = $target->add(0.5, 0.5, 0.5); foreach($drops as $drop){ if(!$drop->isNull()){ @@ -1885,14 +1834,8 @@ class Level implements ChunkManager, Metadatable{ /** * Uses a item on a position and face, placing it or activating the block * - * @param Vector3 $vector - * @param Item $item - * @param int $face - * @param Vector3|null $clickVector * @param Player|null $player default null * @param bool $playSound Whether to play a block-place sound if the block was placed successfully. - * - * @return bool */ public function useItemOn(Vector3 $vector, Item &$item, int $face, Vector3 $clickVector = null, Player $player = null, bool $playSound = false) : bool{ $blockClicked = $this->getBlock($vector); @@ -1949,7 +1892,7 @@ class Level implements ChunkManager, Metadatable{ if($hand->isSolid()){ foreach($hand->getCollisionBoxes() as $collisionBox){ - if(!empty($this->getCollidingEntities($collisionBox))){ + if(count($this->getCollidingEntities($collisionBox)) > 0){ return false; //Entity in block } @@ -1964,7 +1907,6 @@ class Level implements ChunkManager, Metadatable{ } } - if($player !== null){ $ev = new BlockPlaceEvent($player, $hand, $blockReplace, $blockClicked, $item); if($this->checkSpawnProtection($player, $blockClicked)){ @@ -2009,8 +1951,6 @@ class Level implements ChunkManager, Metadatable{ } /** - * @param int $entityId - * * @return Entity|null */ public function getEntity(int $entityId){ @@ -2029,9 +1969,6 @@ class Level implements ChunkManager, Metadatable{ /** * Returns the entities colliding the current one inside the AxisAlignedBB * - * @param AxisAlignedBB $bb - * @param Entity|null $entity - * * @return Entity[] */ public function getCollidingEntities(AxisAlignedBB $bb, Entity $entity = null) : array{ @@ -2061,9 +1998,6 @@ class Level implements ChunkManager, Metadatable{ /** * Returns the entities near the current one inside the AxisAlignedBB * - * @param AxisAlignedBB $bb - * @param Entity $entity - * * @return Entity[] */ public function getNearbyEntities(AxisAlignedBB $bb, Entity $entity = null) : array{ @@ -2090,12 +2024,13 @@ class Level implements ChunkManager, Metadatable{ /** * Returns the closest Entity to the specified position, within the given radius. * - * @param Vector3 $pos - * @param float $maxDistance * @param string $entityType Class of entity to use for instanceof * @param bool $includeDead Whether to include entitites which are dead + * @phpstan-template TEntity of Entity + * @phpstan-param class-string $entityType * * @return Entity|null an entity of type $entityType, or null if not found + * @phpstan-return TEntity */ public function getNearestEntity(Vector3 $pos, float $maxDistance, string $entityType = Entity::class, bool $includeDead = false) : ?Entity{ assert(is_a($entityType, Entity::class, true)); @@ -2107,7 +2042,10 @@ class Level implements ChunkManager, Metadatable{ $currentTargetDistSq = $maxDistance ** 2; - /** @var Entity|null $currentTarget */ + /** + * @var Entity|null $currentTarget + * @phpstan-var TEntity|null $currentTarget + */ $currentTarget = null; for($x = $minX; $x <= $maxX; ++$x){ @@ -2128,7 +2066,6 @@ class Level implements ChunkManager, Metadatable{ return $currentTarget; } - /** * Returns a list of the Tile entities in this level * @@ -2139,8 +2076,6 @@ class Level implements ChunkManager, Metadatable{ } /** - * @param int $tileId - * * @return Tile|null */ public function getTileById(int $tileId){ @@ -2168,10 +2103,6 @@ class Level implements ChunkManager, Metadatable{ * * Note: This method wraps getTileAt(). If you're guaranteed to be passing integers, and you're using this method * in performance-sensitive code, consider using getTileAt() instead of this method for better performance. - * - * @param Vector3 $pos - * - * @return Tile|null */ public function getTile(Vector3 $pos) : ?Tile{ return $this->getTileAt((int) floor($pos->x), (int) floor($pos->y), (int) floor($pos->z)); @@ -2179,12 +2110,6 @@ class Level implements ChunkManager, Metadatable{ /** * Returns the tile at the specified x,y,z coordinates, or null if it does not exist. - * - * @param int $x - * @param int $y - * @param int $z - * - * @return Tile|null */ public function getTileAt(int $x, int $y, int $z) : ?Tile{ $chunk = $this->getChunk($x >> 4, $z >> 4); @@ -2199,9 +2124,6 @@ class Level implements ChunkManager, Metadatable{ /** * Returns a list of the entities on a given chunk * - * @param int $X - * @param int $Z - * * @return Entity[] */ public function getChunkEntities(int $X, int $Z) : array{ @@ -2211,9 +2133,6 @@ class Level implements ChunkManager, Metadatable{ /** * Gives a list of the Tile entities on a given chunk * - * @param int $X - * @param int $Z - * * @return Tile[] */ public function getChunkTiles(int $X, int $Z) : array{ @@ -2223,10 +2142,6 @@ class Level implements ChunkManager, Metadatable{ /** * Gets the raw block id. * - * @param int $x - * @param int $y - * @param int $z - * * @return int 0-255 */ public function getBlockIdAt(int $x, int $y, int $z) : int{ @@ -2236,10 +2151,9 @@ class Level implements ChunkManager, Metadatable{ /** * Sets the raw block id. * - * @param int $x - * @param int $y - * @param int $z * @param int $id 0-255 + * + * @return void */ public function setBlockIdAt(int $x, int $y, int $z, int $id){ if(!$this->isInWorld($x, $y, $z)){ //TODO: bad hack but fixing this requires BC breaks to do properly :( @@ -2262,10 +2176,6 @@ class Level implements ChunkManager, Metadatable{ /** * Gets the raw block metadata * - * @param int $x - * @param int $y - * @param int $z - * * @return int 0-15 */ public function getBlockDataAt(int $x, int $y, int $z) : int{ @@ -2275,10 +2185,9 @@ class Level implements ChunkManager, Metadatable{ /** * Sets the raw block metadata. * - * @param int $x - * @param int $y - * @param int $z * @param int $data 0-15 + * + * @return void */ public function setBlockDataAt(int $x, int $y, int $z, int $data){ if(!$this->isInWorld($x, $y, $z)){ //TODO: bad hack but fixing this requires BC breaks to do properly :( @@ -2302,10 +2211,6 @@ class Level implements ChunkManager, Metadatable{ /** * Gets the raw block skylight level * - * @param int $x - * @param int $y - * @param int $z - * * @return int 0-15 */ public function getBlockSkyLightAt(int $x, int $y, int $z) : int{ @@ -2315,10 +2220,9 @@ class Level implements ChunkManager, Metadatable{ /** * Sets the raw block skylight level. * - * @param int $x - * @param int $y - * @param int $z * @param int $level 0-15 + * + * @return void */ public function setBlockSkyLightAt(int $x, int $y, int $z, int $level){ $this->getChunk($x >> 4, $z >> 4, true)->setBlockSkyLight($x & 0x0f, $y, $z & 0x0f, $level & 0x0f); @@ -2327,10 +2231,6 @@ class Level implements ChunkManager, Metadatable{ /** * Gets the raw block light level * - * @param int $x - * @param int $y - * @param int $z - * * @return int 0-15 */ public function getBlockLightAt(int $x, int $y, int $z) : int{ @@ -2340,58 +2240,35 @@ class Level implements ChunkManager, Metadatable{ /** * Sets the raw block light level. * - * @param int $x - * @param int $y - * @param int $z * @param int $level 0-15 + * + * @return void */ public function setBlockLightAt(int $x, int $y, int $z, int $level){ $this->getChunk($x >> 4, $z >> 4, true)->setBlockLight($x & 0x0f, $y, $z & 0x0f, $level & 0x0f); } - /** - * @param int $x - * @param int $z - * - * @return int - */ public function getBiomeId(int $x, int $z) : int{ return $this->getChunk($x >> 4, $z >> 4, true)->getBiomeId($x & 0x0f, $z & 0x0f); } - /** - * @param int $x - * @param int $z - * - * @return Biome - */ public function getBiome(int $x, int $z) : Biome{ return Biome::getBiome($this->getBiomeId($x, $z)); } /** - * @param int $x - * @param int $z - * @param int $biomeId + * @return void */ public function setBiomeId(int $x, int $z, int $biomeId){ $this->getChunk($x >> 4, $z >> 4, true)->setBiomeId($x & 0x0f, $z & 0x0f, $biomeId); } - /** - * @param int $x - * @param int $z - * - * @return int - */ public function getHeightMap(int $x, int $z) : int{ return $this->getChunk($x >> 4, $z >> 4, true)->getHeightMap($x & 0x0f, $z & 0x0f); } /** - * @param int $x - * @param int $z - * @param int $value + * @return void */ public function setHeightMap(int $x, int $z, int $value){ $this->getChunk($x >> 4, $z >> 4, true)->setHeightMap($x & 0x0f, $z & 0x0f, $value); @@ -2408,8 +2285,6 @@ class Level implements ChunkManager, Metadatable{ * Returns the chunk at the specified X/Z coordinates. If the chunk is not loaded, attempts to (synchronously!!!) * load it. * - * @param int $x - * @param int $z * @param bool $create Whether to create an empty chunk as a placeholder if the chunk does not exist * * @return Chunk|null @@ -2426,11 +2301,6 @@ class Level implements ChunkManager, Metadatable{ /** * Returns the chunk containing the given Vector3 position. - * - * @param Vector3 $pos - * @param bool $create - * - * @return null|Chunk */ public function getChunkAtPosition(Vector3 $pos, bool $create = false) : ?Chunk{ return $this->getChunk($pos->getFloorX() >> 4, $pos->getFloorZ() >> 4, $create); @@ -2439,9 +2309,6 @@ class Level implements ChunkManager, Metadatable{ /** * Returns the chunks adjacent to the specified chunk. * - * @param int $x - * @param int $z - * * @return (Chunk|null)[] */ public function getAdjacentChunks(int $x, int $z) : array{ @@ -2459,6 +2326,9 @@ class Level implements ChunkManager, Metadatable{ return $result; } + /** + * @return void + */ public function generateChunkCallback(int $x, int $z, ?Chunk $chunk){ Timings::$generationCallbackTimer->startTiming(); if(isset($this->chunkPopulationQueue[$index = Level::chunkHash($x, $z)])){ @@ -2492,10 +2362,9 @@ class Level implements ChunkManager, Metadatable{ } /** - * @param int $chunkX - * @param int $chunkZ - * @param Chunk|null $chunk * @param bool $deleteEntitiesAndTiles Whether to delete entities and tiles on the old chunk, or transfer them to the new one + * + * @return void */ public function setChunk(int $chunkX, int $chunkZ, Chunk $chunk = null, bool $deleteEntitiesAndTiles = true){ if($chunk === null){ @@ -2556,9 +2425,6 @@ class Level implements ChunkManager, Metadatable{ /** * Gets the highest block Y value at a specific $x and $z * - * @param int $x - * @param int $z - * * @return int 0-255 */ public function getHighestBlockAt(int $x, int $z) : int{ @@ -2567,42 +2433,20 @@ class Level implements ChunkManager, Metadatable{ /** * Returns whether the given position is in a loaded area of terrain. - * - * @param Vector3 $pos - * - * @return bool */ public function isInLoadedTerrain(Vector3 $pos) : bool{ return $this->isChunkLoaded($pos->getFloorX() >> 4, $pos->getFloorZ() >> 4); } - /** - * @param int $x - * @param int $z - * - * @return bool - */ public function isChunkLoaded(int $x, int $z) : bool{ return isset($this->chunks[Level::chunkHash($x, $z)]); } - /** - * @param int $x - * @param int $z - * - * @return bool - */ public function isChunkGenerated(int $x, int $z) : bool{ $chunk = $this->getChunk($x, $z); return $chunk !== null ? $chunk->isGenerated() : false; } - /** - * @param int $x - * @param int $z - * - * @return bool - */ public function isChunkPopulated(int $x, int $z) : bool{ $chunk = $this->getChunk($x, $z); return $chunk !== null ? $chunk->isPopulated() : false; @@ -2610,8 +2454,6 @@ class Level implements ChunkManager, Metadatable{ /** * Returns a Position pointing to the spawn - * - * @return Position */ public function getSpawnLocation() : Position{ return Position::fromObject($this->provider->getSpawn(), $this); @@ -2620,7 +2462,7 @@ class Level implements ChunkManager, Metadatable{ /** * Sets the level spawn location * - * @param Vector3 $pos + * @return void */ public function setSpawnLocation(Vector3 $pos){ $previousSpawn = $this->getSpawnLocation(); @@ -2628,6 +2470,9 @@ class Level implements ChunkManager, Metadatable{ (new SpawnChangeEvent($this, $previousSpawn))->call(); } + /** + * @return void + */ public function requestChunk(int $x, int $z, Player $player){ $index = Level::chunkHash($x, $z); if(!isset($this->chunkSendQueue[$index])){ @@ -2637,7 +2482,7 @@ class Level implements ChunkManager, Metadatable{ $this->chunkSendQueue[$index][$player->getLoaderId()] = $player; } - private function sendChunkFromCache(int $x, int $z){ + private function sendChunkFromCache(int $x, int $z) : void{ if(isset($this->chunkSendQueue[$index = Level::chunkHash($x, $z)])){ foreach($this->chunkSendQueue[$index] as $player){ /** @var Player $player */ @@ -2649,7 +2494,7 @@ class Level implements ChunkManager, Metadatable{ } } - private function processChunkRequest(){ + private function processChunkRequest() : void{ if(count($this->chunkSendQueue) > 0){ $this->timings->syncChunkSendTimer->startTiming(); @@ -2687,6 +2532,9 @@ class Level implements ChunkManager, Metadatable{ } } + /** + * @return void + */ public function chunkRequestCallback(int $x, int $z, BatchPacket $payload){ $this->timings->syncChunkSendTimer->startTiming(); @@ -2703,8 +2551,7 @@ class Level implements ChunkManager, Metadatable{ } /** - * @param Entity $entity - * + * @return void * @throws LevelException */ public function addEntity(Entity $entity){ @@ -2724,8 +2571,7 @@ class Level implements ChunkManager, Metadatable{ /** * Removes the entity from the level index * - * @param Entity $entity - * + * @return void * @throws LevelException */ public function removeEntity(Entity $entity){ @@ -2743,8 +2589,7 @@ class Level implements ChunkManager, Metadatable{ } /** - * @param Tile $tile - * + * @return void * @throws LevelException */ public function addTile(Tile $tile){ @@ -2769,8 +2614,7 @@ class Level implements ChunkManager, Metadatable{ } /** - * @param Tile $tile - * + * @return void * @throws LevelException */ public function removeTile(Tile $tile){ @@ -2789,12 +2633,6 @@ class Level implements ChunkManager, Metadatable{ $this->clearChunkCache($chunkX, $chunkZ); } - /** - * @param int $x - * @param int $z - * - * @return bool - */ public function isChunkInUse(int $x, int $z) : bool{ return isset($this->chunkLoaders[$index = Level::chunkHash($x, $z)]) and count($this->chunkLoaders[$index]) > 0; } @@ -2802,8 +2640,6 @@ class Level implements ChunkManager, Metadatable{ /** * Attempts to load a chunk from the level provider (if not already loaded). * - * @param int $x - * @param int $z * @param bool $create Whether to create an empty chunk to load if the chunk cannot be loaded from disk. * * @return bool if loading the chunk was successful @@ -2866,11 +2702,14 @@ class Level implements ChunkManager, Metadatable{ return true; } - private function queueUnloadChunk(int $x, int $z){ + private function queueUnloadChunk(int $x, int $z) : void{ $this->unloadQueue[$index = Level::chunkHash($x, $z)] = microtime(true); unset($this->chunkTickList[$index]); } + /** + * @return bool + */ public function unloadChunkRequest(int $x, int $z, bool $safe = true){ if(($safe and $this->isChunkInUse($x, $z)) or $this->isSpawnChunk($x, $z)){ return false; @@ -2881,6 +2720,9 @@ class Level implements ChunkManager, Metadatable{ return true; } + /** + * @return void + */ public function cancelUnloadChunkRequest(int $x, int $z){ unset($this->unloadQueue[Level::chunkHash($x, $z)]); } @@ -2942,11 +2784,6 @@ class Level implements ChunkManager, Metadatable{ /** * Returns whether the chunk at the specified coordinates is a spawn chunk - * - * @param int $X - * @param int $Z - * - * @return bool */ public function isSpawnChunk(int $X, int $Z) : bool{ $spawn = $this->provider->getSpawn(); @@ -2956,11 +2793,6 @@ class Level implements ChunkManager, Metadatable{ return abs($X - $spawnX) <= 1 and abs($Z - $spawnZ) <= 1; } - /** - * @param Vector3|null $spawn - * - * @return Position - */ public function getSafeSpawn(?Vector3 $spawn = null) : Position{ if(!($spawn instanceof Vector3) or $spawn->y < 1){ $spawn = $this->getSpawnLocation(); @@ -3003,8 +2835,6 @@ class Level implements ChunkManager, Metadatable{ /** * Gets the current time - * - * @return int */ public function getTime() : int{ return $this->time; @@ -3021,8 +2851,6 @@ class Level implements ChunkManager, Metadatable{ /** * Returns the Level name - * - * @return string */ public function getName() : string{ return $this->displayName; @@ -3030,8 +2858,6 @@ class Level implements ChunkManager, Metadatable{ /** * Returns the Level folder name - * - * @return string */ public function getFolderName() : string{ return $this->folderName; @@ -3040,7 +2866,7 @@ class Level implements ChunkManager, Metadatable{ /** * Sets the current time on the level * - * @param int $time + * @return void */ public function setTime(int $time){ $this->time = $time; @@ -3049,6 +2875,8 @@ class Level implements ChunkManager, Metadatable{ /** * Stops the time for the level, will not save the lock state to disk + * + * @return void */ public function stopTime(){ $this->stopTime = true; @@ -3057,6 +2885,8 @@ class Level implements ChunkManager, Metadatable{ /** * Start the time again, if it was stopped + * + * @return void */ public function startTime(){ $this->stopTime = false; @@ -3065,8 +2895,6 @@ class Level implements ChunkManager, Metadatable{ /** * Gets the level seed - * - * @return int */ public function getSeed() : int{ return $this->provider->getSeed(); @@ -3075,7 +2903,7 @@ class Level implements ChunkManager, Metadatable{ /** * Sets the seed for the level * - * @param int $seed + * @return void */ public function setSeed(int $seed){ $this->provider->setSeed($seed); @@ -3085,15 +2913,12 @@ class Level implements ChunkManager, Metadatable{ return $this->worldHeight; } - /** - * @return int - */ public function getDifficulty() : int{ return $this->provider->getDifficulty(); } /** - * @param int $difficulty + * @return void */ public function setDifficulty(int $difficulty){ if($difficulty < 0 or $difficulty > 3){ @@ -3106,6 +2931,8 @@ class Level implements ChunkManager, Metadatable{ /** * @param Player ...$targets + * + * @return void */ public function sendDifficulty(Player ...$targets){ if(count($targets) === 0){ @@ -3154,6 +2981,9 @@ class Level implements ChunkManager, Metadatable{ return true; } + /** + * @return void + */ public function doChunkGarbageCollection(){ $this->timings->doChunkGC->startTiming(); @@ -3172,6 +3002,9 @@ class Level implements ChunkManager, Metadatable{ $this->timings->doChunkGC->stopTiming(); } + /** + * @return void + */ public function unloadChunks(bool $force = false){ if(count($this->unloadQueue) > 0){ $maxUnload = 96; diff --git a/src/pocketmine/level/Location.php b/src/pocketmine/level/Location.php index 435e82575d..a3394e31a3 100644 --- a/src/pocketmine/level/Location.php +++ b/src/pocketmine/level/Location.php @@ -38,7 +38,6 @@ class Location extends Position{ * @param float|int $z * @param float $yaw * @param float $pitch - * @param Level $level */ public function __construct($x = 0, $y = 0, $z = 0, $yaw = 0.0, $pitch = 0.0, Level $level = null){ $this->yaw = $yaw; @@ -47,12 +46,8 @@ class Location extends Position{ } /** - * @param Vector3 $pos - * @param Level|null $level default null * @param float $yaw default 0.0 * @param float $pitch default 0.0 - * - * @return Location */ public static function fromObject(Vector3 $pos, Level $level = null, $yaw = 0.0, $pitch = 0.0) : Location{ return new Location($pos->x, $pos->y, $pos->z, $yaw, $pitch, $level ?? (($pos instanceof Position) ? $pos->level : null)); @@ -60,17 +55,21 @@ class Location extends Position{ /** * Return a Location instance - * - * @return Location */ public function asLocation() : Location{ return new Location($this->x, $this->y, $this->z, $this->yaw, $this->pitch, $this->level); } + /** + * @return float + */ public function getYaw(){ return $this->yaw; } + /** + * @return float + */ public function getPitch(){ return $this->pitch; } diff --git a/src/pocketmine/level/Position.php b/src/pocketmine/level/Position.php index cb8ea44b73..19e4fcdb50 100644 --- a/src/pocketmine/level/Position.php +++ b/src/pocketmine/level/Position.php @@ -36,21 +36,21 @@ class Position extends Vector3{ * @param float|int $x * @param float|int $y * @param float|int $z - * @param Level $level */ public function __construct($x = 0, $y = 0, $z = 0, Level $level = null){ parent::__construct($x, $y, $z); $this->setLevel($level); } + /** + * @return Position + */ public static function fromObject(Vector3 $pos, Level $level = null){ return new Position($pos->x, $pos->y, $pos->z, $level); } /** * Return a Position instance - * - * @return Position */ public function asPosition() : Position{ return new Position($this->x, $this->y, $this->z, $this->level); @@ -74,8 +74,6 @@ class Position extends Vector3{ /** * Sets the target Level of the position. * - * @param Level|null $level - * * @return $this * * @throws \InvalidArgumentException if the specified Level has been closed @@ -91,8 +89,6 @@ class Position extends Vector3{ /** * Checks if this object has a valid reference to a loaded Level - * - * @return bool */ public function isValid() : bool{ if($this->level !== null and $this->level->isClosed()){ @@ -107,9 +103,6 @@ class Position extends Vector3{ /** * Returns a side Vector * - * @param int $side - * @param int $step - * * @return Position */ public function getSide(int $side, int $step = 1){ diff --git a/src/pocketmine/level/SimpleChunkManager.php b/src/pocketmine/level/SimpleChunkManager.php index 582598fb0a..3f8b46ea3c 100644 --- a/src/pocketmine/level/SimpleChunkManager.php +++ b/src/pocketmine/level/SimpleChunkManager.php @@ -32,14 +32,13 @@ class SimpleChunkManager implements ChunkManager{ /** @var Chunk[] */ protected $chunks = []; + /** @var int */ protected $seed; + /** @var int */ protected $worldHeight; /** * SimpleChunkManager constructor. - * - * @param int $seed - * @param int $worldHeight */ public function __construct(int $seed, int $worldHeight = Level::Y_MAX){ $this->seed = $seed; @@ -49,14 +48,10 @@ class SimpleChunkManager implements ChunkManager{ /** * Gets the raw block id. * - * @param int $x - * @param int $y - * @param int $z - * * @return int 0-255 */ public function getBlockIdAt(int $x, int $y, int $z) : int{ - if($chunk = $this->getChunk($x >> 4, $z >> 4)){ + if(($chunk = $this->getChunk($x >> 4, $z >> 4)) !== null){ return $chunk->getBlockId($x & 0xf, $y, $z & 0xf); } return 0; @@ -65,13 +60,12 @@ class SimpleChunkManager implements ChunkManager{ /** * Sets the raw block id. * - * @param int $x - * @param int $y - * @param int $z * @param int $id 0-255 + * + * @return void */ public function setBlockIdAt(int $x, int $y, int $z, int $id){ - if($chunk = $this->getChunk($x >> 4, $z >> 4)){ + if(($chunk = $this->getChunk($x >> 4, $z >> 4)) !== null){ $chunk->setBlockId($x & 0xf, $y, $z & 0xf, $id); } } @@ -79,14 +73,10 @@ class SimpleChunkManager implements ChunkManager{ /** * Gets the raw block metadata * - * @param int $x - * @param int $y - * @param int $z - * * @return int 0-15 */ public function getBlockDataAt(int $x, int $y, int $z) : int{ - if($chunk = $this->getChunk($x >> 4, $z >> 4)){ + if(($chunk = $this->getChunk($x >> 4, $z >> 4)) !== null){ return $chunk->getBlockData($x & 0xf, $y, $z & 0xf); } return 0; @@ -95,19 +85,18 @@ class SimpleChunkManager implements ChunkManager{ /** * Sets the raw block metadata. * - * @param int $x - * @param int $y - * @param int $z * @param int $data 0-15 + * + * @return void */ public function setBlockDataAt(int $x, int $y, int $z, int $data){ - if($chunk = $this->getChunk($x >> 4, $z >> 4)){ + if(($chunk = $this->getChunk($x >> 4, $z >> 4)) !== null){ $chunk->setBlockData($x & 0xf, $y, $z & 0xf, $data); } } public function getBlockLightAt(int $x, int $y, int $z) : int{ - if($chunk = $this->getChunk($x >> 4, $z >> 4)){ + if(($chunk = $this->getChunk($x >> 4, $z >> 4)) !== null){ return $chunk->getBlockLight($x & 0xf, $y, $z & 0xf); } @@ -115,13 +104,13 @@ class SimpleChunkManager implements ChunkManager{ } public function setBlockLightAt(int $x, int $y, int $z, int $level){ - if($chunk = $this->getChunk($x >> 4, $z >> 4)){ + if(($chunk = $this->getChunk($x >> 4, $z >> 4)) !== null){ $chunk->setBlockLight($x & 0xf, $y, $z & 0xf, $level); } } public function getBlockSkyLightAt(int $x, int $y, int $z) : int{ - if($chunk = $this->getChunk($x >> 4, $z >> 4)){ + if(($chunk = $this->getChunk($x >> 4, $z >> 4)) !== null){ return $chunk->getBlockSkyLight($x & 0xf, $y, $z & 0xf); } @@ -129,15 +118,12 @@ class SimpleChunkManager implements ChunkManager{ } public function setBlockSkyLightAt(int $x, int $y, int $z, int $level){ - if($chunk = $this->getChunk($x >> 4, $z >> 4)){ + if(($chunk = $this->getChunk($x >> 4, $z >> 4)) !== null){ $chunk->setBlockSkyLight($x & 0xf, $y, $z & 0xf, $level); } } /** - * @param int $chunkX - * @param int $chunkZ - * * @return Chunk|null */ public function getChunk(int $chunkX, int $chunkZ){ @@ -145,9 +131,7 @@ class SimpleChunkManager implements ChunkManager{ } /** - * @param int $chunkX - * @param int $chunkZ - * @param Chunk|null $chunk + * @return void */ public function setChunk(int $chunkX, int $chunkZ, Chunk $chunk = null){ if($chunk === null){ @@ -157,14 +141,15 @@ class SimpleChunkManager implements ChunkManager{ $this->chunks[Level::chunkHash($chunkX, $chunkZ)] = $chunk; } + /** + * @return void + */ public function cleanChunks(){ $this->chunks = []; } /** * Gets the level seed - * - * @return int */ public function getSeed() : int{ return $this->seed; diff --git a/src/pocketmine/level/biome/Biome.php b/src/pocketmine/level/biome/Biome.php index 7ccab348d6..9a92c55483 100644 --- a/src/pocketmine/level/biome/Biome.php +++ b/src/pocketmine/level/biome/Biome.php @@ -43,16 +43,16 @@ abstract class Biome{ public const ICE_PLAINS = 12; - public const SMALL_MOUNTAINS = 20; - public const BIRCH_FOREST = 27; - public const MAX_BIOMES = 256; - /** @var Biome[]|\SplFixedArray */ + /** + * @var Biome[]|\SplFixedArray + * @phpstan-var \SplFixedArray + */ private static $biomes; /** @var int */ @@ -76,11 +76,17 @@ abstract class Biome{ /** @var float */ protected $temperature = 0.5; + /** + * @return void + */ protected static function register(int $id, Biome $biome){ self::$biomes[$id] = $biome; $biome->setId($id); } + /** + * @return void + */ public static function init(){ self::$biomes = new \SplFixedArray(self::MAX_BIOMES); @@ -95,17 +101,11 @@ abstract class Biome{ self::register(self::ICE_PLAINS, new IcePlainsBiome()); - self::register(self::SMALL_MOUNTAINS, new SmallMountainsBiome()); self::register(self::BIRCH_FOREST, new ForestBiome(ForestBiome::TYPE_BIRCH)); } - /** - * @param int $id - * - * @return Biome - */ public static function getBiome(int $id) : Biome{ if(self::$biomes[$id] === null){ self::register($id, new UnknownBiome()); @@ -113,19 +113,22 @@ abstract class Biome{ return self::$biomes[$id]; } + /** + * @return void + */ public function clearPopulators(){ $this->populators = []; } + /** + * @return void + */ public function addPopulator(Populator $populator){ $this->populators[] = $populator; } /** - * @param ChunkManager $level - * @param int $chunkX - * @param int $chunkZ - * @param Random $random + * @return void */ public function populateChunk(ChunkManager $level, int $chunkX, int $chunkZ, Random $random){ foreach($this->populators as $populator){ @@ -140,6 +143,9 @@ abstract class Biome{ return $this->populators; } + /** + * @return void + */ public function setId(int $id){ if(!$this->registered){ $this->registered = true; @@ -161,6 +167,9 @@ abstract class Biome{ return $this->maxElevation; } + /** + * @return void + */ public function setElevation(int $min, int $max){ $this->minElevation = $min; $this->maxElevation = $max; @@ -175,6 +184,8 @@ abstract class Biome{ /** * @param Block[] $covers + * + * @return void */ public function setGroundCover(array $covers){ $this->groundCover = $covers; diff --git a/src/pocketmine/level/biome/DesertBiome.php b/src/pocketmine/level/biome/DesertBiome.php index d520ad5853..d863f47dd8 100644 --- a/src/pocketmine/level/biome/DesertBiome.php +++ b/src/pocketmine/level/biome/DesertBiome.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\level\biome; - class DesertBiome extends SandyBiome{ public function __construct(){ diff --git a/src/pocketmine/level/biome/ForestBiome.php b/src/pocketmine/level/biome/ForestBiome.php index 30ec1475f7..a756d21091 100644 --- a/src/pocketmine/level/biome/ForestBiome.php +++ b/src/pocketmine/level/biome/ForestBiome.php @@ -32,6 +32,7 @@ class ForestBiome extends GrassyBiome{ public const TYPE_NORMAL = 0; public const TYPE_BIRCH = 1; + /** @var int */ public $type; public function __construct(int $type = self::TYPE_NORMAL){ diff --git a/src/pocketmine/level/biome/SmallMountainsBiome.php b/src/pocketmine/level/biome/SmallMountainsBiome.php index 12a9b52293..4e96de245f 100644 --- a/src/pocketmine/level/biome/SmallMountainsBiome.php +++ b/src/pocketmine/level/biome/SmallMountainsBiome.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\level\biome; - class SmallMountainsBiome extends MountainsBiome{ public function __construct(){ diff --git a/src/pocketmine/level/format/Chunk.php b/src/pocketmine/level/format/Chunk.php index 5847dd0aba..1d7e294ac9 100644 --- a/src/pocketmine/level/format/Chunk.php +++ b/src/pocketmine/level/format/Chunk.php @@ -72,7 +72,10 @@ class Chunk{ /** @var int */ protected $height = Chunk::MAX_SUBCHUNKS; - /** @var \SplFixedArray|SubChunkInterface[] */ + /** + * @var \SplFixedArray|SubChunkInterface[] + * @phpstan-var \SplFixedArray + */ protected $subChunks; /** @var EmptySubChunk */ @@ -86,7 +89,10 @@ class Chunk{ /** @var Entity[] */ protected $entities = []; - /** @var \SplFixedArray|int[] */ + /** + * @var \SplFixedArray|int[] + * @phpstan-var \SplFixedArray + */ protected $heightMap; /** @var string */ @@ -99,12 +105,9 @@ class Chunk{ protected $NBTentities = []; /** - * @param int $chunkX - * @param int $chunkZ * @param SubChunkInterface[] $subChunks * @param CompoundTag[] $entities * @param CompoundTag[] $tiles - * @param string $biomeIds * @param int[] $heightMap */ public function __construct(int $chunkX, int $chunkZ, array $subChunks = [], array $entities = [], array $tiles = [], string $biomeIds = "", array $heightMap = []){ @@ -139,26 +142,23 @@ class Chunk{ $this->NBTentities = $entities; } - /** - * @return int - */ public function getX() : int{ return $this->x; } - /** - * @return int - */ public function getZ() : int{ return $this->z; } + /** + * @return void + */ public function setX(int $x){ $this->x = $x; } /** - * @param int $z + * @return void */ public function setZ(int $z){ $this->z = $z; @@ -166,8 +166,6 @@ class Chunk{ /** * Returns the chunk height in count of subchunks. - * - * @return int */ public function getHeight() : int{ return $this->height; @@ -194,8 +192,6 @@ class Chunk{ * @param int $z 0-15 * @param int|null $blockId 0-255 if null, does not change * @param int|null $meta 0-15 if null, does not change - * - * @return bool */ public function setBlock(int $x, int $y, int $z, ?int $blockId = null, ?int $meta = null) : bool{ if($this->getSubChunk($y >> 4, true)->setBlock($x, $y & 0x0f, $z, $blockId !== null ? ($blockId & 0xff) : null, $meta !== null ? ($meta & 0x0f) : null)){ @@ -225,6 +221,8 @@ class Chunk{ * @param int $y * @param int $z 0-15 * @param int $id 0-255 + * + * @return void */ public function setBlockId(int $x, int $y, int $z, int $id){ if($this->getSubChunk($y >> 4, true)->setBlockId($x, $y & 0x0f, $z, $id)){ @@ -252,6 +250,8 @@ class Chunk{ * @param int $y * @param int $z 0-15 * @param int $data 0-15 + * + * @return void */ public function setBlockData(int $x, int $y, int $z, int $data){ if($this->getSubChunk($y >> 4, true)->setBlockData($x, $y & 0x0f, $z, $data)){ @@ -279,6 +279,8 @@ class Chunk{ * @param int $y * @param int $z 0-15 * @param int $level 0-15 + * + * @return void */ public function setBlockSkyLight(int $x, int $y, int $z, int $level){ if($this->getSubChunk($y >> 4, true)->setBlockSkyLight($x, $y & 0x0f, $z, $level)){ @@ -287,7 +289,7 @@ class Chunk{ } /** - * @param int $level + * @return void */ public function setAllBlockSkyLight(int $level){ $char = chr(($level & 0x0f) | ($level << 4)); @@ -317,6 +319,8 @@ class Chunk{ * @param int $y 0-15 * @param int $z 0-15 * @param int $level 0-15 + * + * @return void */ public function setBlockLight(int $x, int $y, int $z, int $level){ if($this->getSubChunk($y >> 4, true)->setBlockLight($x, $y & 0x0f, $z, $level)){ @@ -325,7 +329,7 @@ class Chunk{ } /** - * @param int $level + * @return void */ public function setAllBlockLight(int $level){ $char = chr(($level & 0x0f) | ($level << 4)); @@ -368,8 +372,6 @@ class Chunk{ * * @param int $x 0-15 * @param int $z 0-15 - * - * @return int */ public function getHeightMap(int $x, int $z) : int{ return $this->heightMap[($z << 4) | $x]; @@ -380,7 +382,8 @@ class Chunk{ * * @param int $x 0-15 * @param int $z 0-15 - * @param int $value + * + * @return void */ public function setHeightMap(int $x, int $z, int $value){ $this->heightMap[($z << 4) | $x] = $value; @@ -388,6 +391,8 @@ class Chunk{ /** * Recalculates the heightmap for the whole chunk. + * + * @return void */ public function recalculateHeightMap(){ for($z = 0; $z < 16; ++$z){ @@ -406,8 +411,8 @@ class Chunk{ * @return int New calculated heightmap value (0-256 inclusive) */ public function recalculateHeightMapColumn(int $x, int $z) : int{ - $max = $this->getHighestBlockAt($x, $z); - for($y = $max; $y >= 0; --$y){ + $y = $this->getHighestBlockAt($x, $z); + for(; $y >= 0; --$y){ if(BlockFactory::$lightFilter[$id = $this->getBlockId($x, $y, $z)] > 1 or BlockFactory::$diffusesSkyLight[$id]){ break; } @@ -423,6 +428,8 @@ class Chunk{ * if the chunk is light-populated after being terrain-populated. * * TODO: fast adjacent light spread + * + * @return void */ public function populateSkyLight(){ $maxY = $this->getMaxY(); @@ -431,19 +438,17 @@ class Chunk{ for($x = 0; $x < 16; ++$x){ for($z = 0; $z < 16; ++$z){ + $y = $maxY; $heightMap = $this->getHeightMap($x, $z); - - for($y = $maxY; $y >= $heightMap; --$y){ + for(; $y >= $heightMap; --$y){ $this->setBlockSkyLight($x, $y, $z, 15); } $light = 15; for(; $y >= 0; --$y){ - if($light > 0){ - $light -= BlockFactory::$lightFilter[$this->getBlockId($x, $y, $z)]; - if($light <= 0){ - break; - } + $light -= BlockFactory::$lightFilter[$this->getBlockId($x, $y, $z)]; + if($light <= 0){ + break; } $this->setBlockSkyLight($x, $y, $z, $light); } @@ -469,6 +474,8 @@ class Chunk{ * @param int $x 0-15 * @param int $z 0-15 * @param int $biomeId 0-255 + * + * @return void */ public function setBiomeId(int $x, int $z, int $biomeId){ $this->hasChanged = true; @@ -480,8 +487,6 @@ class Chunk{ * * @param int $x 0-15 * @param int $z 0-15 - * - * @return string */ public function getBlockIdColumn(int $x, int $z) : string{ $result = ""; @@ -497,8 +502,6 @@ class Chunk{ * * @param int $x 0-15 * @param int $z 0-15 - * - * @return string */ public function getBlockDataColumn(int $x, int $z) : string{ $result = ""; @@ -513,8 +516,6 @@ class Chunk{ * * @param int $x 0-15 * @param int $z 0-15 - * - * @return string */ public function getBlockSkyLightColumn(int $x, int $z) : string{ $result = ""; @@ -529,8 +530,6 @@ class Chunk{ * * @param int $x 0-15 * @param int $z 0-15 - * - * @return string */ public function getBlockLightColumn(int $x, int $z) : string{ $result = ""; @@ -540,50 +539,41 @@ class Chunk{ return $result; } - /** - * @return bool - */ public function isLightPopulated() : bool{ return $this->lightPopulated; } /** - * @param bool $value + * @return void */ public function setLightPopulated(bool $value = true){ $this->lightPopulated = $value; } - /** - * @return bool - */ public function isPopulated() : bool{ return $this->terrainPopulated; } /** - * @param bool $value + * @return void */ public function setPopulated(bool $value = true){ $this->terrainPopulated = $value; } - /** - * @return bool - */ public function isGenerated() : bool{ return $this->terrainGenerated; } /** - * @param bool $value + * @return void */ public function setGenerated(bool $value = true){ $this->terrainGenerated = $value; } /** - * @param Entity $entity + * @return void */ public function addEntity(Entity $entity){ if($entity->isClosed()){ @@ -596,7 +586,7 @@ class Chunk{ } /** - * @param Entity $entity + * @return void */ public function removeEntity(Entity $entity){ unset($this->entities[$entity->getId()]); @@ -606,7 +596,7 @@ class Chunk{ } /** - * @param Tile $tile + * @return void */ public function addTile(Tile $tile){ if($tile->isClosed()){ @@ -623,7 +613,7 @@ class Chunk{ } /** - * @param Tile $tile + * @return void */ public function removeTile(Tile $tile){ unset($this->tiles[$tile->getId()]); @@ -689,7 +679,7 @@ class Chunk{ /** * Deserializes tiles and entities from NBT * - * @param Level $level + * @return void */ public function initChunk(Level $level){ if(!$this->isInit){ @@ -697,23 +687,21 @@ class Chunk{ $level->timings->syncChunkLoadEntitiesTimer->startTiming(); foreach($this->NBTentities as $nbt){ - if($nbt instanceof CompoundTag){ - if(!$nbt->hasTag("id")){ //allow mixed types (because of leveldb) - $changed = true; - continue; - } + if(!$nbt->hasTag("id")){ //allow mixed types (because of leveldb) + $changed = true; + continue; + } - try{ - $entity = Entity::createEntity($nbt->getTag("id")->getValue(), $level, $nbt); - if(!($entity instanceof Entity)){ - $changed = true; - continue; - } - }catch(\Throwable $t){ - $level->getServer()->getLogger()->logException($t); + try{ + $entity = Entity::createEntity($nbt->getTag("id")->getValue(), $level, $nbt); + if(!($entity instanceof Entity)){ $changed = true; continue; } + }catch(\Throwable $t){ + $level->getServer()->getLogger()->logException($t); + $changed = true; + continue; } } $this->NBTentities = []; @@ -721,16 +709,14 @@ class Chunk{ $level->timings->syncChunkLoadTileEntitiesTimer->startTiming(); foreach($this->NBTtiles as $nbt){ - if($nbt instanceof CompoundTag){ - if(!$nbt->hasTag(Tile::TAG_ID, StringTag::class)){ - $changed = true; - continue; - } + if(!$nbt->hasTag(Tile::TAG_ID, StringTag::class)){ + $changed = true; + continue; + } - if(Tile::createTile($nbt->getString(Tile::TAG_ID), $level, $nbt) === null){ - $changed = true; - continue; - } + if(Tile::createTile($nbt->getString(Tile::TAG_ID), $level, $nbt) === null){ + $changed = true; + continue; } } @@ -743,9 +729,6 @@ class Chunk{ } } - /** - * @return string - */ public function getBiomeIdArray() : string{ return $this->biomeIds; } @@ -757,15 +740,12 @@ class Chunk{ return $this->heightMap->toArray(); } - /** - * @return bool - */ public function hasChanged() : bool{ return $this->hasChanged; } /** - * @param bool $value + * @return void */ public function setChanged(bool $value = true){ $this->hasChanged = $value; @@ -774,10 +754,7 @@ class Chunk{ /** * Returns the subchunk at the specified subchunk Y coordinate, or an empty, unmodifiable stub if it does not exist or the coordinate is out of range. * - * @param int $y * @param bool $generateNew Whether to create a new, modifiable subchunk if there is not one in place - * - * @return SubChunkInterface */ public function getSubChunk(int $y, bool $generateNew = false) : SubChunkInterface{ if($y < 0 or $y >= $this->height){ @@ -792,11 +769,7 @@ class Chunk{ /** * Sets a subchunk in the chunk index * - * @param int $y - * @param SubChunkInterface|null $subChunk * @param bool $allowEmpty Whether to check if the chunk is empty, and if so replace it with an empty stub - * - * @return bool */ public function setSubChunk(int $y, SubChunkInterface $subChunk = null, bool $allowEmpty = false) : bool{ if($y < 0 or $y >= $this->height){ @@ -813,6 +786,7 @@ class Chunk{ /** * @return \SplFixedArray|SubChunkInterface[] + * @phpstan-return \SplFixedArray */ public function getSubChunks() : \SplFixedArray{ return $this->subChunks; @@ -820,8 +794,6 @@ class Chunk{ /** * Returns the Y coordinate of the highest non-empty subchunk in this chunk. - * - * @return int */ public function getHighestSubChunkIndex() : int{ for($y = $this->subChunks->count() - 1; $y >= 0; --$y){ @@ -829,16 +801,14 @@ class Chunk{ //No need to thoroughly prune empties at runtime, this will just reduce performance. continue; } - break; + return $y; } - return $y; + return -1; } /** * Returns the count of subchunks that need sending to players - * - * @return int */ public function getSubChunkSendCount() : int{ return $this->getHighestSubChunkIndex() + 1; @@ -861,8 +831,6 @@ class Chunk{ /** * Serializes the chunk for sending to players - * - * @return string */ public function networkSerialize() : string{ $result = ""; @@ -885,8 +853,6 @@ class Chunk{ /** * Fast-serializes the chunk for passing between threads * TODO: tiles and entities - * - * @return string */ public function fastSerialize() : string{ $stream = new BinaryStream(); @@ -922,10 +888,6 @@ class Chunk{ /** * Deserializes a fast-serialized chunk - * - * @param string $data - * - * @return Chunk */ public static function fastDeserialize(string $data) : Chunk{ $stream = new BinaryStream($data); diff --git a/src/pocketmine/level/format/SubChunk.php b/src/pocketmine/level/format/SubChunk.php index 20207c5636..773afbf86a 100644 --- a/src/pocketmine/level/format/SubChunk.php +++ b/src/pocketmine/level/format/SubChunk.php @@ -38,25 +38,28 @@ if(!defined(__NAMESPACE__ . '\ZERO_NIBBLE_ARRAY')){ } class SubChunk implements SubChunkInterface{ + /** @var string */ protected $ids; + /** @var string */ protected $data; + /** @var string */ protected $blockLight; + /** @var string */ protected $skyLight; - private static function assignData(&$target, string $data, int $length, string $value = "\x00"){ + private static function assignData(string $data, int $length, string $value = "\x00") : string{ if(strlen($data) !== $length){ assert($data === "", "Invalid non-zero length given, expected $length, got " . strlen($data)); - $target = str_repeat($value, $length); - }else{ - $target = $data; + return str_repeat($value, $length); } + return $data; } public function __construct(string $ids = "", string $data = "", string $skyLight = "", string $blockLight = ""){ - self::assignData($this->ids, $ids, 4096); - self::assignData($this->data, $data, 2048); - self::assignData($this->skyLight, $skyLight, 2048, "\xff"); - self::assignData($this->blockLight, $blockLight, 2048); + $this->ids = self::assignData($ids, 4096); + $this->data = self::assignData($data, 2048); + $this->skyLight = self::assignData($skyLight, 2048, "\xff"); + $this->blockLight = self::assignData($blockLight, 2048); $this->collectGarbage(); } @@ -214,6 +217,9 @@ class SubChunk implements SubChunkInterface{ return "\x00" . $this->ids . $this->data; } + /** + * @return mixed[] + */ public function __debugInfo(){ return []; } diff --git a/src/pocketmine/level/format/SubChunkInterface.php b/src/pocketmine/level/format/SubChunkInterface.php index e7d4cde8b1..6b5cd1433f 100644 --- a/src/pocketmine/level/format/SubChunkInterface.php +++ b/src/pocketmine/level/format/SubChunkInterface.php @@ -25,181 +25,55 @@ namespace pocketmine\level\format; interface SubChunkInterface{ - /** - * @param bool $checkLight - * - * @return bool - */ public function isEmpty(bool $checkLight = true) : bool; - /** - * @param int $x - * @param int $y - * @param int $z - * - * @return int - */ public function getBlockId(int $x, int $y, int $z) : int; - /** - * @param int $x - * @param int $y - * @param int $z - * @param int $id - * - * @return bool - */ public function setBlockId(int $x, int $y, int $z, int $id) : bool; - /** - * @param int $x - * @param int $y - * @param int $z - * - * @return int - */ public function getBlockData(int $x, int $y, int $z) : int; - /** - * @param int $x - * @param int $y - * @param int $z - * @param int $data - * - * @return bool - */ public function setBlockData(int $x, int $y, int $z, int $data) : bool; - /** - * @param int $x - * @param int $y - * @param int $z - * - * @return int - */ public function getFullBlock(int $x, int $y, int $z) : int; - /** - * @param int $x - * @param int $y - * @param int $z - * @param int|null $id - * @param int|null $data - * - * @return bool - */ public function setBlock(int $x, int $y, int $z, ?int $id = null, ?int $data = null) : bool; - /** - * @param int $x - * @param int $y - * @param int $z - * - * @return int - */ public function getBlockLight(int $x, int $y, int $z) : int; - /** - * @param int $x - * @param int $y - * @param int $z - * @param int $level - * - * @return bool - */ public function setBlockLight(int $x, int $y, int $z, int $level) : bool; - /** - * @param int $x - * @param int $y - * @param int $z - * - * @return int - */ public function getBlockSkyLight(int $x, int $y, int $z) : int; - /** - * @param int $x - * @param int $y - * @param int $z - * @param int $level - * - * @return bool - */ public function setBlockSkyLight(int $x, int $y, int $z, int $level) : bool; - /** - * @param int $x - * @param int $z - * - * @return int - */ public function getHighestBlockAt(int $x, int $z) : int; - /** - * @param int $x - * @param int $z - * - * @return string - */ public function getBlockIdColumn(int $x, int $z) : string; - /** - * @param int $x - * @param int $z - * - * @return string - */ public function getBlockDataColumn(int $x, int $z) : string; - /** - * @param int $x - * @param int $z - * - * @return string - */ public function getBlockLightColumn(int $x, int $z) : string; - /** - * @param int $x - * @param int $z - * - * @return string - */ public function getBlockSkyLightColumn(int $x, int $z) : string; - /** - * @return string - */ public function getBlockIdArray() : string; - /** - * @return string - */ public function getBlockDataArray() : string; - /** - * @return string - */ public function getBlockSkyLightArray() : string; /** - * @param string $data + * @return void */ public function setBlockSkyLightArray(string $data); - /** - * @return string - */ public function getBlockLightArray() : string; /** - * @param string $data + * @return void */ public function setBlockLightArray(string $data); - /** - * @return string - */ public function networkSerialize() : string; } diff --git a/src/pocketmine/level/format/io/BaseLevelProvider.php b/src/pocketmine/level/format/io/BaseLevelProvider.php index 3a9a01be47..bf65f3d1ae 100644 --- a/src/pocketmine/level/format/io/BaseLevelProvider.php +++ b/src/pocketmine/level/format/io/BaseLevelProvider.php @@ -143,13 +143,13 @@ abstract class BaseLevelProvider implements LevelProvider{ } - /** - * @return CompoundTag - */ public function getLevelData() : CompoundTag{ return $this->levelData; } + /** + * @return void + */ public function saveLevelData(){ $nbt = new BigEndianNBTStream(); $buffer = $nbt->writeCompressed(new CompoundTag("", [ @@ -159,10 +159,6 @@ abstract class BaseLevelProvider implements LevelProvider{ } /** - * @param int $chunkX - * @param int $chunkZ - * - * @return Chunk|null * @throws CorruptedChunkException * @throws UnsupportedChunkFormatException */ @@ -178,10 +174,6 @@ abstract class BaseLevelProvider implements LevelProvider{ } /** - * @param int $chunkX - * @param int $chunkZ - * - * @return Chunk|null * @throws UnsupportedChunkFormatException * @throws CorruptedChunkException */ diff --git a/src/pocketmine/level/format/io/ChunkRequestTask.php b/src/pocketmine/level/format/io/ChunkRequestTask.php index 07bf31eb0e..945ae324a5 100644 --- a/src/pocketmine/level/format/io/ChunkRequestTask.php +++ b/src/pocketmine/level/format/io/ChunkRequestTask.php @@ -34,12 +34,17 @@ use function strlen; class ChunkRequestTask extends AsyncTask{ + /** @var int */ protected $levelId; + /** @var string */ protected $chunk; + /** @var int */ protected $chunkX; + /** @var int */ protected $chunkZ; + /** @var int */ protected $compressionLevel; /** @var int */ diff --git a/src/pocketmine/level/format/io/ChunkUtils.php b/src/pocketmine/level/format/io/ChunkUtils.php index d14f11a51e..8eaf4d8653 100644 --- a/src/pocketmine/level/format/io/ChunkUtils.php +++ b/src/pocketmine/level/format/io/ChunkUtils.php @@ -98,8 +98,6 @@ if(!extension_loaded('pocketmine_chunkutils')){ * Converts pre-MCPE-1.0 biome color array to biome ID array. * * @param int[] $array of biome color values - * - * @return string */ public static function convertBiomeColors(array $array) : string{ $result = str_repeat("\x00", 256); diff --git a/src/pocketmine/level/format/io/LevelProvider.php b/src/pocketmine/level/format/io/LevelProvider.php index 5fa272c17c..b35613de69 100644 --- a/src/pocketmine/level/format/io/LevelProvider.php +++ b/src/pocketmine/level/format/io/LevelProvider.php @@ -26,142 +26,112 @@ namespace pocketmine\level\format\io; use pocketmine\level\format\Chunk; use pocketmine\level\format\io\exception\CorruptedChunkException; use pocketmine\level\format\io\exception\UnsupportedChunkFormatException; +use pocketmine\level\generator\Generator; use pocketmine\math\Vector3; interface LevelProvider{ - /** - * @param string $path - */ public function __construct(string $path); /** * Returns the full provider name, like "anvil" or "mcregion", will be used to find the correct format. - * - * @return string */ public static function getProviderName() : string; /** * Gets the build height limit of this world - * - * @return int */ public function getWorldHeight() : int; - /** - * @return string - */ public function getPath() : string; /** * Tells if the path is a valid level. * This must tell if the current format supports opening the files in the directory - * - * @param string $path - * - * @return bool */ public static function isValid(string $path) : bool; /** * Generate the needed files in the path given * - * @param string $path - * @param string $name - * @param int $seed - * @param string $generator - * @param array $options + * @param mixed[] $options + * @phpstan-param class-string $generator + * @phpstan-param array $options + * + * @return void */ public static function generate(string $path, string $name, int $seed, string $generator, array $options = []); /** * Returns the generator name - * - * @return string */ public function getGenerator() : string; /** - * @return array + * @return mixed[] + * @phpstan-return array */ public function getGeneratorOptions() : array; /** * Saves a chunk (usually to disk). - * - * @param Chunk $chunk */ public function saveChunk(Chunk $chunk) : void; /** * Loads a chunk (usually from disk storage) and returns it. If the chunk does not exist, null is returned. * - * @param int $chunkX - * @param int $chunkZ - * - * @return null|Chunk - * * @throws CorruptedChunkException * @throws UnsupportedChunkFormatException */ public function loadChunk(int $chunkX, int $chunkZ) : ?Chunk; - /** - * @return string - */ public function getName() : string; - /** - * @return int - */ public function getTime() : int; /** - * @param int $value + * @return void */ public function setTime(int $value); - /** - * @return int - */ public function getSeed() : int; /** - * @param int $value + * @return void */ public function setSeed(int $value); - /** - * @return Vector3 - */ public function getSpawn() : Vector3; /** - * @param Vector3 $pos + * @return void */ public function setSpawn(Vector3 $pos); /** * Returns the world difficulty. This will be one of the Level constants. - * @return int */ public function getDifficulty() : int; /** * Sets the world difficulty. * - * @param int $difficulty + * @return void */ public function setDifficulty(int $difficulty); /** * Performs garbage collection in the level provider, such as cleaning up regions in Region-based worlds. + * + * @return void */ public function doGarbageCollection(); /** * Performs cleanups necessary when the level provider is closed and no longer needed. + * + * @return void */ public function close(); diff --git a/src/pocketmine/level/format/io/LevelProviderManager.php b/src/pocketmine/level/format/io/LevelProviderManager.php index b53889f0f3..67c19256df 100644 --- a/src/pocketmine/level/format/io/LevelProviderManager.php +++ b/src/pocketmine/level/format/io/LevelProviderManager.php @@ -31,6 +31,10 @@ use function strtolower; use function trim; abstract class LevelProviderManager{ + /** + * @var string[] + * @phpstan-var array> + */ protected static $providers = []; public static function init() : void{ @@ -41,8 +45,9 @@ abstract class LevelProviderManager{ } /** - * @param string $class + * @phpstan-param class-string $class * + * @return void * @throws \InvalidArgumentException */ public static function addProvider(string $class){ @@ -65,13 +70,12 @@ abstract class LevelProviderManager{ /** * Returns a LevelProvider class for this path, or null * - * @param string $path - * * @return string|null + * @phpstan-return class-string|null */ public static function getProvider(string $path){ foreach(self::$providers as $provider){ - /** @var $provider LevelProvider */ + /** @phpstan-var class-string $provider */ if($provider::isValid($path)){ return $provider; } @@ -83,9 +87,8 @@ abstract class LevelProviderManager{ /** * Returns a LevelProvider by name, or null if not found * - * @param string $name - * * @return string|null + * @phpstan-return class-string|null */ public static function getProviderByName(string $name){ return self::$providers[trim(strtolower($name))] ?? null; diff --git a/src/pocketmine/level/format/io/leveldb/LevelDB.php b/src/pocketmine/level/format/io/leveldb/LevelDB.php index a6aef3060c..2d16d12dc9 100644 --- a/src/pocketmine/level/format/io/leveldb/LevelDB.php +++ b/src/pocketmine/level/format/io/leveldb/LevelDB.php @@ -45,6 +45,7 @@ use pocketmine\utils\Binary; use pocketmine\utils\BinaryStream; use function array_values; use function chr; +use function count; use function defined; use function explode; use function extension_loaded; @@ -101,7 +102,7 @@ class LevelDB extends BaseLevelProvider{ /** @var \LevelDB */ protected $db; - private static function checkForLevelDBExtension(){ + private static function checkForLevelDBExtension() : void{ if(!extension_loaded('leveldb')){ throw new LevelException("The leveldb PHP extension is required to use this world format"); } @@ -125,8 +126,12 @@ class LevelDB extends BaseLevelProvider{ } protected function loadLevelData() : void{ + $rawLevelData = file_get_contents($this->getPath() . "level.dat"); + if($rawLevelData === false or strlen($rawLevelData) <= 8){ + throw new LevelException("Truncated level.dat"); + } $nbt = new LittleEndianNBTStream(); - $levelData = $nbt->read(substr(file_get_contents($this->getPath() . "level.dat"), 8)); + $levelData = $nbt->read(substr($rawLevelData, 8)); if($levelData instanceof CompoundTag){ $this->levelData = $levelData; }else{ @@ -247,7 +252,6 @@ class LevelDB extends BaseLevelProvider{ $buffer = $nbt->write($levelData); file_put_contents($path . "level.dat", Binary::writeLInt(self::CURRENT_STORAGE_VERSION) . Binary::writeLInt(strlen($buffer)) . $buffer); - $db = self::createDB($path); if($generatorType === self::GENERATOR_FLAT and isset($options["preset"])){ @@ -292,10 +296,6 @@ class LevelDB extends BaseLevelProvider{ } /** - * @param int $chunkX - * @param int $chunkZ - * - * @return Chunk|null * @throws UnsupportedChunkFormatException */ protected function readChunk(int $chunkX, int $chunkZ) : ?Chunk{ @@ -516,10 +516,9 @@ class LevelDB extends BaseLevelProvider{ /** * @param CompoundTag[] $targets - * @param string $index */ - private function writeTags(array $targets, string $index){ - if(!empty($targets)){ + private function writeTags(array $targets, string $index) : void{ + if(count($targets) > 0){ $nbt = new LittleEndianNBTStream(); $this->db->put($index, $nbt->write($targets)); }else{ @@ -527,9 +526,6 @@ class LevelDB extends BaseLevelProvider{ } } - /** - * @return \LevelDB - */ public function getDatabase() : \LevelDB{ return $this->db; } diff --git a/src/pocketmine/level/format/io/region/CorruptedRegionException.php b/src/pocketmine/level/format/io/region/CorruptedRegionException.php index 6a63080229..d148603afb 100644 --- a/src/pocketmine/level/format/io/region/CorruptedRegionException.php +++ b/src/pocketmine/level/format/io/region/CorruptedRegionException.php @@ -21,10 +21,8 @@ declare(strict_types=1); - namespace pocketmine\level\format\io\region; - class CorruptedRegionException extends RegionException{ } diff --git a/src/pocketmine/level/format/io/region/McRegion.php b/src/pocketmine/level/format/io/region/McRegion.php index 51cad2438f..3516fc5984 100644 --- a/src/pocketmine/level/format/io/region/McRegion.php +++ b/src/pocketmine/level/format/io/region/McRegion.php @@ -67,11 +67,6 @@ class McRegion extends BaseLevelProvider{ /** @var RegionLoader[] */ protected $regions = []; - /** - * @param Chunk $chunk - * - * @return string - */ protected function nbtSerialize(Chunk $chunk) : string{ $nbt = new CompoundTag("Level", []); $nbt->setInt("xPos", $chunk->getX()); @@ -127,9 +122,6 @@ class McRegion extends BaseLevelProvider{ } /** - * @param string $data - * - * @return Chunk * @throws CorruptedChunkException */ protected function nbtDeserialize(string $data) : Chunk{ @@ -206,9 +198,6 @@ class McRegion extends BaseLevelProvider{ } /** - * @param string $context - * @param ListTag $list - * * @return CompoundTag[] * @throws CorruptedChunkException */ @@ -236,7 +225,6 @@ class McRegion extends BaseLevelProvider{ /** * Returns the storage version as per Minecraft PC world formats. - * @return int */ public static function getPcWorldFormatVersion() : int{ return 19132; //mcregion @@ -251,7 +239,7 @@ class McRegion extends BaseLevelProvider{ $isValid = (file_exists($path . "/level.dat") and is_dir($path . "/region/")); if($isValid){ - $files = array_filter(scandir($path . "/region/", SCANDIR_SORT_NONE), function($file){ + $files = array_filter(scandir($path . "/region/", SCANDIR_SORT_NONE), function(string $file) : bool{ return substr($file, strrpos($file, ".") + 1, 2) === "mc"; //region file }); @@ -329,10 +317,10 @@ class McRegion extends BaseLevelProvider{ } /** - * @param int $chunkX - * @param int $chunkZ - * @param int &$regionX - * @param int &$regionZ + * @param int $regionX reference parameter + * @param int $regionZ reference parameter + * + * @return void */ public static function getRegionIndex(int $chunkX, int $chunkZ, &$regionX, &$regionZ){ $regionX = $chunkX >> 5; @@ -340,9 +328,6 @@ class McRegion extends BaseLevelProvider{ } /** - * @param int $regionX - * @param int $regionZ - * * @return RegionLoader|null */ protected function getRegion(int $regionX, int $regionZ){ @@ -351,19 +336,13 @@ class McRegion extends BaseLevelProvider{ /** * Returns the path to a specific region file based on its X/Z coordinates - * - * @param int $regionX - * @param int $regionZ - * - * @return string */ protected function pathToRegion(int $regionX, int $regionZ) : string{ return $this->path . "region/r.$regionX.$regionZ." . static::REGION_FILE_EXTENSION; } /** - * @param int $regionX - * @param int $regionZ + * @return void */ protected function loadRegion(int $regionX, int $regionZ){ if(!isset($this->regions[$index = Level::chunkHash($regionX, $regionZ)])){ @@ -398,11 +377,6 @@ class McRegion extends BaseLevelProvider{ } /** - * @param int $chunkX - * @param int $chunkZ - * - * @return Chunk|null - * * @throws CorruptedChunkException */ protected function readChunk(int $chunkX, int $chunkZ) : ?Chunk{ diff --git a/src/pocketmine/level/format/io/region/RegionException.php b/src/pocketmine/level/format/io/region/RegionException.php index 4118a00d32..d3e3a6bf17 100644 --- a/src/pocketmine/level/format/io/region/RegionException.php +++ b/src/pocketmine/level/format/io/region/RegionException.php @@ -21,10 +21,8 @@ declare(strict_types=1); - namespace pocketmine\level\format\io\region; - class RegionException extends \RuntimeException{ } diff --git a/src/pocketmine/level/format/io/region/RegionLoader.php b/src/pocketmine/level/format/io/region/RegionLoader.php index 6c64a2489e..87383a3a63 100644 --- a/src/pocketmine/level/format/io/region/RegionLoader.php +++ b/src/pocketmine/level/format/io/region/RegionLoader.php @@ -62,6 +62,7 @@ class RegionLoader{ private const FIRST_SECTOR = 2; //location table occupies 0 and 1 + /** @var int */ public static $COMPRESSION_LEVEL = 7; /** @var int */ @@ -86,6 +87,7 @@ class RegionLoader{ } /** + * @return void * @throws CorruptedRegionException */ public function open(){ @@ -120,10 +122,6 @@ class RegionLoader{ } /** - * @param int $x - * @param int $z - * - * @return null|string * @throws \InvalidArgumentException if invalid coordinates are given * @throws CorruptedChunkException if chunk corruption is detected */ @@ -172,10 +170,6 @@ class RegionLoader{ } /** - * @param int $x - * @param int $z - * - * @return bool * @throws \InvalidArgumentException */ public function chunkExists(int $x, int $z) : bool{ @@ -183,10 +177,7 @@ class RegionLoader{ } /** - * @param int $x - * @param int $z - * @param string $chunkData - * + * @return void * @throws ChunkException * @throws \InvalidArgumentException */ @@ -216,9 +207,7 @@ class RegionLoader{ } /** - * @param int $x - * @param int $z - * + * @return void * @throws \InvalidArgumentException */ public function removeChunk(int $x, int $z){ @@ -228,10 +217,6 @@ class RegionLoader{ } /** - * @param int $x - * @param int $z - * - * @return int * @throws \InvalidArgumentException */ protected static function getChunkOffset(int $x, int $z) : int{ @@ -242,9 +227,8 @@ class RegionLoader{ } /** - * @param int $offset - * @param int &$x - * @param int &$z + * @param int $x reference parameter + * @param int $z reference parameter */ protected static function getChunkCoords(int $offset, ?int &$x, ?int &$z) : void{ $x = $offset & 0x1f; @@ -254,7 +238,7 @@ class RegionLoader{ /** * Writes the region header and closes the file * - * @param bool $writeHeader + * @return void */ public function close(bool $writeHeader = true){ if(is_resource($this->filePointer)){ @@ -267,6 +251,7 @@ class RegionLoader{ } /** + * @return void * @throws CorruptedRegionException */ protected function loadLocationTable(){ @@ -328,7 +313,7 @@ class RegionLoader{ } } - private function writeLocationTable(){ + private function writeLocationTable() : void{ $write = []; for($i = 0; $i < 1024; ++$i){ @@ -341,6 +326,11 @@ class RegionLoader{ fwrite($this->filePointer, pack("N*", ...$write), 4096 * 2); } + /** + * @param int $index + * + * @return void + */ protected function writeLocationIndex($index){ fseek($this->filePointer, $index << 2); fwrite($this->filePointer, Binary::writeInt(($this->locationTable[$index]->getFirstSector() << 8) | $this->locationTable[$index]->getSectorCount()), 4); @@ -348,6 +338,9 @@ class RegionLoader{ fwrite($this->filePointer, Binary::writeInt($this->locationTable[$index]->getTimestamp()), 4); } + /** + * @return void + */ protected function createBlank(){ fseek($this->filePointer, 0); ftruncate($this->filePointer, 8192); // this fills the file with the null byte diff --git a/src/pocketmine/level/format/io/region/RegionLocationTableEntry.php b/src/pocketmine/level/format/io/region/RegionLocationTableEntry.php index f17ae5bdc5..167a9786a5 100644 --- a/src/pocketmine/level/format/io/region/RegionLocationTableEntry.php +++ b/src/pocketmine/level/format/io/region/RegionLocationTableEntry.php @@ -35,10 +35,6 @@ class RegionLocationTableEntry{ private $timestamp; /** - * @param int $firstSector - * @param int $sectorCount - * @param int $timestamp - * * @throws \InvalidArgumentException */ public function __construct(int $firstSector, int $sectorCount, int $timestamp){ @@ -53,16 +49,10 @@ class RegionLocationTableEntry{ $this->timestamp = $timestamp; } - /** - * @return int - */ public function getFirstSector() : int{ return $this->firstSector; } - /** - * @return int - */ public function getLastSector() : int{ return $this->firstSector + $this->sectorCount - 1; } @@ -75,23 +65,14 @@ class RegionLocationTableEntry{ return range($this->getFirstSector(), $this->getLastSector()); } - /** - * @return int - */ public function getSectorCount() : int{ return $this->sectorCount; } - /** - * @return int - */ public function getTimestamp() : int{ return $this->timestamp; } - /** - * @return bool - */ public function isNull() : bool{ return $this->firstSector === 0 or $this->sectorCount === 0; } diff --git a/src/pocketmine/level/generator/Flat.php b/src/pocketmine/level/generator/Flat.php index c3672ba8e0..24c4888d38 100644 --- a/src/pocketmine/level/generator/Flat.php +++ b/src/pocketmine/level/generator/Flat.php @@ -44,13 +44,19 @@ class Flat extends Generator{ private $chunk; /** @var Populator[] */ private $populators = []; - /** @var int[][] */ + /** + * @var int[][] + * @phpstan-var array + */ private $structure; /** @var int */ private $floorLevel; /** @var int */ private $biome; - /** @var mixed[] */ + /** + * @var mixed[] + * @phpstan-var array + */ private $options; /** @var string */ private $preset; @@ -64,7 +70,8 @@ class Flat extends Generator{ } /** - * @param array $options + * @param mixed[] $options + * @phpstan-param array $options * * @throws InvalidGeneratorOptionsException */ @@ -96,9 +103,9 @@ class Flat extends Generator{ } /** - * @param string $layers - * * @return int[][] + * @phpstan-return array + * * @throws InvalidGeneratorOptionsException */ public static function parseLayers(string $layers) : array{ @@ -127,9 +134,9 @@ class Flat extends Generator{ protected function parsePreset() : void{ $preset = explode(";", $this->preset); - $blocks = (string) ($preset[1] ?? ""); + $blocks = $preset[1] ?? ""; $this->biome = (int) ($preset[2] ?? 1); - $options = (string) ($preset[3] ?? ""); + $options = $preset[3] ?? ""; $this->structure = self::parseLayers($blocks); $this->floorLevel = count($this->structure); diff --git a/src/pocketmine/level/generator/Generator.php b/src/pocketmine/level/generator/Generator.php index 1330cb65c3..fa44ad9d31 100644 --- a/src/pocketmine/level/generator/Generator.php +++ b/src/pocketmine/level/generator/Generator.php @@ -36,10 +36,6 @@ abstract class Generator{ /** * Converts a string level seed into an integer for use by the generator. - * - * @param string $seed - * - * @return int|null */ public static function convertSeed(string $seed) : ?int{ if($seed === ""){ //empty seed should cause a random seed to be selected - can't use 0 here because 0 is a valid seed @@ -59,13 +55,13 @@ abstract class Generator{ protected $random; /** - * @param array $settings - * * @throws InvalidGeneratorOptionsException + * + * @param mixed[] $settings + * @phpstan-param array $settings */ abstract public function __construct(array $settings = []); - public function init(ChunkManager $level, Random $random) : void{ $this->level = $level; $this->random = $random; @@ -75,6 +71,10 @@ abstract class Generator{ abstract public function populateChunk(int $chunkX, int $chunkZ) : void; + /** + * @return mixed[] + * @phpstan-return array + */ abstract public function getSettings() : array; abstract public function getName() : string; diff --git a/src/pocketmine/level/generator/GeneratorManager.php b/src/pocketmine/level/generator/GeneratorManager.php index 013fe90310..1f370f26cf 100644 --- a/src/pocketmine/level/generator/GeneratorManager.php +++ b/src/pocketmine/level/generator/GeneratorManager.php @@ -30,7 +30,10 @@ use function is_subclass_of; use function strtolower; final class GeneratorManager{ - /** @var string[] name => classname mapping */ + /** + * @var string[] name => classname mapping + * @phpstan-var array> + */ private static $list = []; /** @@ -48,6 +51,7 @@ final class GeneratorManager{ * @param string $class Fully qualified name of class that extends \pocketmine\level\generator\Generator * @param string $name Alias for this generator type that can be written in configs * @param bool $overwrite Whether to force overwriting any existing registered generator with the same name + * @phpstan-param class-string $class */ public static function addGenerator(string $class, string $name, bool $overwrite = false) : void{ if(!is_subclass_of($class, Generator::class)){ @@ -73,10 +77,11 @@ final class GeneratorManager{ /** * Returns a class name of a registered Generator matching the given name. * - * @param string $name * @param bool $throwOnMissing @deprecated this is for backwards compatibility only * - * @return string|Generator Name of class that extends Generator (not an actual Generator object) + * @return string Name of class that extends Generator + * @phpstan-return class-string + * * @throws \InvalidArgumentException if the generator type isn't registered */ public static function getGenerator(string $name, bool $throwOnMissing = false){ @@ -94,8 +99,7 @@ final class GeneratorManager{ * Returns the registered name of the given Generator class. * * @param string $class Fully qualified name of class that extends \pocketmine\level\generator\Generator - * - * @return string + * @phpstan-param class-string $class */ public static function getGeneratorName(string $class) : string{ foreach(self::$list as $name => $c){ diff --git a/src/pocketmine/level/generator/GeneratorRegisterTask.php b/src/pocketmine/level/generator/GeneratorRegisterTask.php index f56ad5b21c..715d3cff56 100644 --- a/src/pocketmine/level/generator/GeneratorRegisterTask.php +++ b/src/pocketmine/level/generator/GeneratorRegisterTask.php @@ -34,12 +34,21 @@ use function unserialize; class GeneratorRegisterTask extends AsyncTask{ + /** @var string */ public $generatorClass; + /** @var string */ public $settings; + /** @var int */ public $seed; + /** @var int */ public $levelId; + /** @var int */ public $worldHeight = Level::Y_MAX; + /** + * @param mixed[] $generatorSettings + * @phpstan-param array $generatorSettings + */ public function __construct(Level $level, string $generatorClass, array $generatorSettings = []){ $this->generatorClass = $generatorClass; $this->settings = serialize($generatorSettings); diff --git a/src/pocketmine/level/generator/GeneratorUnregisterTask.php b/src/pocketmine/level/generator/GeneratorUnregisterTask.php index 780268cac2..597c2fe4f5 100644 --- a/src/pocketmine/level/generator/GeneratorUnregisterTask.php +++ b/src/pocketmine/level/generator/GeneratorUnregisterTask.php @@ -28,6 +28,7 @@ use pocketmine\scheduler\AsyncTask; class GeneratorUnregisterTask extends AsyncTask{ + /** @var int */ public $levelId; public function __construct(Level $level){ diff --git a/src/pocketmine/level/generator/PopulationTask.php b/src/pocketmine/level/generator/PopulationTask.php index d061c415b2..95019457ab 100644 --- a/src/pocketmine/level/generator/PopulationTask.php +++ b/src/pocketmine/level/generator/PopulationTask.php @@ -31,18 +31,31 @@ use pocketmine\Server; class PopulationTask extends AsyncTask{ + /** @var bool */ public $state; + /** @var int */ public $levelId; + /** @var string */ public $chunk; + /** @var string */ public $chunk0; + /** @var string */ public $chunk1; + /** @var string */ public $chunk2; + /** @var string */ public $chunk3; + //center chunk + + /** @var string */ public $chunk5; + /** @var string */ public $chunk6; + /** @var string */ public $chunk7; + /** @var string */ public $chunk8; public function __construct(Level $level, Chunk $chunk){ @@ -89,48 +102,26 @@ class PopulationTask extends AsyncTask{ } foreach($chunks as $c){ - if($c !== null){ - $manager->setChunk($c->getX(), $c->getZ(), $c); - if(!$c->isGenerated()){ - $generator->generateChunk($c->getX(), $c->getZ()); - $c = $manager->getChunk($c->getX(), $c->getZ()); - $c->setGenerated(); - } + $manager->setChunk($c->getX(), $c->getZ(), $c); + if(!$c->isGenerated()){ + $generator->generateChunk($c->getX(), $c->getZ()); + $c->setGenerated(); } } $generator->populateChunk($chunk->getX(), $chunk->getZ()); - $chunk = $manager->getChunk($chunk->getX(), $chunk->getZ()); $chunk->recalculateHeightMap(); $chunk->populateSkyLight(); $chunk->setLightPopulated(); $chunk->setPopulated(); $this->chunk = $chunk->fastSerialize(); - $manager->setChunk($chunk->getX(), $chunk->getZ(), null); - foreach($chunks as $i => $c){ - if($c !== null){ - $c = $chunks[$i] = $manager->getChunk($c->getX(), $c->getZ()); - if(!$c->hasChanged()){ - $chunks[$i] = null; - } - }else{ - //This way non-changed chunks are not set - $chunks[$i] = null; - } + $this->{"chunk$i"} = $c->hasChanged() ? $c->fastSerialize() : null; } $manager->cleanChunks(); - - for($i = 0; $i < 9; ++$i){ - if($i === 4){ - continue; - } - - $this->{"chunk$i"} = $chunks[$i] !== null ? $chunks[$i]->fastSerialize() : null; - } } public function onCompletion(Server $server){ diff --git a/src/pocketmine/level/generator/biome/BiomeSelector.php b/src/pocketmine/level/generator/biome/BiomeSelector.php index d5496775ad..4688e9e88d 100644 --- a/src/pocketmine/level/generator/biome/BiomeSelector.php +++ b/src/pocketmine/level/generator/biome/BiomeSelector.php @@ -34,7 +34,10 @@ abstract class BiomeSelector{ /** @var Simplex */ private $rainfall; - /** @var Biome[]|\SplFixedArray */ + /** + * @var Biome[]|\SplFixedArray + * @phpstan-var \SplFixedArray + */ private $map = null; public function __construct(Random $random){ @@ -45,13 +48,13 @@ abstract class BiomeSelector{ /** * Lookup function called by recalculate() to determine the biome to use for this temperature and rainfall. * - * @param float $temperature - * @param float $rainfall - * * @return int biome ID 0-255 */ abstract protected function lookup(float $temperature, float $rainfall) : int; + /** + * @return void + */ public function recalculate(){ $this->map = new \SplFixedArray(64 * 64); @@ -66,20 +69,29 @@ abstract class BiomeSelector{ } } + /** + * @param float $x + * @param float $z + * + * @return float + */ public function getTemperature($x, $z){ return ($this->temperature->noise2D($x, $z, true) + 1) / 2; } + /** + * @param float $x + * @param float $z + * + * @return float + */ public function getRainfall($x, $z){ return ($this->rainfall->noise2D($x, $z, true) + 1) / 2; } /** - * TODO: not sure on types here - * @param int|float $x - * @param int|float $z - * - * @return Biome + * @param int $x + * @param int $z */ public function pickBiome($x, $z) : Biome{ $temperature = (int) ($this->getTemperature($x, $z) * 63); diff --git a/src/pocketmine/level/generator/hell/Nether.php b/src/pocketmine/level/generator/hell/Nether.php index 110d3687b9..4b1d8aaab0 100644 --- a/src/pocketmine/level/generator/hell/Nether.php +++ b/src/pocketmine/level/generator/hell/Nether.php @@ -53,7 +53,8 @@ class Nether extends Generator{ private $noiseBase; /** - * @param array $options + * @param mixed[] $options + * @phpstan-param array $options * * @throws InvalidGeneratorOptionsException */ diff --git a/src/pocketmine/level/generator/noise/Noise.php b/src/pocketmine/level/generator/noise/Noise.php index f0b4b6b508..727dd82998 100644 --- a/src/pocketmine/level/generator/noise/Noise.php +++ b/src/pocketmine/level/generator/noise/Noise.php @@ -26,35 +26,79 @@ declare(strict_types=1); */ namespace pocketmine\level\generator\noise; - use function array_fill; use function assert; abstract class Noise{ + /** @var int[] */ protected $perm = []; + /** @var float */ protected $offsetX = 0; + /** @var float */ protected $offsetY = 0; + /** @var float */ protected $offsetZ = 0; + /** @var int */ protected $octaves = 8; + /** @var float */ protected $persistence; + /** @var float */ protected $expansion; + /** + * @param float $x + */ public static function floor($x) : int{ return $x >= 0 ? (int) $x : (int) ($x - 1); } + /** + * @param float $x + * + * @return float + */ public static function fade($x){ return $x * $x * $x * ($x * ($x * 6 - 15) + 10); } + /** + * @param float $x + * @param float $y + * @param float $z + * + * @return float + */ public static function lerp($x, $y, $z){ return $y + $x * ($z - $y); } + /** + * @param float $x + * @param float $x1 + * @param float $x2 + * @param float $q0 + * @param float $q1 + * + * @return float + */ public static function linearLerp($x, $x1, $x2, $q0, $q1){ return (($x2 - $x) / ($x2 - $x1)) * $q0 + (($x - $x1) / ($x2 - $x1)) * $q1; } + /** + * @param float $x + * @param float $y + * @param float $q00 + * @param float $q01 + * @param float $q10 + * @param float $q11 + * @param float $x1 + * @param float $x2 + * @param float $y1 + * @param float $y2 + * + * @return float + */ public static function bilinearLerp($x, $y, $q00, $q01, $q10, $q11, $x1, $x2, $y1, $y2){ $dx1 = (($x2 - $x) / ($x2 - $x1)); $dx2 = (($x - $x1) / ($x2 - $x1)); @@ -66,6 +110,27 @@ abstract class Noise{ ); } + /** + * @param float $x + * @param float $y + * @param float $z + * @param float $q000 + * @param float $q001 + * @param float $q010 + * @param float $q011 + * @param float $q100 + * @param float $q101 + * @param float $q110 + * @param float $q111 + * @param float $x1 + * @param float $x2 + * @param float $y1 + * @param float $y2 + * @param float $z1 + * @param float $z2 + * + * @return float + */ public static function trilinearLerp($x, $y, $z, $q000, $q001, $q010, $q011, $q100, $q101, $q110, $q111, $x1, $x2, $y1, $y2, $z1, $z2){ $dx1 = (($x2 - $x) / ($x2 - $x1)); $dx2 = (($x - $x1) / ($x2 - $x1)); @@ -87,6 +152,14 @@ abstract class Noise{ ); } + /** + * @param int $hash + * @param float $x + * @param float $y + * @param float $z + * + * @return float + */ public static function grad($hash, $x, $y, $z){ $hash &= 15; $u = $hash < 8 ? $x : $y; @@ -95,10 +168,30 @@ abstract class Noise{ return (($hash & 1) === 0 ? $u : -$u) + (($hash & 2) === 0 ? $v : -$v); } + /** + * @param float $x + * @param float $z + * + * @return float + */ abstract public function getNoise2D($x, $z); + /** + * @param float $x + * @param float $y + * @param float $z + * + * @return float + */ abstract public function getNoise3D($x, $y, $z); + /** + * @param float $x + * @param float $z + * @param bool $normalized + * + * @return float + */ public function noise2D($x, $z, $normalized = false){ $result = 0; $amp = 1; @@ -122,6 +215,14 @@ abstract class Noise{ return $result; } + /** + * @param float $x + * @param float $y + * @param float $z + * @param bool $normalized + * + * @return float + */ public function noise3D($x, $y, $z, $normalized = false){ $result = 0; $amp = 1; @@ -146,15 +247,9 @@ abstract class Noise{ return $result; } - /** - * @param int $xSize - * @param int $samplingRate - * @param int $x - * @param int $y - * @param int $z - * - * @return \SplFixedArray + * @return \SplFixedArray|float[] + * @phpstan-return \SplFixedArray */ public function getFastNoise1D(int $xSize, int $samplingRate, int $x, int $y, int $z) : \SplFixedArray{ if($samplingRate === 0){ @@ -181,14 +276,8 @@ abstract class Noise{ } /** - * @param int $xSize - * @param int $zSize - * @param int $samplingRate - * @param int $x - * @param int $y - * @param int $z - * - * @return \SplFixedArray + * @return \SplFixedArray|float[][] + * @phpstan-return \SplFixedArray<\SplFixedArray> */ public function getFastNoise2D(int $xSize, int $zSize, int $samplingRate, int $x, int $y, int $z) : \SplFixedArray{ assert($samplingRate !== 0, new \InvalidArgumentException("samplingRate cannot be 0")); @@ -227,17 +316,7 @@ abstract class Noise{ } /** - * @param int $xSize - * @param int $ySize - * @param int $zSize - * @param int $xSamplingRate - * @param int $ySamplingRate - * @param int $zSamplingRate - * @param int $x - * @param int $y - * @param int $z - * - * @return array + * @return float[][][] */ public function getFastNoise3D(int $xSize, int $ySize, int $zSize, int $xSamplingRate, int $ySamplingRate, int $zSamplingRate, int $x, int $y, int $z) : array{ @@ -297,6 +376,13 @@ abstract class Noise{ return $noiseArray; } + /** + * @param float $x + * @param float $y + * @param float $z + * + * @return void + */ public function setOffset($x, $y, $z){ $this->offsetX = $x; $this->offsetY = $y; diff --git a/src/pocketmine/level/generator/noise/Perlin.php b/src/pocketmine/level/generator/noise/Perlin.php index 84b2ab2c2e..e0b37f3972 100644 --- a/src/pocketmine/level/generator/noise/Perlin.php +++ b/src/pocketmine/level/generator/noise/Perlin.php @@ -26,13 +26,18 @@ namespace pocketmine\level\generator\noise; use pocketmine\utils\Random; class Perlin extends Noise{ + /** @var int[][] */ public static $grad3 = [ [1, 1, 0], [-1, 1, 0], [1, -1, 0], [-1, -1, 0], [1, 0, 1], [-1, 0, 1], [1, 0, -1], [-1, 0, -1], [0, 1, 1], [0, -1, 1], [0, 1, -1], [0, -1, -1] ]; - + /** + * @param int $octaves + * @param float $persistence + * @param float $expansion + */ public function __construct(Random $random, $octaves, $persistence, $expansion = 1){ $this->octaves = $octaves; $this->persistence = $persistence; @@ -144,6 +149,12 @@ class Perlin extends Noise{ */ } + /** + * @param float $x + * @param float $y + * + * @return float + */ public function getNoise2D($x, $y){ return $this->getNoise3D($x, $y, 0); } diff --git a/src/pocketmine/level/generator/noise/Simplex.php b/src/pocketmine/level/generator/noise/Simplex.php index be2de635f2..47c5e7b814 100644 --- a/src/pocketmine/level/generator/noise/Simplex.php +++ b/src/pocketmine/level/generator/noise/Simplex.php @@ -34,18 +34,31 @@ use function sqrt; * http://staffwww.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf */ class Simplex extends Perlin{ + /** @var float */ protected static $SQRT_3; + /** @var float */ protected static $SQRT_5; + /** @var float */ protected static $F2; + /** @var float */ protected static $G2; + /** @var float */ protected static $G22; + /** @var float */ protected static $F3; + /** @var float */ protected static $G3; + /** @var float */ protected static $F4; + /** @var float */ protected static $G4; + /** @var float */ protected static $G42; + /** @var float */ protected static $G43; + /** @var float */ protected static $G44; + /** @var int[][] */ protected static $grad4 = [[0, 1, 1, 1], [0, 1, 1, -1], [0, 1, -1, 1], [0, 1, -1, -1], [0, -1, 1, 1], [0, -1, 1, -1], [0, -1, -1, 1], [0, -1, -1, -1], [1, 0, 1, 1], [1, 0, 1, -1], [1, 0, -1, 1], [1, 0, -1, -1], @@ -54,6 +67,8 @@ class Simplex extends Perlin{ [-1, 1, 0, 1], [-1, 1, 0, -1], [-1, -1, 0, 1], [-1, -1, 0, -1], [1, 1, 1, 0], [1, 1, -1, 0], [1, -1, 1, 0], [1, -1, -1, 0], [-1, 1, 1, 0], [-1, 1, -1, 0], [-1, -1, 1, 0], [-1, -1, -1, 0]]; + + /** @var int[][] */ protected static $simplex = [ [0, 1, 2, 3], [0, 1, 3, 2], [0, 0, 0, 0], [0, 2, 3, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 2, 3, 0], [0, 2, 1, 3], [0, 0, 0, 0], [0, 3, 1, 2], [0, 3, 2, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 3, 2, 0], @@ -63,9 +78,15 @@ class Simplex extends Perlin{ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 0, 1, 3], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [3, 0, 1, 2], [3, 0, 2, 1], [0, 0, 0, 0], [3, 1, 2, 0], [2, 1, 0, 3], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [3, 1, 0, 2], [0, 0, 0, 0], [3, 2, 0, 1], [3, 2, 1, 0]]; + + /** @var float */ protected $offsetW; - + /** + * @param int $octaves + * @param float $persistence + * @param float $expansion + */ public function __construct(Random $random, $octaves, $persistence, $expansion = 1){ parent::__construct($random, $octaves, $persistence, $expansion); $this->offsetW = $random->nextFloat() * 256; @@ -83,14 +104,38 @@ class Simplex extends Perlin{ self::$G44 = self::$G4 * 4.0 - 1.0; } + /** + * @param int[] $g + * @param float $x + * @param float $y + * + * @return float + */ protected static function dot2D($g, $x, $y){ return $g[0] * $x + $g[1] * $y; } + /** + * @param int[] $g + * @param float $x + * @param float $y + * @param float $z + * + * @return float + */ protected static function dot3D($g, $x, $y, $z){ return $g[0] * $x + $g[1] * $y + $g[2] * $z; } + /** + * @param int[] $g + * @param float $x + * @param float $y + * @param float $z + * @param float $w + * + * @return float + */ protected static function dot4D($g, $x, $y, $z, $w){ return $g[0] * $x + $g[1] * $y + $g[2] * $z + $g[3] * $w; } @@ -219,6 +264,12 @@ class Simplex extends Perlin{ return 32.0 * $n; } + /** + * @param float $x + * @param float $y + * + * @return float + */ public function getNoise2D($x, $y){ $x += $this->offsetX; $y += $this->offsetY; diff --git a/src/pocketmine/level/generator/normal/Normal.php b/src/pocketmine/level/generator/normal/Normal.php index cfb7ea65e4..86dfc6b96d 100644 --- a/src/pocketmine/level/generator/normal/Normal.php +++ b/src/pocketmine/level/generator/normal/Normal.php @@ -55,11 +55,14 @@ class Normal extends Generator{ /** @var BiomeSelector */ private $selector; + /** @var float[][]|null */ private static $GAUSSIAN_KERNEL = null; + /** @var int */ private static $SMOOTH_SIZE = 2; /** - * @param array $options + * @param mixed[] $options + * @phpstan-param array $options * * @throws InvalidGeneratorOptionsException */ diff --git a/src/pocketmine/level/generator/object/BigTree.php b/src/pocketmine/level/generator/object/BigTree.php index 0306c6b726..0e1951f5f7 100644 --- a/src/pocketmine/level/generator/object/BigTree.php +++ b/src/pocketmine/level/generator/object/BigTree.php @@ -26,60 +26,19 @@ namespace pocketmine\level\generator\object; use pocketmine\level\ChunkManager; use pocketmine\utils\Random; +/** + * @deprecated + */ class BigTree extends Tree{ - private $trunkHeightMultiplier = 0.618; - private $trunkHeight; - private $leafAmount = 1; - private $leafDistanceLimit = 5; - private $widthScale = 1; - private $branchSlope = 0.381; - - private $totalHeight = 6; - private $leavesHeight = 3; - protected $radiusIncrease = 0; - private $addLeavesVines = false; - private $addLogVines = false; - private $addCocoaPlants = false; public function canPlaceObject(ChunkManager $level, int $x, int $y, int $z, Random $random) : bool{ return false; } + /** + * @return void + */ public function placeObject(ChunkManager $level, int $x, int $y, int $z, Random $random){ - /*$this->trunkHeight = (int) ($this->totalHeight * $this->trunkHeightMultiplier); - $leaves = $this->getLeafGroupPoints($level, $pos); - foreach($leaves as $leafGroup){ - $groupX = $leafGroup->getBlockX(); - $groupY = $leafGroup->getBlockY(); - $groupZ = $leafGroup->getBlockZ(); - for($yy = $groupY; $yy < $groupY + $this->leafDistanceLimit; ++$yy){ - $this->generateGroupLayer($level, $groupX, $yy, $groupZ, $this->getLeafGroupLayerSize($yy - $groupY)); - } - } - final BlockIterator trunk = new BlockIterator(new Point(w, x, y - 1, z), new Point(w, x, y + trunkHeight, z)); - while (trunk.hasNext()) { - trunk.next().setMaterial(VanillaMaterials.LOG, logMetadata); - } - generateBranches(w, x, y, z, leaves); - - $level->setBlock($x, $pos->y - 1, $z, 3, 0); - $this->totalHeight += $random->nextRange(0, 2); - $this->leavesHeight += mt_rand(0, 1); - for($yy = ($this->totalHeight - $this->leavesHeight); $yy < ($this->totalHeight + 1); ++$yy){ - $yRadius = ($yy - $this->totalHeight); - $xzRadius = (int) (($this->radiusIncrease + 1) - $yRadius / 2); - for($xx = -$xzRadius; $xx < ($xzRadius + 1); ++$xx){ - for($zz = -$xzRadius; $zz < ($xzRadius + 1); ++$zz){ - if((abs($xx) != $xzRadius or abs($zz) != $xzRadius) and $yRadius != 0){ - $level->setBlock($pos->x + $xx, $pos->y + $yy, $pos->z + $zz, 18, $this->type); - } - } - } - } - for($yy = 0; $yy < ($this->totalHeight - 1); ++$yy){ - $level->setBlock($x, $pos->y + $yy, $z, 17, $this->type); - } - */ } } diff --git a/src/pocketmine/level/generator/object/BirchTree.php b/src/pocketmine/level/generator/object/BirchTree.php index 18a3cc9f56..453973c2de 100644 --- a/src/pocketmine/level/generator/object/BirchTree.php +++ b/src/pocketmine/level/generator/object/BirchTree.php @@ -30,6 +30,7 @@ use pocketmine\utils\Random; class BirchTree extends Tree{ + /** @var bool */ protected $superBirch = false; public function __construct(bool $superBirch = false){ @@ -39,6 +40,9 @@ class BirchTree extends Tree{ $this->superBirch = $superBirch; } + /** + * @return void + */ public function placeObject(ChunkManager $level, int $x, int $y, int $z, Random $random){ $this->treeHeight = $random->nextBoundedInt(3) + 5; if($this->superBirch){ diff --git a/src/pocketmine/level/generator/object/OakTree.php b/src/pocketmine/level/generator/object/OakTree.php index 47865de7ee..b11757ba5f 100644 --- a/src/pocketmine/level/generator/object/OakTree.php +++ b/src/pocketmine/level/generator/object/OakTree.php @@ -36,6 +36,9 @@ class OakTree extends Tree{ $this->type = Wood::OAK; } + /** + * @return void + */ public function placeObject(ChunkManager $level, int $x, int $y, int $z, Random $random){ $this->treeHeight = $random->nextBoundedInt(3) + 4; parent::placeObject($level, $x, $y, $z, $random); diff --git a/src/pocketmine/level/generator/object/Ore.php b/src/pocketmine/level/generator/object/Ore.php index ad1f5da3c0..92d9683951 100644 --- a/src/pocketmine/level/generator/object/Ore.php +++ b/src/pocketmine/level/generator/object/Ore.php @@ -49,6 +49,9 @@ class Ore{ return $level->getBlockIdAt($x, $y, $z) === Block::STONE; } + /** + * @return void + */ public function placeObject(ChunkManager $level, int $x, int $y, int $z){ $clusterSize = $this->type->clusterSize; $angle = $this->random->nextFloat() * M_PI; @@ -72,24 +75,24 @@ class Ore{ $endY = (int) ($seedY + $size); $endZ = (int) ($seedZ + $size); - for($x = $startX; $x <= $endX; ++$x){ - $sizeX = ($x + 0.5 - $seedX) / $size; + for($xx = $startX; $xx <= $endX; ++$xx){ + $sizeX = ($xx + 0.5 - $seedX) / $size; $sizeX *= $sizeX; if($sizeX < 1){ - for($y = $startY; $y <= $endY; ++$y){ - $sizeY = ($y + 0.5 - $seedY) / $size; + for($yy = $startY; $yy <= $endY; ++$yy){ + $sizeY = ($yy + 0.5 - $seedY) / $size; $sizeY *= $sizeY; - if($y > 0 and ($sizeX + $sizeY) < 1){ - for($z = $startZ; $z <= $endZ; ++$z){ - $sizeZ = ($z + 0.5 - $seedZ) / $size; + if($yy > 0 and ($sizeX + $sizeY) < 1){ + for($zz = $startZ; $zz <= $endZ; ++$zz){ + $sizeZ = ($zz + 0.5 - $seedZ) / $size; $sizeZ *= $sizeZ; - if(($sizeX + $sizeY + $sizeZ) < 1 and $level->getBlockIdAt($x, $y, $z) === Block::STONE){ - $level->setBlockIdAt($x, $y, $z, $this->type->material->getId()); + if(($sizeX + $sizeY + $sizeZ) < 1 and $level->getBlockIdAt($xx, $yy, $zz) === Block::STONE){ + $level->setBlockIdAt($xx, $yy, $zz, $this->type->material->getId()); if($this->type->material->getDamage() !== 0){ - $level->setBlockDataAt($x, $y, $z, $this->type->material->getDamage()); + $level->setBlockDataAt($xx, $yy, $zz, $this->type->material->getDamage()); } } } diff --git a/src/pocketmine/level/generator/object/Pond.php b/src/pocketmine/level/generator/object/Pond.php index 560d644648..f547239be4 100644 --- a/src/pocketmine/level/generator/object/Pond.php +++ b/src/pocketmine/level/generator/object/Pond.php @@ -29,7 +29,9 @@ use pocketmine\math\Vector3; use pocketmine\utils\Random; class Pond{ + /** @var Random */ private $random; + /** @var Block */ public $type; public function __construct(Random $random, Block $type){ @@ -41,6 +43,9 @@ class Pond{ return false; } + /** + * @return void + */ public function placeObject(ChunkManager $level, Vector3 $pos){ } diff --git a/src/pocketmine/level/generator/object/PopulatorObject.php b/src/pocketmine/level/generator/object/PopulatorObject.php index 0b7b0def64..63a11647d2 100644 --- a/src/pocketmine/level/generator/object/PopulatorObject.php +++ b/src/pocketmine/level/generator/object/PopulatorObject.php @@ -26,7 +26,6 @@ declare(strict_types=1); */ namespace pocketmine\level\generator\object; - abstract class PopulatorObject{ } diff --git a/src/pocketmine/level/generator/object/SpruceTree.php b/src/pocketmine/level/generator/object/SpruceTree.php index 78a8578b87..5dddbd31c6 100644 --- a/src/pocketmine/level/generator/object/SpruceTree.php +++ b/src/pocketmine/level/generator/object/SpruceTree.php @@ -39,6 +39,9 @@ class SpruceTree extends Tree{ $this->treeHeight = 10; } + /** + * @return void + */ public function placeObject(ChunkManager $level, int $x, int $y, int $z, Random $random){ $this->treeHeight = $random->nextBoundedInt(4) + 6; diff --git a/src/pocketmine/level/generator/object/TallGrass.php b/src/pocketmine/level/generator/object/TallGrass.php index 695b879ade..7457ed0fda 100644 --- a/src/pocketmine/level/generator/object/TallGrass.php +++ b/src/pocketmine/level/generator/object/TallGrass.php @@ -31,6 +31,9 @@ use function count; class TallGrass{ + /** + * @return void + */ public static function growGrass(ChunkManager $level, Vector3 $pos, Random $random, int $count = 15, int $radius = 10){ $arr = [ [Block::DANDELION, 0], diff --git a/src/pocketmine/level/generator/object/Tree.php b/src/pocketmine/level/generator/object/Tree.php index dae3995393..ea16d3d9ca 100644 --- a/src/pocketmine/level/generator/object/Tree.php +++ b/src/pocketmine/level/generator/object/Tree.php @@ -31,6 +31,7 @@ use pocketmine\utils\Random; use function abs; abstract class Tree{ + /** @var bool[] */ public $overridable = [ Block::AIR => true, Block::SAPLING => true, @@ -39,11 +40,18 @@ abstract class Tree{ Block::LEAVES2 => true ]; + /** @var int */ public $type = 0; + /** @var int */ public $trunkBlock = Block::LOG; + /** @var int */ public $leafBlock = Block::LEAVES; + /** @var int */ public $treeHeight = 7; + /** + * @return void + */ public static function growTree(ChunkManager $level, int $x, int $y, int $z, Random $random, int $type = 0){ switch($type){ case Sapling::SPRUCE: @@ -76,7 +84,6 @@ abstract class Tree{ } } - public function canPlaceObject(ChunkManager $level, int $x, int $y, int $z, Random $random) : bool{ $radiusToCheck = 0; for($yy = 0; $yy < $this->treeHeight + 3; ++$yy){ @@ -95,6 +102,9 @@ abstract class Tree{ return true; } + /** + * @return void + */ public function placeObject(ChunkManager $level, int $x, int $y, int $z, Random $random){ $this->placeTrunk($level, $x, $y, $z, $random, $this->treeHeight - 1); @@ -118,6 +128,9 @@ abstract class Tree{ } } + /** + * @return void + */ protected function placeTrunk(ChunkManager $level, int $x, int $y, int $z, Random $random, int $trunkHeight){ // The base dirt block $level->setBlockIdAt($x, $y - 1, $z, Block::DIRT); diff --git a/src/pocketmine/level/generator/populator/GroundCover.php b/src/pocketmine/level/generator/populator/GroundCover.php index 5961a54877..7858bd2dc5 100644 --- a/src/pocketmine/level/generator/populator/GroundCover.php +++ b/src/pocketmine/level/generator/populator/GroundCover.php @@ -47,12 +47,13 @@ class GroundCover extends Populator{ } $column = $chunk->getBlockIdColumn($x, $z); - for($y = 127; $y > 0; --$y){ - if($column[$y] !== "\x00" and !BlockFactory::get(ord($column[$y]))->isTransparent()){ + $startY = 127; + for(; $startY > 0; --$startY){ + if($column[$startY] !== "\x00" and !BlockFactory::get(ord($column[$startY]))->isTransparent()){ break; } } - $startY = min(127, $y + $diffY); + $startY = min(127, $startY + $diffY); $endY = $startY - count($cover); for($y = $startY; $y > $endY and $y >= 0; --$y){ $b = $cover[$startY - $y]; diff --git a/src/pocketmine/level/generator/populator/Ore.php b/src/pocketmine/level/generator/populator/Ore.php index a5b472fa51..a2d962c17b 100644 --- a/src/pocketmine/level/generator/populator/Ore.php +++ b/src/pocketmine/level/generator/populator/Ore.php @@ -48,6 +48,8 @@ class Ore extends Populator{ /** * @param OreType[] $types + * + * @return void */ public function setOreTypes(array $types){ $this->oreTypes = $types; diff --git a/src/pocketmine/level/generator/populator/Pond.php b/src/pocketmine/level/generator/populator/Pond.php index c420cf65dd..7c926dbbc0 100644 --- a/src/pocketmine/level/generator/populator/Pond.php +++ b/src/pocketmine/level/generator/populator/Pond.php @@ -30,8 +30,11 @@ use pocketmine\math\Vector3; use pocketmine\utils\Random; class Pond extends Populator{ + /** @var int */ private $waterOdd = 4; + /** @var int */ private $lavaOdd = 4; + /** @var int */ private $lavaSurfaceOdd = 4; public function populate(ChunkManager $level, int $chunkX, int $chunkZ, Random $random){ @@ -46,14 +49,23 @@ class Pond extends Populator{ } } + /** + * @return void + */ public function setWaterOdd(int $waterOdd){ $this->waterOdd = $waterOdd; } + /** + * @return void + */ public function setLavaOdd(int $lavaOdd){ $this->lavaOdd = $lavaOdd; } + /** + * @return void + */ public function setLavaSurfaceOdd(int $lavaSurfaceOdd){ $this->lavaSurfaceOdd = $lavaSurfaceOdd; } diff --git a/src/pocketmine/level/generator/populator/Populator.php b/src/pocketmine/level/generator/populator/Populator.php index 02fae11ed7..c69d04a03a 100644 --- a/src/pocketmine/level/generator/populator/Populator.php +++ b/src/pocketmine/level/generator/populator/Populator.php @@ -32,11 +32,6 @@ use pocketmine\utils\Random; abstract class Populator{ /** - * @param ChunkManager $level - * @param int $chunkX - * @param int $chunkZ - * @param Random $random - * * @return mixed */ abstract public function populate(ChunkManager $level, int $chunkX, int $chunkZ, Random $random); diff --git a/src/pocketmine/level/generator/populator/TallGrass.php b/src/pocketmine/level/generator/populator/TallGrass.php index 49c8fdb8bc..73f8e1f636 100644 --- a/src/pocketmine/level/generator/populator/TallGrass.php +++ b/src/pocketmine/level/generator/populator/TallGrass.php @@ -30,13 +30,25 @@ use pocketmine\utils\Random; class TallGrass extends Populator{ /** @var ChunkManager */ private $level; + /** @var int */ private $randomAmount = 1; + /** @var int */ private $baseAmount = 0; + /** + * @param int $amount + * + * @return void + */ public function setRandomAmount($amount){ $this->randomAmount = $amount; } + /** + * @param int $amount + * + * @return void + */ public function setBaseAmount($amount){ $this->baseAmount = $amount; } @@ -65,10 +77,10 @@ class TallGrass extends Populator{ for($y = 127; $y >= 0; --$y){ $b = $this->level->getBlockIdAt($x, $y, $z); if($b !== Block::AIR and $b !== Block::LEAVES and $b !== Block::LEAVES2 and $b !== Block::SNOW_LAYER){ - break; + return $y + 1; } } - return $y === 0 ? -1 : ++$y; + return -1; } } diff --git a/src/pocketmine/level/generator/populator/Tree.php b/src/pocketmine/level/generator/populator/Tree.php index edcd48f2c8..997107cf39 100644 --- a/src/pocketmine/level/generator/populator/Tree.php +++ b/src/pocketmine/level/generator/populator/Tree.php @@ -32,19 +32,35 @@ use pocketmine\utils\Random; class Tree extends Populator{ /** @var ChunkManager */ private $level; + /** @var int */ private $randomAmount = 1; + /** @var int */ private $baseAmount = 0; + /** @var int */ private $type; + /** + * @param int $type + */ public function __construct($type = Sapling::OAK){ $this->type = $type; } + /** + * @param int $amount + * + * @return void + */ public function setRandomAmount($amount){ $this->randomAmount = $amount; } + /** + * @param int $amount + * + * @return void + */ public function setBaseAmount($amount){ $this->baseAmount = $amount; } @@ -64,15 +80,15 @@ class Tree extends Populator{ } private function getHighestWorkableBlock(int $x, int $z) : int{ - for($y = 127; $y > 0; --$y){ + for($y = 127; $y >= 0; --$y){ $b = $this->level->getBlockIdAt($x, $y, $z); if($b === Block::DIRT or $b === Block::GRASS){ - break; + return $y + 1; }elseif($b !== Block::AIR and $b !== Block::SNOW_LAYER){ return -1; } } - return ++$y; + return -1; } } diff --git a/src/pocketmine/level/light/LightPopulationTask.php b/src/pocketmine/level/light/LightPopulationTask.php index 6a7ab7a858..26a3913032 100644 --- a/src/pocketmine/level/light/LightPopulationTask.php +++ b/src/pocketmine/level/light/LightPopulationTask.php @@ -31,7 +31,9 @@ use pocketmine\Server; class LightPopulationTask extends AsyncTask{ + /** @var int */ public $levelId; + /** @var string */ public $chunk; public function __construct(Level $level, Chunk $chunk){ diff --git a/src/pocketmine/level/light/LightUpdate.php b/src/pocketmine/level/light/LightUpdate.php index a2c4bc45e1..80bf4689a4 100644 --- a/src/pocketmine/level/light/LightUpdate.php +++ b/src/pocketmine/level/light/LightUpdate.php @@ -59,8 +59,14 @@ abstract class LightUpdate{ abstract protected function getLight(int $x, int $y, int $z) : int; + /** + * @return void + */ abstract protected function setLight(int $x, int $y, int $z, int $level); + /** + * @return void + */ public function setAndUpdateLight(int $x, int $y, int $z, int $newLevel){ $this->updateNodes[Level::blockHash($x, $y, $z)] = [$x, $y, $z, $newLevel]; } @@ -84,6 +90,9 @@ abstract class LightUpdate{ } } + /** + * @return void + */ public function execute(){ $this->prepareNodes(); @@ -137,6 +146,9 @@ abstract class LightUpdate{ } } + /** + * @return void + */ protected function computeRemoveLight(int $x, int $y, int $z, int $oldAdjacentLevel){ $current = $this->getLight($x, $y, $z); @@ -157,6 +169,9 @@ abstract class LightUpdate{ } } + /** + * @return void + */ protected function computeSpreadLight(int $x, int $y, int $z, int $newAdjacentLevel){ $current = $this->getLight($x, $y, $z); $potentialLight = $newAdjacentLevel - BlockFactory::$lightFilter[$this->subChunkHandler->currentSubChunk->getBlockId($x & 0x0f, $y & 0x0f, $z & 0x0f)]; diff --git a/src/pocketmine/level/particle/FloatingTextParticle.php b/src/pocketmine/level/particle/FloatingTextParticle.php index 4ec0ccce2a..20942ec4ba 100644 --- a/src/pocketmine/level/particle/FloatingTextParticle.php +++ b/src/pocketmine/level/particle/FloatingTextParticle.php @@ -39,16 +39,15 @@ use function str_repeat; class FloatingTextParticle extends Particle{ //TODO: HACK! + /** @var string */ protected $text; + /** @var string */ protected $title; - protected $entityId; + /** @var int|null */ + protected $entityId = null; + /** @var bool */ protected $invisible = false; - /** - * @param Vector3 $pos - * @param string $text - * @param string $title - */ public function __construct(Vector3 $pos, string $text, string $title = ""){ parent::__construct($pos->x, $pos->y, $pos->z); $this->text = $text; diff --git a/src/pocketmine/level/particle/Particle.php b/src/pocketmine/level/particle/Particle.php index ec7370857b..785a7e54a1 100644 --- a/src/pocketmine/level/particle/Particle.php +++ b/src/pocketmine/level/particle/Particle.php @@ -29,7 +29,7 @@ use pocketmine\network\mcpe\protocol\DataPacket; abstract class Particle extends Vector3{ public const TYPE_BUBBLE = 1; - //2 same as 1 + public const TYPE_BUBBLE_MANUAL = 2; public const TYPE_CRITICAL = 3; public const TYPE_BLOCK_FORCE_FIELD = 4; public const TYPE_SMOKE = 5; @@ -40,56 +40,61 @@ abstract class Particle extends Vector3{ public const TYPE_LARGE_SMOKE = 10; public const TYPE_REDSTONE = 11; public const TYPE_RISING_RED_DUST = 12; - //62 same as 12 public const TYPE_ITEM_BREAK = 13; public const TYPE_SNOWBALL_POOF = 14; public const TYPE_HUGE_EXPLODE = 15; - //60 same as 15 public const TYPE_HUGE_EXPLODE_SEED = 16; public const TYPE_MOB_FLAME = 17; public const TYPE_HEART = 18; public const TYPE_TERRAIN = 19; public const TYPE_SUSPENDED_TOWN = 20, TYPE_TOWN_AURA = 20; - //61 same as 20 public const TYPE_PORTAL = 21; //22 same as 21 public const TYPE_SPLASH = 23, TYPE_WATER_SPLASH = 23; - //24 same as 23 + public const TYPE_WATER_SPLASH_MANUAL = 24; public const TYPE_WATER_WAKE = 25; public const TYPE_DRIP_WATER = 26; public const TYPE_DRIP_LAVA = 27; - public const TYPE_FALLING_DUST = 28, TYPE_DUST = 28; - public const TYPE_MOB_SPELL = 29; - public const TYPE_MOB_SPELL_AMBIENT = 30; - public const TYPE_MOB_SPELL_INSTANTANEOUS = 31; - public const TYPE_INK = 32; - public const TYPE_SLIME = 33; - public const TYPE_RAIN_SPLASH = 34; - public const TYPE_VILLAGER_ANGRY = 35; - //59 same as 35 - public const TYPE_VILLAGER_HAPPY = 36; - public const TYPE_ENCHANTMENT_TABLE = 37; - public const TYPE_TRACKING_EMITTER = 38; - public const TYPE_NOTE = 39; - public const TYPE_WITCH_SPELL = 40; - public const TYPE_CARROT = 41; - //42 unknown - public const TYPE_END_ROD = 43; - //58 same as 43 - public const TYPE_DRAGONS_BREATH = 44; - public const TYPE_SPIT = 45; - public const TYPE_TOTEM = 46; - public const TYPE_FOOD = 47; - public const TYPE_FIREWORKS_STARTER = 48; - public const TYPE_FIREWORKS_SPARK = 49; - public const TYPE_FIREWORKS_OVERLAY = 50; - public const TYPE_BALLOON_GAS = 51; - public const TYPE_COLORED_FLAME = 52; - public const TYPE_SPARKLER = 53; - public const TYPE_CONDUIT = 54; - public const TYPE_BUBBLE_COLUMN_UP = 55; - public const TYPE_BUBBLE_COLUMN_DOWN = 56; - public const TYPE_SNEEZE = 57; + public const TYPE_DRIP_HONEY = 28; + public const TYPE_FALLING_DUST = 29, TYPE_DUST = 29; + public const TYPE_MOB_SPELL = 30; + public const TYPE_MOB_SPELL_AMBIENT = 31; + public const TYPE_MOB_SPELL_INSTANTANEOUS = 32; + public const TYPE_INK = 33; + public const TYPE_SLIME = 34; + public const TYPE_RAIN_SPLASH = 35; + public const TYPE_VILLAGER_ANGRY = 36; + public const TYPE_VILLAGER_HAPPY = 37; + public const TYPE_ENCHANTMENT_TABLE = 38; + public const TYPE_TRACKING_EMITTER = 39; + public const TYPE_NOTE = 40; + public const TYPE_WITCH_SPELL = 41; + public const TYPE_CARROT = 42; + public const TYPE_MOB_APPEARANCE = 43; + public const TYPE_END_ROD = 44; + public const TYPE_DRAGONS_BREATH = 45; + public const TYPE_SPIT = 46; + public const TYPE_TOTEM = 47; + public const TYPE_FOOD = 48; + public const TYPE_FIREWORKS_STARTER = 49; + public const TYPE_FIREWORKS_SPARK = 50; + public const TYPE_FIREWORKS_OVERLAY = 51; + public const TYPE_BALLOON_GAS = 52; + public const TYPE_COLORED_FLAME = 53; + public const TYPE_SPARKLER = 54; + public const TYPE_CONDUIT = 55; + public const TYPE_BUBBLE_COLUMN_UP = 56; + public const TYPE_BUBBLE_COLUMN_DOWN = 57; + public const TYPE_SNEEZE = 58; + public const TYPE_SHULKER_BULLET = 59; + public const TYPE_BLEACH = 60; + public const TYPE_DRAGON_DESTROY_BLOCK = 61; + public const TYPE_MYCELIUM_DUST = 62; + public const TYPE_FALLING_RED_DUST = 63; + public const TYPE_CAMPFIRE_SMOKE = 64; + public const TYPE_TALL_CAMPFIRE_SMOKE = 65; + public const TYPE_DRAGON_BREATH_FIRE = 66; + public const TYPE_DRAGON_BREATH_TRAIL = 67; /** * @return DataPacket|DataPacket[] diff --git a/src/pocketmine/metadata/BlockMetadataStore.php b/src/pocketmine/metadata/BlockMetadataStore.php index 58adf2e54a..04c69b21aa 100644 --- a/src/pocketmine/metadata/BlockMetadataStore.php +++ b/src/pocketmine/metadata/BlockMetadataStore.php @@ -42,6 +42,9 @@ class BlockMetadataStore extends MetadataStore{ return $block->x . ":" . $block->y . ":" . $block->z . ":" . $metadataKey; } + /** + * @return MetadataValue[] + */ public function getMetadata(Block $subject, string $metadataKey){ return $this->getMetadataInternal($this->disambiguate($subject, $metadataKey)); } @@ -50,10 +53,16 @@ class BlockMetadataStore extends MetadataStore{ return $this->hasMetadataInternal($this->disambiguate($subject, $metadataKey)); } + /** + * @return void + */ public function removeMetadata(Block $subject, string $metadataKey, Plugin $owningPlugin){ $this->removeMetadataInternal($this->disambiguate($subject, $metadataKey), $owningPlugin); } + /** + * @return void + */ public function setMetadata(Block $subject, string $metadataKey, MetadataValue $newMetadataValue){ $this->setMetadataInternal($this->disambiguate($subject, $metadataKey), $newMetadataValue); } diff --git a/src/pocketmine/metadata/EntityMetadataStore.php b/src/pocketmine/metadata/EntityMetadataStore.php index 681ecf7f24..e040f9f4c9 100644 --- a/src/pocketmine/metadata/EntityMetadataStore.php +++ b/src/pocketmine/metadata/EntityMetadataStore.php @@ -32,6 +32,9 @@ class EntityMetadataStore extends MetadataStore{ return $entity->getId() . ":" . $metadataKey; } + /** + * @return MetadataValue[] + */ public function getMetadata(Entity $subject, string $metadataKey){ return $this->getMetadataInternal($this->disambiguate($subject, $metadataKey)); } @@ -40,10 +43,16 @@ class EntityMetadataStore extends MetadataStore{ return $this->hasMetadataInternal($this->disambiguate($subject, $metadataKey)); } + /** + * @return void + */ public function removeMetadata(Entity $subject, string $metadataKey, Plugin $owningPlugin){ $this->removeMetadataInternal($this->disambiguate($subject, $metadataKey), $owningPlugin); } + /** + * @return void + */ public function setMetadata(Entity $subject, string $metadataKey, MetadataValue $newMetadataValue){ $this->setMetadataInternal($this->disambiguate($subject, $metadataKey), $newMetadataValue); } diff --git a/src/pocketmine/metadata/LevelMetadataStore.php b/src/pocketmine/metadata/LevelMetadataStore.php index 790c5221ca..8866bca9d0 100644 --- a/src/pocketmine/metadata/LevelMetadataStore.php +++ b/src/pocketmine/metadata/LevelMetadataStore.php @@ -33,6 +33,9 @@ class LevelMetadataStore extends MetadataStore{ return strtolower($level->getName()) . ":" . $metadataKey; } + /** + * @return MetadataValue[] + */ public function getMetadata(Level $subject, string $metadataKey){ return $this->getMetadataInternal($this->disambiguate($subject, $metadataKey)); } @@ -41,10 +44,16 @@ class LevelMetadataStore extends MetadataStore{ return $this->hasMetadataInternal($this->disambiguate($subject, $metadataKey)); } + /** + * @return void + */ public function removeMetadata(Level $subject, string $metadataKey, Plugin $owningPlugin){ $this->removeMetadataInternal($this->disambiguate($subject, $metadataKey), $owningPlugin); } + /** + * @return void + */ public function setMetadata(Level $subject, string $metadataKey, MetadataValue $newMetadataValue){ $this->setMetadataInternal($this->disambiguate($subject, $metadataKey), $newMetadataValue); } diff --git a/src/pocketmine/metadata/MetadataStore.php b/src/pocketmine/metadata/MetadataStore.php index 7d2519c8a5..47e551d8c7 100644 --- a/src/pocketmine/metadata/MetadataStore.php +++ b/src/pocketmine/metadata/MetadataStore.php @@ -35,8 +35,7 @@ abstract class MetadataStore{ /** * Adds a metadata value to an object. * - * @param string $key - * @param MetadataValue $newMetadataValue + * @return void */ protected function setMetadataInternal(string $key, MetadataValue $newMetadataValue){ $owningPlugin = $newMetadataValue->getOwningPlugin(); @@ -54,8 +53,6 @@ abstract class MetadataStore{ * Returns all metadata values attached to an object. If multiple * have attached metadata, each will value will be included. * - * @param string $key - * * @return MetadataValue[] */ protected function getMetadataInternal(string $key){ @@ -68,10 +65,6 @@ abstract class MetadataStore{ /** * Tests to see if a metadata attribute has been set on an object. - * - * @param string $key - * - * @return bool */ protected function hasMetadataInternal(string $key) : bool{ return isset($this->metadataMap[$key]); @@ -80,8 +73,7 @@ abstract class MetadataStore{ /** * Removes a metadata item owned by a plugin from a subject. * - * @param string $key - * @param Plugin $owningPlugin + * @return void */ protected function removeMetadataInternal(string $key, Plugin $owningPlugin){ if(isset($this->metadataMap[$key])){ @@ -97,7 +89,7 @@ abstract class MetadataStore{ * given plugin. Doing this will force each invalidated metadata item to * be recalculated the next time it is accessed. * - * @param Plugin $owningPlugin + * @return void */ public function invalidateAll(Plugin $owningPlugin){ /** @var \SplObjectStorage|MetadataValue[] $values */ diff --git a/src/pocketmine/metadata/MetadataValue.php b/src/pocketmine/metadata/MetadataValue.php index 6d3ab6d85c..46622002d7 100644 --- a/src/pocketmine/metadata/MetadataValue.php +++ b/src/pocketmine/metadata/MetadataValue.php @@ -50,6 +50,8 @@ abstract class MetadataValue{ /** * Invalidates this metadata item, forcing it to recompute when next * accessed. + * + * @return void */ abstract public function invalidate(); } diff --git a/src/pocketmine/metadata/Metadatable.php b/src/pocketmine/metadata/Metadatable.php index 802071b03f..297c2ee652 100644 --- a/src/pocketmine/metadata/Metadatable.php +++ b/src/pocketmine/metadata/Metadatable.php @@ -30,8 +30,7 @@ interface Metadatable{ /** * Sets a metadata value in the implementing object's metadata store. * - * @param string $metadataKey - * @param MetadataValue $newMetadataValue + * @return void */ public function setMetadata(string $metadataKey, MetadataValue $newMetadataValue); @@ -39,8 +38,6 @@ interface Metadatable{ * Returns a list of previously set metadata values from the implementing * object's metadata store. * - * @param string $metadataKey - * * @return MetadataValue[] */ public function getMetadata(string $metadataKey); @@ -48,10 +45,6 @@ interface Metadatable{ /** * Tests to see whether the implementing object contains the given * metadata value in its metadata store. - * - * @param string $metadataKey - * - * @return bool */ public function hasMetadata(string $metadataKey) : bool; @@ -59,8 +52,7 @@ interface Metadatable{ * Removes the given metadata value from the implementing object's * metadata store. * - * @param string $metadataKey - * @param Plugin $owningPlugin + * @return void */ public function removeMetadata(string $metadataKey, Plugin $owningPlugin); diff --git a/src/pocketmine/metadata/PlayerMetadataStore.php b/src/pocketmine/metadata/PlayerMetadataStore.php index 7c4fce37d9..ac0e2b3608 100644 --- a/src/pocketmine/metadata/PlayerMetadataStore.php +++ b/src/pocketmine/metadata/PlayerMetadataStore.php @@ -33,6 +33,9 @@ class PlayerMetadataStore extends MetadataStore{ return strtolower($player->getName()) . ":" . $metadataKey; } + /** + * @return MetadataValue[] + */ public function getMetadata(IPlayer $subject, string $metadataKey){ return $this->getMetadataInternal($this->disambiguate($subject, $metadataKey)); } @@ -41,10 +44,16 @@ class PlayerMetadataStore extends MetadataStore{ return $this->hasMetadataInternal($this->disambiguate($subject, $metadataKey)); } + /** + * @return void + */ public function removeMetadata(IPlayer $subject, string $metadataKey, Plugin $owningPlugin){ $this->removeMetadataInternal($this->disambiguate($subject, $metadataKey), $owningPlugin); } + /** + * @return void + */ public function setMetadata(IPlayer $subject, string $metadataKey, MetadataValue $newMetadataValue){ $this->setMetadataInternal($this->disambiguate($subject, $metadataKey), $newMetadataValue); } diff --git a/src/pocketmine/network/AdvancedSourceInterface.php b/src/pocketmine/network/AdvancedSourceInterface.php index 44bf863ed9..f3e0b899ff 100644 --- a/src/pocketmine/network/AdvancedSourceInterface.php +++ b/src/pocketmine/network/AdvancedSourceInterface.php @@ -35,29 +35,28 @@ interface AdvancedSourceInterface extends SourceInterface{ /** * Prevents packets received from the IP address getting processed for the given timeout. * - * @param string $address * @param int $timeout Seconds + * + * @return void */ public function blockAddress(string $address, int $timeout = 300); /** * Unblocks a previously-blocked address. * - * @param string $address + * @return void */ public function unblockAddress(string $address); /** - * @param Network $network + * @return void */ public function setNetwork(Network $network); /** * Sends a raw payload to the network interface, bypassing any sessions. * - * @param string $address - * @param int $port - * @param string $payload + * @return void */ public function sendRawPacket(string $address, int $port, string $payload); diff --git a/src/pocketmine/network/CompressBatchedTask.php b/src/pocketmine/network/CompressBatchedTask.php index d0f6757c27..a170a1563d 100644 --- a/src/pocketmine/network/CompressBatchedTask.php +++ b/src/pocketmine/network/CompressBatchedTask.php @@ -30,11 +30,12 @@ use pocketmine\Server; class CompressBatchedTask extends AsyncTask{ + /** @var int */ public $level = 7; + /** @var string */ public $data; /** - * @param BatchPacket $batch * @param Player[] $targets */ public function __construct(BatchPacket $batch, array $targets){ @@ -46,7 +47,6 @@ class CompressBatchedTask extends AsyncTask{ public function onRun(){ $batch = new BatchPacket(); $batch->payload = $this->data; - $this->data = null; $batch->setCompressionLevel($this->level); $batch->encode(); diff --git a/src/pocketmine/network/Network.php b/src/pocketmine/network/Network.php index c3633215fd..0a8b27c99f 100644 --- a/src/pocketmine/network/Network.php +++ b/src/pocketmine/network/Network.php @@ -34,6 +34,7 @@ use function spl_object_hash; class Network{ + /** @var int */ public static $BATCH_THRESHOLD = 512; /** @var Server */ @@ -45,7 +46,9 @@ class Network{ /** @var AdvancedSourceInterface[] */ private $advancedInterfaces = []; + /** @var float */ private $upload = 0; + /** @var float */ private $download = 0; /** @var string */ @@ -58,19 +61,34 @@ class Network{ } + /** + * @param float $upload + * @param float $download + * + * @return void + */ public function addStatistics($upload, $download){ $this->upload += $upload; $this->download += $download; } + /** + * @return float + */ public function getUpload(){ return $this->upload; } + /** + * @return float + */ public function getDownload(){ return $this->download; } + /** + * @return void + */ public function resetStatistics(){ $this->upload = 0; $this->download = 0; @@ -83,6 +101,9 @@ class Network{ return $this->interfaces; } + /** + * @return void + */ public function processInterfaces(){ foreach($this->interfaces as $interface){ $interface->process(); @@ -91,14 +112,13 @@ class Network{ /** * @deprecated - * @param SourceInterface $interface */ public function processInterface(SourceInterface $interface) : void{ $interface->process(); } /** - * @param SourceInterface $interface + * @return void */ public function registerInterface(SourceInterface $interface){ $ev = new NetworkInterfaceRegisterEvent($interface); @@ -115,7 +135,7 @@ class Network{ } /** - * @param SourceInterface $interface + * @return void */ public function unregisterInterface(SourceInterface $interface){ (new NetworkInterfaceUnregisterEvent($interface))->call(); @@ -125,7 +145,7 @@ class Network{ /** * Sets the server name shown on each interface Query * - * @param string $name + * @return void */ public function setName(string $name){ $this->name = $name; @@ -134,30 +154,25 @@ class Network{ } } - /** - * @return string - */ public function getName() : string{ return $this->name; } + /** + * @return void + */ public function updateName(){ foreach($this->interfaces as $interface){ $interface->setName($this->name); } } - /** - * @return Server - */ public function getServer() : Server{ return $this->server; } /** - * @param string $address - * @param int $port - * @param string $payload + * @return void */ public function sendPacket(string $address, int $port, string $payload){ foreach($this->advancedInterfaces as $interface){ @@ -168,8 +183,7 @@ class Network{ /** * Blocks an IP address from the main interface. Setting timeout to -1 will block it forever * - * @param string $address - * @param int $timeout + * @return void */ public function blockAddress(string $address, int $timeout = 300){ foreach($this->advancedInterfaces as $interface){ @@ -177,6 +191,9 @@ class Network{ } } + /** + * @return void + */ public function unblockAddress(string $address){ foreach($this->advancedInterfaces as $interface){ $interface->unblockAddress($address); diff --git a/src/pocketmine/network/SourceInterface.php b/src/pocketmine/network/SourceInterface.php index 75e14c98b3..168f68b221 100644 --- a/src/pocketmine/network/SourceInterface.php +++ b/src/pocketmine/network/SourceInterface.php @@ -36,17 +36,14 @@ interface SourceInterface{ /** * Performs actions needed to start the interface after it is registered. + * + * @return void */ public function start(); /** * Sends a DataPacket to the interface, returns an unique identifier for the packet if $needACK is true * - * @param Player $player - * @param DataPacket $packet - * @param bool $needACK - * @param bool $immediate - * * @return int|null */ public function putPacket(Player $player, DataPacket $packet, bool $needACK = false, bool $immediate = true); @@ -54,13 +51,12 @@ interface SourceInterface{ /** * Terminates the connection * - * @param Player $player - * @param string $reason + * @return void */ public function close(Player $player, string $reason = "unknown reason"); /** - * @param string $name + * @return void */ public function setName(string $name); @@ -71,12 +67,16 @@ interface SourceInterface{ /** * Gracefully shuts down the network interface. + * + * @return void */ public function shutdown(); /** * @deprecated * Shuts down the network interface in an emergency situation, such as due to a crash. + * + * @return void */ public function emergencyShutdown(); diff --git a/src/pocketmine/network/mcpe/NetworkBinaryStream.php b/src/pocketmine/network/mcpe/NetworkBinaryStream.php index b8cd85838a..0e8831e6b3 100644 --- a/src/pocketmine/network/mcpe/NetworkBinaryStream.php +++ b/src/pocketmine/network/mcpe/NetworkBinaryStream.php @@ -103,6 +103,9 @@ class NetworkBinaryStream extends BinaryStream{ return new SkinData($skinId, $skinResourcePatch, $skinData, $animations, $capeData, $geometryData, $animationData, $premium, $persona, $capeOnClassic, $capeId); } + /** + * @return void + */ public function putSkin(SkinData $skin){ $this->putString($skin->getSkinId()); $this->putString($skin->getResourcePatch()); @@ -198,7 +201,6 @@ class NetworkBinaryStream extends BinaryStream{ return ItemFactory::get($id, $data, $cnt, $nbt); } - public function putSlot(Item $item) : void{ if($item->getId() === 0){ $this->putVarInt(0); @@ -271,7 +273,8 @@ class NetworkBinaryStream extends BinaryStream{ * * @param bool $types Whether to include metadata types along with values in the returned array * - * @return array + * @return mixed[]|mixed[][] + * @phpstan-return array|array */ public function getEntityMetadata(bool $types = true) : array{ $count = $this->getUnsignedVarInt(); @@ -325,7 +328,8 @@ class NetworkBinaryStream extends BinaryStream{ /** * Writes entity metadata to the packet buffer. * - * @param array $metadata + * @param mixed[][] $metadata + * @phpstan-param array $metadata */ public function putEntityMetadata(array $metadata) : void{ $this->putUnsignedVarInt(count($metadata)); @@ -422,7 +426,6 @@ class NetworkBinaryStream extends BinaryStream{ /** * Reads and returns an EntityUniqueID - * @return int */ public function getEntityUniqueId() : int{ return $this->getVarLong(); @@ -430,8 +433,6 @@ class NetworkBinaryStream extends BinaryStream{ /** * Writes an EntityUniqueID - * - * @param int $eid */ public function putEntityUniqueId(int $eid) : void{ $this->putVarLong($eid); @@ -439,7 +440,6 @@ class NetworkBinaryStream extends BinaryStream{ /** * Reads and returns an EntityRuntimeID - * @return int */ public function getEntityRuntimeId() : int{ return $this->getUnsignedVarLong(); @@ -447,8 +447,6 @@ class NetworkBinaryStream extends BinaryStream{ /** * Writes an EntityRuntimeID - * - * @param int $eid */ public function putEntityRuntimeId(int $eid) : void{ $this->putUnsignedVarLong($eid); @@ -457,9 +455,9 @@ class NetworkBinaryStream extends BinaryStream{ /** * Reads an block position with unsigned Y coordinate. * - * @param int &$x - * @param int &$y - * @param int &$z + * @param int $x reference parameter + * @param int $y reference parameter + * @param int $z reference parameter */ public function getBlockPosition(&$x, &$y, &$z) : void{ $x = $this->getVarInt(); @@ -469,10 +467,6 @@ class NetworkBinaryStream extends BinaryStream{ /** * Writes a block position with unsigned Y coordinate. - * - * @param int $x - * @param int $y - * @param int $z */ public function putBlockPosition(int $x, int $y, int $z) : void{ $this->putVarInt($x); @@ -483,9 +477,9 @@ class NetworkBinaryStream extends BinaryStream{ /** * Reads a block position with a signed Y coordinate. * - * @param int &$x - * @param int &$y - * @param int &$z + * @param int $x reference parameter + * @param int $y reference parameter + * @param int $z reference parameter */ public function getSignedBlockPosition(&$x, &$y, &$z) : void{ $x = $this->getVarInt(); @@ -495,10 +489,6 @@ class NetworkBinaryStream extends BinaryStream{ /** * Writes a block position with a signed Y coordinate. - * - * @param int $x - * @param int $y - * @param int $z */ public function putSignedBlockPosition(int $x, int $y, int $z) : void{ $this->putVarInt($x); @@ -508,8 +498,6 @@ class NetworkBinaryStream extends BinaryStream{ /** * Reads a floating-point Vector3 object with coordinates rounded to 4 decimal places. - * - * @return Vector3 */ public function getVector3() : Vector3{ return new Vector3( @@ -526,11 +514,9 @@ class NetworkBinaryStream extends BinaryStream{ * For all other purposes, use the non-nullable version. * * @see NetworkBinaryStream::putVector3() - * - * @param Vector3|null $vector */ public function putVector3Nullable(?Vector3 $vector) : void{ - if($vector){ + if($vector !== null){ $this->putVector3($vector); }else{ $this->putLFloat(0.0); @@ -541,8 +527,6 @@ class NetworkBinaryStream extends BinaryStream{ /** * Writes a floating-point Vector3 object - * - * @param Vector3 $vector */ public function putVector3(Vector3 $vector) : void{ $this->putLFloat($vector->x); @@ -551,7 +535,7 @@ class NetworkBinaryStream extends BinaryStream{ } public function getByteRotation() : float{ - return (float) ($this->getByte() * (360 / 256)); + return ($this->getByte() * (360 / 256)); } public function putByteRotation(float $rotation) : void{ @@ -562,7 +546,8 @@ class NetworkBinaryStream extends BinaryStream{ * Reads gamerules * TODO: implement this properly * - * @return array, members are in the structure [name => [type, value]] + * @return mixed[][], members are in the structure [name => [type, value]] + * @phpstan-return array */ public function getGameRules() : array{ $count = $this->getUnsignedVarInt(); @@ -593,7 +578,8 @@ class NetworkBinaryStream extends BinaryStream{ * Writes a gamerule array, members should be in the structure [name => [type, value]] * TODO: implement this properly * - * @param array $rules + * @param mixed[][] $rules + * @phpstan-param array $rules */ public function putGameRules(array $rules) : void{ $this->putUnsignedVarInt(count($rules)); @@ -614,9 +600,6 @@ class NetworkBinaryStream extends BinaryStream{ } } - /** - * @return EntityLink - */ protected function getEntityLink() : EntityLink{ $link = new EntityLink(); @@ -628,9 +611,6 @@ class NetworkBinaryStream extends BinaryStream{ return $link; } - /** - * @param EntityLink $link - */ protected function putEntityLink(EntityLink $link) : void{ $this->putEntityUniqueId($link->fromEntityUniqueId); $this->putEntityUniqueId($link->toEntityUniqueId); diff --git a/src/pocketmine/network/mcpe/NetworkSession.php b/src/pocketmine/network/mcpe/NetworkSession.php index 19a5a14baf..cb647212ba 100644 --- a/src/pocketmine/network/mcpe/NetworkSession.php +++ b/src/pocketmine/network/mcpe/NetworkSession.php @@ -169,6 +169,9 @@ use pocketmine\network\mcpe\protocol\VideoStreamConnectPacket; abstract class NetworkSession{ + /** + * @return void + */ abstract public function handleDataPacket(DataPacket $packet); public function handleLogin(LoginPacket $packet) : bool{ diff --git a/src/pocketmine/network/mcpe/PlayerNetworkSessionAdapter.php b/src/pocketmine/network/mcpe/PlayerNetworkSessionAdapter.php index 6b8297e75e..59203e2f8d 100644 --- a/src/pocketmine/network/mcpe/PlayerNetworkSessionAdapter.php +++ b/src/pocketmine/network/mcpe/PlayerNetworkSessionAdapter.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\network\mcpe; - use pocketmine\event\server\DataPacketReceiveEvent; use pocketmine\network\mcpe\protocol\ActorEventPacket; use pocketmine\network\mcpe\protocol\ActorFallPacket; @@ -268,9 +267,6 @@ class PlayerNetworkSessionAdapter extends NetworkSession{ /** * Hack to work around a stupid bug in Minecraft W10 which causes empty strings to be sent unquoted in form responses. * - * @param string $json - * @param bool $assoc - * * @return mixed */ private static function stupid_json_decode(string $json, bool $assoc = false){ @@ -278,9 +274,9 @@ class PlayerNetworkSessionAdapter extends NetworkSession{ $raw = $matches[1]; $lastComma = -1; $newParts = []; - $quoteType = null; + $inQuotes = false; for($i = 0, $len = strlen($raw); $i <= $len; ++$i){ - if($i === $len or ($raw[$i] === "," and $quoteType === null)){ + if($i === $len or ($raw[$i] === "," and !$inQuotes)){ $part = substr($raw, $lastComma + 1, $i - ($lastComma + 1)); if(trim($part) === ""){ //regular parts will have quotes or something else that makes them non-empty $part = '""'; @@ -288,12 +284,13 @@ class PlayerNetworkSessionAdapter extends NetworkSession{ $newParts[] = $part; $lastComma = $i; }elseif($raw[$i] === '"'){ - if($quoteType === null){ - $quoteType = $raw[$i]; - }elseif($raw[$i] === $quoteType){ - for($backslashes = 0; $backslashes < $i && $raw[$i - $backslashes - 1] === "\\"; ++$backslashes){} + if(!$inQuotes){ + $inQuotes = true; + }else{ + $backslashes = 0; + for(; $backslashes < $i && $raw[$i - $backslashes - 1] === "\\"; ++$backslashes){} if(($backslashes % 2) === 0){ //unescaped quote - $quoteType = null; + $inQuotes = false; } } } diff --git a/src/pocketmine/network/mcpe/RakLibInterface.php b/src/pocketmine/network/mcpe/RakLibInterface.php index 1877b0a131..c9d28370cd 100644 --- a/src/pocketmine/network/mcpe/RakLibInterface.php +++ b/src/pocketmine/network/mcpe/RakLibInterface.php @@ -217,8 +217,13 @@ class RakLibInterface implements ServerInstance, AdvancedSourceInterface{ ); } + /** + * @param bool $name + * + * @return void + */ public function setPortCheck($name){ - $this->interface->sendOption("portChecking", (bool) $name); + $this->interface->sendOption("portChecking", $name); } public function handleOption(string $option, string $value) : void{ diff --git a/src/pocketmine/network/mcpe/VerifyLoginTask.php b/src/pocketmine/network/mcpe/VerifyLoginTask.php index 620cdae087..db3d86d28f 100644 --- a/src/pocketmine/network/mcpe/VerifyLoginTask.php +++ b/src/pocketmine/network/mcpe/VerifyLoginTask.php @@ -65,7 +65,6 @@ class VerifyLoginTask extends AsyncTask{ */ private $authenticated = false; - public function __construct(Player $player, LoginPacket $packet){ $this->storeLocal($player); $this->packet = $packet; @@ -92,10 +91,6 @@ class VerifyLoginTask extends AsyncTask{ } /** - * @param string $jwt - * @param null|string $currentPublicKey - * @param bool $first - * * @throws VerifyLoginException if errors are encountered */ private function validateToken(string $jwt, ?string &$currentPublicKey, bool $first = false) : void{ diff --git a/src/pocketmine/network/mcpe/protocol/ActorEventPacket.php b/src/pocketmine/network/mcpe/protocol/ActorEventPacket.php index 531309efab..3d4caa299f 100644 --- a/src/pocketmine/network/mcpe/protocol/ActorEventPacket.php +++ b/src/pocketmine/network/mcpe/protocol/ActorEventPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class ActorEventPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/ActorFallPacket.php b/src/pocketmine/network/mcpe/protocol/ActorFallPacket.php index 76f8dca7a2..645bc14cf3 100644 --- a/src/pocketmine/network/mcpe/protocol/ActorFallPacket.php +++ b/src/pocketmine/network/mcpe/protocol/ActorFallPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class ActorFallPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/AddActorPacket.php b/src/pocketmine/network/mcpe/protocol/AddActorPacket.php index 50aade6fae..e3122dc059 100644 --- a/src/pocketmine/network/mcpe/protocol/AddActorPacket.php +++ b/src/pocketmine/network/mcpe/protocol/AddActorPacket.php @@ -163,7 +163,10 @@ class AddActorPacket extends DataPacket{ /** @var Attribute[] */ public $attributes = []; - /** @var array */ + /** + * @var mixed[][] + * @phpstan-var array + */ public $metadata = []; /** @var EntityLink[] */ public $links = []; diff --git a/src/pocketmine/network/mcpe/protocol/AddEntityPacket.php b/src/pocketmine/network/mcpe/protocol/AddEntityPacket.php index ba428cbcb6..726a3c7d57 100644 --- a/src/pocketmine/network/mcpe/protocol/AddEntityPacket.php +++ b/src/pocketmine/network/mcpe/protocol/AddEntityPacket.php @@ -39,9 +39,6 @@ class AddEntityPacket extends DataPacket/* implements ClientboundPacket*/{ return $result; } - /** - * @return int - */ public function getUvarint1() : int{ return $this->uvarint1; } diff --git a/src/pocketmine/network/mcpe/protocol/AddItemActorPacket.php b/src/pocketmine/network/mcpe/protocol/AddItemActorPacket.php index 13492dae4b..9e7bb0d160 100644 --- a/src/pocketmine/network/mcpe/protocol/AddItemActorPacket.php +++ b/src/pocketmine/network/mcpe/protocol/AddItemActorPacket.php @@ -42,7 +42,10 @@ class AddItemActorPacket extends DataPacket{ public $position; /** @var Vector3|null */ public $motion; - /** @var array */ + /** + * @var mixed[][] + * @phpstan-var array + */ public $metadata = []; /** @var bool */ public $isFromFishing = false; diff --git a/src/pocketmine/network/mcpe/protocol/AddPaintingPacket.php b/src/pocketmine/network/mcpe/protocol/AddPaintingPacket.php index 4b6491adf8..a5f20b94c2 100644 --- a/src/pocketmine/network/mcpe/protocol/AddPaintingPacket.php +++ b/src/pocketmine/network/mcpe/protocol/AddPaintingPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\math\Vector3; use pocketmine\network\mcpe\NetworkSession; diff --git a/src/pocketmine/network/mcpe/protocol/AddPlayerPacket.php b/src/pocketmine/network/mcpe/protocol/AddPlayerPacket.php index 28c61b970b..fa4fbf64fa 100644 --- a/src/pocketmine/network/mcpe/protocol/AddPlayerPacket.php +++ b/src/pocketmine/network/mcpe/protocol/AddPlayerPacket.php @@ -57,16 +57,25 @@ class AddPlayerPacket extends DataPacket{ public $headYaw = null; //TODO /** @var Item */ public $item; - /** @var array */ + /** + * @var mixed[][] + * @phpstan-var array + */ public $metadata = []; //TODO: adventure settings stuff + /** @var int */ public $uvarint1 = 0; + /** @var int */ public $uvarint2 = 0; + /** @var int */ public $uvarint3 = 0; + /** @var int */ public $uvarint4 = 0; + /** @var int */ public $uvarint5 = 0; + /** @var int */ public $long1 = 0; /** @var EntityLink[] */ diff --git a/src/pocketmine/network/mcpe/protocol/AdventureSettingsPacket.php b/src/pocketmine/network/mcpe/protocol/AdventureSettingsPacket.php index 8196f6d3aa..b6c72b01e3 100644 --- a/src/pocketmine/network/mcpe/protocol/AdventureSettingsPacket.php +++ b/src/pocketmine/network/mcpe/protocol/AdventureSettingsPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; use pocketmine\network\mcpe\protocol\types\PlayerPermissions; @@ -95,15 +94,18 @@ class AdventureSettingsPacket extends DataPacket{ } public function getFlag(int $flag) : bool{ - if($flag & self::BITFLAG_SECOND_SET){ + if(($flag & self::BITFLAG_SECOND_SET) !== 0){ return ($this->flags2 & $flag) !== 0; } return ($this->flags & $flag) !== 0; } + /** + * @return void + */ public function setFlag(int $flag, bool $value){ - if($flag & self::BITFLAG_SECOND_SET){ + if(($flag & self::BITFLAG_SECOND_SET) !== 0){ $flagSet =& $this->flags2; }else{ $flagSet =& $this->flags; diff --git a/src/pocketmine/network/mcpe/protocol/AnimatePacket.php b/src/pocketmine/network/mcpe/protocol/AnimatePacket.php index 9613f9cf55..75f67a4714 100644 --- a/src/pocketmine/network/mcpe/protocol/AnimatePacket.php +++ b/src/pocketmine/network/mcpe/protocol/AnimatePacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class AnimatePacket extends DataPacket{ @@ -48,7 +47,7 @@ class AnimatePacket extends DataPacket{ protected function decodePayload(){ $this->action = $this->getVarInt(); $this->entityRuntimeId = $this->getEntityRuntimeId(); - if($this->action & 0x80){ + if(($this->action & 0x80) !== 0){ $this->float = $this->getLFloat(); } } @@ -56,7 +55,7 @@ class AnimatePacket extends DataPacket{ protected function encodePayload(){ $this->putVarInt($this->action); $this->putEntityRuntimeId($this->entityRuntimeId); - if($this->action & 0x80){ + if(($this->action & 0x80) !== 0){ $this->putLFloat($this->float); } } diff --git a/src/pocketmine/network/mcpe/protocol/AvailableCommandsPacket.php b/src/pocketmine/network/mcpe/protocol/AvailableCommandsPacket.php index 67c2e691a0..eac4833d0a 100644 --- a/src/pocketmine/network/mcpe/protocol/AvailableCommandsPacket.php +++ b/src/pocketmine/network/mcpe/protocol/AvailableCommandsPacket.php @@ -38,7 +38,6 @@ use function dechex; class AvailableCommandsPacket extends DataPacket{ public const NETWORK_ID = ProtocolInfo::AVAILABLE_COMMANDS_PACKET; - /** * This flag is set on all types EXCEPT the POSTFIX type. Not completely sure what this is for, but it is required * for the argtype to work correctly. VALID seems as good a name as any. @@ -149,7 +148,6 @@ class AvailableCommandsPacket extends DataPacket{ /** * @param string[] $enumValueList * - * @return CommandEnum * @throws \UnexpectedValueException * @throws BinaryDataException */ @@ -184,7 +182,6 @@ class AvailableCommandsPacket extends DataPacket{ } /** - * @param CommandEnum $enum * @param int[] $enumValueMap string enum name -> int index */ protected function putEnum(CommandEnum $enum, array $enumValueMap) : void{ @@ -211,9 +208,6 @@ class AvailableCommandsPacket extends DataPacket{ } /** - * @param int $valueCount - * - * @return int * @throws BinaryDataException */ protected function getEnumValueIndex(int $valueCount) : int{ @@ -239,8 +233,6 @@ class AvailableCommandsPacket extends DataPacket{ /** * @param CommandEnum[] $enums * @param string[] $enumValues - * - * @return CommandEnumConstraint */ protected function getEnumConstraint(array $enums, array $enumValues) : CommandEnumConstraint{ //wtf, what was wrong with an offset inside the enum? :( @@ -267,7 +259,6 @@ class AvailableCommandsPacket extends DataPacket{ } /** - * @param CommandEnumConstraint $constraint * @param int[] $enumIndexes string enum name -> int index * @param int[] $enumValueIndexes string value -> int index */ @@ -284,7 +275,6 @@ class AvailableCommandsPacket extends DataPacket{ * @param CommandEnum[] $enums * @param string[] $postfixes * - * @return CommandData * @throws \UnexpectedValueException * @throws BinaryDataException */ @@ -305,13 +295,13 @@ class AvailableCommandsPacket extends DataPacket{ $parameter->isOptional = $this->getBool(); $parameter->flags = $this->getByte(); - if($parameter->paramType & self::ARG_FLAG_ENUM){ + if(($parameter->paramType & self::ARG_FLAG_ENUM) !== 0){ $index = ($parameter->paramType & 0xffff); $parameter->enum = $enums[$index] ?? null; if($parameter->enum === null){ throw new \UnexpectedValueException("deserializing $retval->commandName parameter $parameter->paramName: expected enum at $index, but got none"); } - }elseif($parameter->paramType & self::ARG_FLAG_POSTFIX){ + }elseif(($parameter->paramType & self::ARG_FLAG_POSTFIX) !== 0){ $index = ($parameter->paramType & 0xffff); $parameter->postfix = $postfixes[$index] ?? null; if($parameter->postfix === null){ @@ -329,7 +319,6 @@ class AvailableCommandsPacket extends DataPacket{ } /** - * @param CommandData $data * @param int[] $enumIndexes string enum name -> int index * @param int[] $postfixIndexes */ @@ -371,9 +360,13 @@ class AvailableCommandsPacket extends DataPacket{ } } + /** + * @param string[] $postfixes + * @phpstan-param array $postfixes + */ private function argTypeToString(int $argtype, array $postfixes) : string{ - if($argtype & self::ARG_FLAG_VALID){ - if($argtype & self::ARG_FLAG_ENUM){ + if(($argtype & self::ARG_FLAG_VALID) !== 0){ + if(($argtype & self::ARG_FLAG_ENUM) !== 0){ return "stringenum (" . ($argtype & 0xffff) . ")"; } @@ -399,7 +392,7 @@ class AvailableCommandsPacket extends DataPacket{ case self::ARG_TYPE_COMMAND: return "command"; } - }elseif($argtype & self::ARG_FLAG_POSTFIX){ + }elseif(($argtype & self::ARG_FLAG_POSTFIX) !== 0){ $postfix = $postfixes[$argtype & 0xffff]; return "int (postfix $postfix)"; @@ -420,7 +413,7 @@ class AvailableCommandsPacket extends DataPacket{ /** @var CommandEnum[] $enums */ $enums = []; - $addEnumFn = static function(CommandEnum $enum) use (&$enums, &$enumIndexes, &$enumValueIndexes){ + $addEnumFn = static function(CommandEnum $enum) use (&$enums, &$enumIndexes, &$enumValueIndexes) : void{ if(!isset($enumIndexes[$enum->enumName])){ $enums[$enumIndexes[$enum->enumName] = count($enumIndexes)] = $enum; } diff --git a/src/pocketmine/network/mcpe/protocol/BatchPacket.php b/src/pocketmine/network/mcpe/protocol/BatchPacket.php index b49ebb8efa..7124f7515f 100644 --- a/src/pocketmine/network/mcpe/protocol/BatchPacket.php +++ b/src/pocketmine/network/mcpe/protocol/BatchPacket.php @@ -76,7 +76,7 @@ class BatchPacket extends DataPacket{ } /** - * @param DataPacket $packet + * @return void */ public function addPacket(DataPacket $packet){ if(!$packet->canBeBatched()){ @@ -91,6 +91,7 @@ class BatchPacket extends DataPacket{ /** * @return \Generator + * @phpstan-return \Generator */ public function getPackets(){ $stream = new NetworkBinaryStream($this->payload); @@ -107,6 +108,9 @@ class BatchPacket extends DataPacket{ return $this->compressionLevel; } + /** + * @return void + */ public function setCompressionLevel(int $level){ $this->compressionLevel = $level; } diff --git a/src/pocketmine/network/mcpe/protocol/BlockActorDataPacket.php b/src/pocketmine/network/mcpe/protocol/BlockActorDataPacket.php index 01bb20f1e1..f842873e91 100644 --- a/src/pocketmine/network/mcpe/protocol/BlockActorDataPacket.php +++ b/src/pocketmine/network/mcpe/protocol/BlockActorDataPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class BlockActorDataPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/BlockEventPacket.php b/src/pocketmine/network/mcpe/protocol/BlockEventPacket.php index 12e7fc0c74..b9dffe108e 100644 --- a/src/pocketmine/network/mcpe/protocol/BlockEventPacket.php +++ b/src/pocketmine/network/mcpe/protocol/BlockEventPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class BlockEventPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/BlockPickRequestPacket.php b/src/pocketmine/network/mcpe/protocol/BlockPickRequestPacket.php index 8e36475658..683104fef6 100644 --- a/src/pocketmine/network/mcpe/protocol/BlockPickRequestPacket.php +++ b/src/pocketmine/network/mcpe/protocol/BlockPickRequestPacket.php @@ -21,12 +21,10 @@ declare(strict_types=1); - namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class BlockPickRequestPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/BossEventPacket.php b/src/pocketmine/network/mcpe/protocol/BossEventPacket.php index f23c7020b6..0369e1f7ef 100644 --- a/src/pocketmine/network/mcpe/protocol/BossEventPacket.php +++ b/src/pocketmine/network/mcpe/protocol/BossEventPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class BossEventPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/ChangeDimensionPacket.php b/src/pocketmine/network/mcpe/protocol/ChangeDimensionPacket.php index 485748f6d5..9af2db5fb1 100644 --- a/src/pocketmine/network/mcpe/protocol/ChangeDimensionPacket.php +++ b/src/pocketmine/network/mcpe/protocol/ChangeDimensionPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\math\Vector3; use pocketmine\network\mcpe\NetworkSession; diff --git a/src/pocketmine/network/mcpe/protocol/ChunkRadiusUpdatedPacket.php b/src/pocketmine/network/mcpe/protocol/ChunkRadiusUpdatedPacket.php index 684de5f33e..42643d9e36 100644 --- a/src/pocketmine/network/mcpe/protocol/ChunkRadiusUpdatedPacket.php +++ b/src/pocketmine/network/mcpe/protocol/ChunkRadiusUpdatedPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class ChunkRadiusUpdatedPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/ClientCacheBlobStatusPacket.php b/src/pocketmine/network/mcpe/protocol/ClientCacheBlobStatusPacket.php index 81ca481633..7957c94a1d 100644 --- a/src/pocketmine/network/mcpe/protocol/ClientCacheBlobStatusPacket.php +++ b/src/pocketmine/network/mcpe/protocol/ClientCacheBlobStatusPacket.php @@ -39,13 +39,11 @@ class ClientCacheBlobStatusPacket extends DataPacket/* implements ServerboundPac /** * @param int[] $hitHashes * @param int[] $missHashes - * - * @return self */ public static function create(array $hitHashes, array $missHashes) : self{ //type checks - (static function(int ...$hashes){})(...$hitHashes); - (static function(int ...$hashes){})(...$missHashes); + (static function(int ...$hashes) : void{})(...$hitHashes); + (static function(int ...$hashes) : void{})(...$missHashes); $result = new self; $result->hitHashes = $hitHashes; diff --git a/src/pocketmine/network/mcpe/protocol/ClientCacheMissResponsePacket.php b/src/pocketmine/network/mcpe/protocol/ClientCacheMissResponsePacket.php index 1118181d17..28e823cbcd 100644 --- a/src/pocketmine/network/mcpe/protocol/ClientCacheMissResponsePacket.php +++ b/src/pocketmine/network/mcpe/protocol/ClientCacheMissResponsePacket.php @@ -37,12 +37,10 @@ class ClientCacheMissResponsePacket extends DataPacket/* implements ClientboundP /** * @param ChunkCacheBlob[] $blobs - * - * @return self */ public static function create(array $blobs) : self{ //type check - (static function(ChunkCacheBlob ...$blobs){})(...$blobs); + (static function(ChunkCacheBlob ...$blobs) : void{})(...$blobs); $result = new self; $result->blobs = $blobs; diff --git a/src/pocketmine/network/mcpe/protocol/ClientCacheStatusPacket.php b/src/pocketmine/network/mcpe/protocol/ClientCacheStatusPacket.php index a7eb0f8243..3a4faf0530 100644 --- a/src/pocketmine/network/mcpe/protocol/ClientCacheStatusPacket.php +++ b/src/pocketmine/network/mcpe/protocol/ClientCacheStatusPacket.php @@ -39,9 +39,6 @@ class ClientCacheStatusPacket extends DataPacket/* implements ServerboundPacket* return $result; } - /** - * @return bool - */ public function isEnabled() : bool{ return $this->enabled; } diff --git a/src/pocketmine/network/mcpe/protocol/ClientToServerHandshakePacket.php b/src/pocketmine/network/mcpe/protocol/ClientToServerHandshakePacket.php index a4a564109a..9a13a7d8e8 100644 --- a/src/pocketmine/network/mcpe/protocol/ClientToServerHandshakePacket.php +++ b/src/pocketmine/network/mcpe/protocol/ClientToServerHandshakePacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class ClientToServerHandshakePacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/ClientboundMapItemDataPacket.php b/src/pocketmine/network/mcpe/protocol/ClientboundMapItemDataPacket.php index da5acbc83a..b0559be583 100644 --- a/src/pocketmine/network/mcpe/protocol/ClientboundMapItemDataPacket.php +++ b/src/pocketmine/network/mcpe/protocol/ClientboundMapItemDataPacket.php @@ -21,17 +21,15 @@ declare(strict_types=1); - namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; use pocketmine\network\mcpe\protocol\types\DimensionIds; +use pocketmine\network\mcpe\protocol\types\MapDecoration; use pocketmine\network\mcpe\protocol\types\MapTrackedObject; use pocketmine\utils\Color; -use function assert; use function count; class ClientboundMapItemDataPacket extends DataPacket{ @@ -56,7 +54,7 @@ class ClientboundMapItemDataPacket extends DataPacket{ /** @var MapTrackedObject[] */ public $trackedEntities = []; - /** @var array */ + /** @var MapDecoration[] */ public $decorations = []; /** @var int */ @@ -102,13 +100,13 @@ class ClientboundMapItemDataPacket extends DataPacket{ } for($i = 0, $count = $this->getUnsignedVarInt(); $i < $count; ++$i){ - $this->decorations[$i]["img"] = $this->getByte(); - $this->decorations[$i]["rot"] = $this->getByte(); - $this->decorations[$i]["xOffset"] = $this->getByte(); - $this->decorations[$i]["yOffset"] = $this->getByte(); - $this->decorations[$i]["label"] = $this->getString(); - - $this->decorations[$i]["color"] = Color::fromABGR($this->getUnsignedVarInt()); + $icon = $this->getByte(); + $rotation = $this->getByte(); + $xOffset = $this->getByte(); + $yOffset = $this->getByte(); + $label = $this->getString(); + $color = Color::fromABGR($this->getUnsignedVarInt()); + $this->decorations[] = new MapDecoration($icon, $rotation, $xOffset, $yOffset, $label, $color); } } @@ -175,14 +173,12 @@ class ClientboundMapItemDataPacket extends DataPacket{ $this->putUnsignedVarInt($decorationCount); foreach($this->decorations as $decoration){ - $this->putByte($decoration["img"]); - $this->putByte($decoration["rot"]); - $this->putByte($decoration["xOffset"]); - $this->putByte($decoration["yOffset"]); - $this->putString($decoration["label"]); - - assert($decoration["color"] instanceof Color); - $this->putUnsignedVarInt($decoration["color"]->toABGR()); + $this->putByte($decoration->getIcon()); + $this->putByte($decoration->getRotation()); + $this->putByte($decoration->getXOffset()); + $this->putByte($decoration->getYOffset()); + $this->putString($decoration->getLabel()); + $this->putUnsignedVarInt($decoration->getColor()->toABGR()); } } diff --git a/src/pocketmine/network/mcpe/protocol/CommandBlockUpdatePacket.php b/src/pocketmine/network/mcpe/protocol/CommandBlockUpdatePacket.php index e88f80c9a9..01f6bae8ab 100644 --- a/src/pocketmine/network/mcpe/protocol/CommandBlockUpdatePacket.php +++ b/src/pocketmine/network/mcpe/protocol/CommandBlockUpdatePacket.php @@ -21,12 +21,10 @@ declare(strict_types=1); - namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class CommandBlockUpdatePacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/CommandOutputPacket.php b/src/pocketmine/network/mcpe/protocol/CommandOutputPacket.php index e7c3ff655a..b6bc2856e0 100644 --- a/src/pocketmine/network/mcpe/protocol/CommandOutputPacket.php +++ b/src/pocketmine/network/mcpe/protocol/CommandOutputPacket.php @@ -86,6 +86,9 @@ class CommandOutputPacket extends DataPacket{ } } + /** + * @return void + */ protected function putCommandMessage(CommandOutputMessage $message){ $this->putBool($message->isInternal); $this->putString($message->messageId); diff --git a/src/pocketmine/network/mcpe/protocol/CompletedUsingItemPacket.php b/src/pocketmine/network/mcpe/protocol/CompletedUsingItemPacket.php index 27e6688e22..1f044f7219 100644 --- a/src/pocketmine/network/mcpe/protocol/CompletedUsingItemPacket.php +++ b/src/pocketmine/network/mcpe/protocol/CompletedUsingItemPacket.php @@ -23,6 +23,8 @@ declare(strict_types=1); namespace pocketmine\network\mcpe\protocol; +#include + use pocketmine\network\mcpe\NetworkSession; class CompletedUsingItemPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/ContainerClosePacket.php b/src/pocketmine/network/mcpe/protocol/ContainerClosePacket.php index 105de06ea2..2c35cf413e 100644 --- a/src/pocketmine/network/mcpe/protocol/ContainerClosePacket.php +++ b/src/pocketmine/network/mcpe/protocol/ContainerClosePacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class ContainerClosePacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/ContainerOpenPacket.php b/src/pocketmine/network/mcpe/protocol/ContainerOpenPacket.php index 9b1b07c41e..be86a18189 100644 --- a/src/pocketmine/network/mcpe/protocol/ContainerOpenPacket.php +++ b/src/pocketmine/network/mcpe/protocol/ContainerOpenPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class ContainerOpenPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/ContainerSetDataPacket.php b/src/pocketmine/network/mcpe/protocol/ContainerSetDataPacket.php index fc5958fb1a..71c324b235 100644 --- a/src/pocketmine/network/mcpe/protocol/ContainerSetDataPacket.php +++ b/src/pocketmine/network/mcpe/protocol/ContainerSetDataPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class ContainerSetDataPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/CraftingDataPacket.php b/src/pocketmine/network/mcpe/protocol/CraftingDataPacket.php index a05d2bc27c..2b3e1d98ef 100644 --- a/src/pocketmine/network/mcpe/protocol/CraftingDataPacket.php +++ b/src/pocketmine/network/mcpe/protocol/CraftingDataPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\inventory\FurnaceRecipe; use pocketmine\inventory\ShapedRecipe; use pocketmine\inventory\ShapelessRecipe; @@ -62,6 +61,7 @@ class CraftingDataPacket extends DataPacket{ /** @var bool */ public $cleanRecipes = false; + /** @var mixed[][] */ public $decodedEntries = []; public function clean(){ @@ -161,7 +161,10 @@ class CraftingDataPacket extends DataPacket{ $this->cleanRecipes = $this->getBool(); } - private static function writeEntry($entry, NetworkBinaryStream $stream, int $pos){ + /** + * @param object $entry + */ + private static function writeEntry($entry, NetworkBinaryStream $stream, int $pos) : int{ if($entry instanceof ShapelessRecipe){ return self::writeShapelessRecipe($entry, $stream, $pos); }elseif($entry instanceof ShapedRecipe){ @@ -174,7 +177,7 @@ class CraftingDataPacket extends DataPacket{ return -1; } - private static function writeShapelessRecipe(ShapelessRecipe $recipe, NetworkBinaryStream $stream, int $pos){ + private static function writeShapelessRecipe(ShapelessRecipe $recipe, NetworkBinaryStream $stream, int $pos) : int{ $stream->putString(Binary::writeInt($pos)); //some kind of recipe ID, doesn't matter what it is as long as it's unique $stream->putUnsignedVarInt($recipe->getIngredientCount()); foreach($recipe->getIngredientList() as $item){ @@ -194,7 +197,7 @@ class CraftingDataPacket extends DataPacket{ return CraftingDataPacket::ENTRY_SHAPELESS; } - private static function writeShapedRecipe(ShapedRecipe $recipe, NetworkBinaryStream $stream, int $pos){ + private static function writeShapedRecipe(ShapedRecipe $recipe, NetworkBinaryStream $stream, int $pos) : int{ $stream->putString(Binary::writeInt($pos)); //some kind of recipe ID, doesn't matter what it is as long as it's unique $stream->putVarInt($recipe->getWidth()); $stream->putVarInt($recipe->getHeight()); @@ -218,7 +221,7 @@ class CraftingDataPacket extends DataPacket{ return CraftingDataPacket::ENTRY_SHAPED; } - private static function writeFurnaceRecipe(FurnaceRecipe $recipe, NetworkBinaryStream $stream){ + private static function writeFurnaceRecipe(FurnaceRecipe $recipe, NetworkBinaryStream $stream) : int{ $stream->putVarInt($recipe->getInput()->getId()); $result = CraftingDataPacket::ENTRY_FURNACE; if(!$recipe->getInput()->hasAnyDamageValue()){ //Data recipe @@ -230,14 +233,23 @@ class CraftingDataPacket extends DataPacket{ return $result; } + /** + * @return void + */ public function addShapelessRecipe(ShapelessRecipe $recipe){ $this->entries[] = $recipe; } + /** + * @return void + */ public function addShapedRecipe(ShapedRecipe $recipe){ $this->entries[] = $recipe; } + /** + * @return void + */ public function addFurnaceRecipe(FurnaceRecipe $recipe){ $this->entries[] = $recipe; } diff --git a/src/pocketmine/network/mcpe/protocol/DataPacket.php b/src/pocketmine/network/mcpe/protocol/DataPacket.php index aeeeaf0546..7f8aa2fb75 100644 --- a/src/pocketmine/network/mcpe/protocol/DataPacket.php +++ b/src/pocketmine/network/mcpe/protocol/DataPacket.php @@ -41,7 +41,7 @@ abstract class DataPacket extends NetworkBinaryStream{ /** @var bool */ public $isEncoded = false; - /** @var CachedEncapsulatedPacket */ + /** @var CachedEncapsulatedPacket|null */ public $__encapsulatedPacket = null; /** @var int */ @@ -49,6 +49,9 @@ abstract class DataPacket extends NetworkBinaryStream{ /** @var int */ public $recipientSubId = 0; + /** + * @return int + */ public function pid(){ return $this::NETWORK_ID; } @@ -67,13 +70,13 @@ abstract class DataPacket extends NetworkBinaryStream{ /** * Returns whether the packet may legally have unread bytes left in the buffer. - * @return bool */ public function mayHaveUnreadBytes() : bool{ return false; } /** + * @return void * @throws \OutOfBoundsException * @throws \UnexpectedValueException */ @@ -84,6 +87,7 @@ abstract class DataPacket extends NetworkBinaryStream{ } /** + * @return void * @throws \OutOfBoundsException * @throws \UnexpectedValueException */ @@ -97,6 +101,7 @@ abstract class DataPacket extends NetworkBinaryStream{ /** * Note for plugin developers: If you're adding your own packets, you should perform decoding in here. * + * @return void * @throws \OutOfBoundsException * @throws \UnexpectedValueException */ @@ -104,6 +109,9 @@ abstract class DataPacket extends NetworkBinaryStream{ } + /** + * @return void + */ public function encode(){ $this->reset(); $this->encodeHeader(); @@ -111,12 +119,17 @@ abstract class DataPacket extends NetworkBinaryStream{ $this->isEncoded = true; } + /** + * @return void + */ protected function encodeHeader(){ $this->putUnsignedVarInt(static::NETWORK_ID); } /** * Note for plugin developers: If you're adding your own packets, you should perform encoding in here. + * + * @return void */ protected function encodePayload(){ @@ -128,12 +141,13 @@ abstract class DataPacket extends NetworkBinaryStream{ * This method returns a bool to indicate whether the packet was handled or not. If the packet was unhandled, a debug message will be logged with a hexdump of the packet. * Typically this method returns the return value of the handler in the supplied NetworkSession. See other packets for examples how to implement this. * - * @param NetworkSession $session - * * @return bool true if the packet was handled successfully, false if not. */ abstract public function handle(NetworkSession $session) : bool; + /** + * @return $this + */ public function clean(){ $this->buffer = ""; $this->isEncoded = false; @@ -141,6 +155,9 @@ abstract class DataPacket extends NetworkBinaryStream{ return $this; } + /** + * @return mixed[] + */ public function __debugInfo(){ $data = []; foreach((array) $this as $k => $v){ @@ -156,10 +173,21 @@ abstract class DataPacket extends NetworkBinaryStream{ return $data; } + /** + * @param string $name + * + * @return mixed + */ public function __get($name){ throw new \Error("Undefined property: " . get_class($this) . "::\$" . $name); } + /** + * @param string $name + * @param mixed $value + * + * @return void + */ public function __set($name, $value){ throw new \Error("Undefined property: " . get_class($this) . "::\$" . $name); } diff --git a/src/pocketmine/network/mcpe/protocol/DisconnectPacket.php b/src/pocketmine/network/mcpe/protocol/DisconnectPacket.php index e9047df259..3374f14f77 100644 --- a/src/pocketmine/network/mcpe/protocol/DisconnectPacket.php +++ b/src/pocketmine/network/mcpe/protocol/DisconnectPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class DisconnectPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/EmotePacket.php b/src/pocketmine/network/mcpe/protocol/EmotePacket.php index b973b39bd9..dacf38af43 100644 --- a/src/pocketmine/network/mcpe/protocol/EmotePacket.php +++ b/src/pocketmine/network/mcpe/protocol/EmotePacket.php @@ -49,7 +49,6 @@ class EmotePacket extends DataPacket/* implements ClientboundPacket, Serverbound /** * TODO: we can't call this getEntityRuntimeId() because of base class collision (crap architecture, thanks Shoghi) - * @return int */ public function getEntityRuntimeIdField() : int{ return $this->entityRuntimeId; diff --git a/src/pocketmine/network/mcpe/protocol/GameRulesChangedPacket.php b/src/pocketmine/network/mcpe/protocol/GameRulesChangedPacket.php index 1a45daa911..6c59c16721 100644 --- a/src/pocketmine/network/mcpe/protocol/GameRulesChangedPacket.php +++ b/src/pocketmine/network/mcpe/protocol/GameRulesChangedPacket.php @@ -30,7 +30,10 @@ use pocketmine\network\mcpe\NetworkSession; class GameRulesChangedPacket extends DataPacket{ public const NETWORK_ID = ProtocolInfo::GAME_RULES_CHANGED_PACKET; - /** @var array */ + /** + * @var mixed[][] + * @phpstan-var array + */ public $gameRules = []; protected function decodePayload(){ diff --git a/src/pocketmine/network/mcpe/protocol/HurtArmorPacket.php b/src/pocketmine/network/mcpe/protocol/HurtArmorPacket.php index 805d0f1af6..9205e046e7 100644 --- a/src/pocketmine/network/mcpe/protocol/HurtArmorPacket.php +++ b/src/pocketmine/network/mcpe/protocol/HurtArmorPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class HurtArmorPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/InteractPacket.php b/src/pocketmine/network/mcpe/protocol/InteractPacket.php index 7373962799..52b0ca4e42 100644 --- a/src/pocketmine/network/mcpe/protocol/InteractPacket.php +++ b/src/pocketmine/network/mcpe/protocol/InteractPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class InteractPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/LevelChunkPacket.php b/src/pocketmine/network/mcpe/protocol/LevelChunkPacket.php index 008d26bf34..43c5ee894d 100644 --- a/src/pocketmine/network/mcpe/protocol/LevelChunkPacket.php +++ b/src/pocketmine/network/mcpe/protocol/LevelChunkPacket.php @@ -56,8 +56,11 @@ class LevelChunkPacket extends DataPacket/* implements ClientboundPacket*/{ return $result; } + /** + * @param int[] $usedBlobHashes + */ public static function withCache(int $chunkX, int $chunkZ, int $subChunkCount, array $usedBlobHashes, string $extraPayload) : self{ - (static function(int ...$hashes){})(...$usedBlobHashes); + (static function(int ...$hashes) : void{})(...$usedBlobHashes); $result = new self; $result->chunkX = $chunkX; $result->chunkZ = $chunkZ; @@ -70,30 +73,18 @@ class LevelChunkPacket extends DataPacket/* implements ClientboundPacket*/{ return $result; } - /** - * @return int - */ public function getChunkX() : int{ return $this->chunkX; } - /** - * @return int - */ public function getChunkZ() : int{ return $this->chunkZ; } - /** - * @return int - */ public function getSubChunkCount() : int{ return $this->subChunkCount; } - /** - * @return bool - */ public function isCacheEnabled() : bool{ return $this->cacheEnabled; } @@ -105,9 +96,6 @@ class LevelChunkPacket extends DataPacket/* implements ClientboundPacket*/{ return $this->usedBlobHashes; } - /** - * @return string - */ public function getExtraPayload() : string{ return $this->extraPayload; } diff --git a/src/pocketmine/network/mcpe/protocol/LevelEventGenericPacket.php b/src/pocketmine/network/mcpe/protocol/LevelEventGenericPacket.php index 872a4d014a..7c250e7012 100644 --- a/src/pocketmine/network/mcpe/protocol/LevelEventGenericPacket.php +++ b/src/pocketmine/network/mcpe/protocol/LevelEventGenericPacket.php @@ -44,16 +44,10 @@ class LevelEventGenericPacket extends DataPacket/* implements ClientboundPacket* return $result; } - /** - * @return int - */ public function getEventId() : int{ return $this->eventId; } - /** - * @return string - */ public function getEventData() : string{ return $this->eventData; } diff --git a/src/pocketmine/network/mcpe/protocol/LoginPacket.php b/src/pocketmine/network/mcpe/protocol/LoginPacket.php index dd6488145c..5e8a5a8ed5 100644 --- a/src/pocketmine/network/mcpe/protocol/LoginPacket.php +++ b/src/pocketmine/network/mcpe/protocol/LoginPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; use pocketmine\utils\BinaryStream; use pocketmine\utils\MainLogger; @@ -46,8 +45,8 @@ class LoginPacket extends DataPacket{ public $clientUUID; /** @var int */ public $clientId; - /** @var string */ - public $xuid; + /** @var string|null */ + public $xuid = null; /** @var string */ public $identityPublicKey; /** @var string */ @@ -55,11 +54,17 @@ class LoginPacket extends DataPacket{ /** @var string */ public $locale; - /** @var array (the "chain" index contains one or more JWTs) */ + /** + * @var string[][] (the "chain" index contains one or more JWTs) + * @phpstan-var array{chain?: list} + */ public $chainData = []; /** @var string */ public $clientDataJwt; - /** @var array decoded payload of the clientData JWT */ + /** + * @var mixed[] decoded payload of the clientData JWT + * @phpstan-var array + */ public $clientData = []; /** diff --git a/src/pocketmine/network/mcpe/protocol/MapInfoRequestPacket.php b/src/pocketmine/network/mcpe/protocol/MapInfoRequestPacket.php index 4590aac25d..58c23ffdab 100644 --- a/src/pocketmine/network/mcpe/protocol/MapInfoRequestPacket.php +++ b/src/pocketmine/network/mcpe/protocol/MapInfoRequestPacket.php @@ -21,12 +21,10 @@ declare(strict_types=1); - namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class MapInfoRequestPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/MobArmorEquipmentPacket.php b/src/pocketmine/network/mcpe/protocol/MobArmorEquipmentPacket.php index af4a258674..6af905a107 100644 --- a/src/pocketmine/network/mcpe/protocol/MobArmorEquipmentPacket.php +++ b/src/pocketmine/network/mcpe/protocol/MobArmorEquipmentPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\item\Item; use pocketmine\network\mcpe\NetworkSession; diff --git a/src/pocketmine/network/mcpe/protocol/MobEffectPacket.php b/src/pocketmine/network/mcpe/protocol/MobEffectPacket.php index e14bf73578..a17de4d176 100644 --- a/src/pocketmine/network/mcpe/protocol/MobEffectPacket.php +++ b/src/pocketmine/network/mcpe/protocol/MobEffectPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class MobEffectPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/MobEquipmentPacket.php b/src/pocketmine/network/mcpe/protocol/MobEquipmentPacket.php index 49025bb27a..723100c707 100644 --- a/src/pocketmine/network/mcpe/protocol/MobEquipmentPacket.php +++ b/src/pocketmine/network/mcpe/protocol/MobEquipmentPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\item\Item; use pocketmine\network\mcpe\NetworkSession; diff --git a/src/pocketmine/network/mcpe/protocol/MoveActorAbsolutePacket.php b/src/pocketmine/network/mcpe/protocol/MoveActorAbsolutePacket.php index 8a7685593e..7e0e7b5485 100644 --- a/src/pocketmine/network/mcpe/protocol/MoveActorAbsolutePacket.php +++ b/src/pocketmine/network/mcpe/protocol/MoveActorAbsolutePacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\math\Vector3; use pocketmine\network\mcpe\NetworkSession; diff --git a/src/pocketmine/network/mcpe/protocol/MoveActorDeltaPacket.php b/src/pocketmine/network/mcpe/protocol/MoveActorDeltaPacket.php index c92265abdf..1728b936d7 100644 --- a/src/pocketmine/network/mcpe/protocol/MoveActorDeltaPacket.php +++ b/src/pocketmine/network/mcpe/protocol/MoveActorDeltaPacket.php @@ -55,14 +55,14 @@ class MoveActorDeltaPacket extends DataPacket{ public $zRot = 0.0; private function maybeReadCoord(int $flag) : int{ - if($this->flags & $flag){ + if(($this->flags & $flag) !== 0){ return $this->getVarInt(); } return 0; } private function maybeReadRotation(int $flag) : float{ - if($this->flags & $flag){ + if(($this->flags & $flag) !== 0){ return $this->getByteRotation(); } return 0.0; @@ -80,13 +80,13 @@ class MoveActorDeltaPacket extends DataPacket{ } private function maybeWriteCoord(int $flag, int $val) : void{ - if($this->flags & $flag){ + if(($this->flags & $flag) !== 0){ $this->putVarInt($val); } } private function maybeWriteRotation(int $flag, float $val) : void{ - if($this->flags & $flag){ + if(($this->flags & $flag) !== 0){ $this->putByteRotation($val); } } diff --git a/src/pocketmine/network/mcpe/protocol/MovePlayerPacket.php b/src/pocketmine/network/mcpe/protocol/MovePlayerPacket.php index cb85b447e5..5f318e968d 100644 --- a/src/pocketmine/network/mcpe/protocol/MovePlayerPacket.php +++ b/src/pocketmine/network/mcpe/protocol/MovePlayerPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\math\Vector3; use pocketmine\network\mcpe\NetworkSession; diff --git a/src/pocketmine/network/mcpe/protocol/PacketPool.php b/src/pocketmine/network/mcpe/protocol/PacketPool.php index 3ca0541046..3c8e3610e5 100644 --- a/src/pocketmine/network/mcpe/protocol/PacketPool.php +++ b/src/pocketmine/network/mcpe/protocol/PacketPool.php @@ -28,8 +28,11 @@ use pocketmine\utils\BinaryDataException; class PacketPool{ /** @var \SplFixedArray */ - protected static $pool = null; + protected static $pool; + /** + * @return void + */ public static function init(){ static::$pool = new \SplFixedArray(256); @@ -178,25 +181,17 @@ class PacketPool{ } /** - * @param DataPacket $packet + * @return void */ public static function registerPacket(DataPacket $packet){ static::$pool[$packet->pid()] = clone $packet; } - /** - * @param int $pid - * - * @return DataPacket - */ public static function getPacketById(int $pid) : DataPacket{ return isset(static::$pool[$pid]) ? clone static::$pool[$pid] : new UnknownPacket(); } /** - * @param string $buffer - * - * @return DataPacket * @throws BinaryDataException */ public static function getPacket(string $buffer) : DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/PlaySoundPacket.php b/src/pocketmine/network/mcpe/protocol/PlaySoundPacket.php index b9ddb193e3..94ef54ee79 100644 --- a/src/pocketmine/network/mcpe/protocol/PlaySoundPacket.php +++ b/src/pocketmine/network/mcpe/protocol/PlaySoundPacket.php @@ -21,12 +21,10 @@ declare(strict_types=1); - namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class PlaySoundPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/PlayStatusPacket.php b/src/pocketmine/network/mcpe/protocol/PlayStatusPacket.php index 97e65ffb33..1c81f5049b 100644 --- a/src/pocketmine/network/mcpe/protocol/PlayStatusPacket.php +++ b/src/pocketmine/network/mcpe/protocol/PlayStatusPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class PlayStatusPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/PlayerActionPacket.php b/src/pocketmine/network/mcpe/protocol/PlayerActionPacket.php index 590111e151..647c5c5738 100644 --- a/src/pocketmine/network/mcpe/protocol/PlayerActionPacket.php +++ b/src/pocketmine/network/mcpe/protocol/PlayerActionPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class PlayerActionPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/PlayerAuthInputPacket.php b/src/pocketmine/network/mcpe/protocol/PlayerAuthInputPacket.php index 91cac5c166..13acf5c72b 100644 --- a/src/pocketmine/network/mcpe/protocol/PlayerAuthInputPacket.php +++ b/src/pocketmine/network/mcpe/protocol/PlayerAuthInputPacket.php @@ -56,18 +56,9 @@ class PlayerAuthInputPacket extends DataPacket/* implements ServerboundPacket*/{ private $vrGazeDirection = null; /** - * @param Vector3 $position - * @param float $pitch - * @param float $yaw - * @param float $headYaw - * @param float $moveVecX - * @param float $moveVecZ - * @param int $inputFlags * @param int $inputMode @see InputMode * @param int $playMode @see PlayMode * @param Vector3|null $vrGazeDirection only used when PlayMode::VR - * - * @return self */ public static function create(Vector3 $position, float $pitch, float $yaw, float $headYaw, float $moveVecX, float $moveVecZ, int $inputFlags, int $inputMode, int $playMode, ?Vector3 $vrGazeDirection = null) : self{ if($playMode === PlayMode::VR and $vrGazeDirection === null){ @@ -85,7 +76,7 @@ class PlayerAuthInputPacket extends DataPacket/* implements ServerboundPacket*/{ $result->inputMode = $inputMode; $result->playMode = $playMode; if($vrGazeDirection !== null){ - $this->vrGazeDirection = $vrGazeDirection->asVector3(); + $result->vrGazeDirection = $vrGazeDirection->asVector3(); } return $result; } @@ -120,7 +111,6 @@ class PlayerAuthInputPacket extends DataPacket/* implements ServerboundPacket*/{ /** * @see InputMode - * @return int */ public function getInputMode() : int{ return $this->inputMode; @@ -128,7 +118,6 @@ class PlayerAuthInputPacket extends DataPacket/* implements ServerboundPacket*/{ /** * @see PlayMode - * @return int */ public function getPlayMode() : int{ return $this->playMode; diff --git a/src/pocketmine/network/mcpe/protocol/PlayerInputPacket.php b/src/pocketmine/network/mcpe/protocol/PlayerInputPacket.php index 9835e832ab..65274393b2 100644 --- a/src/pocketmine/network/mcpe/protocol/PlayerInputPacket.php +++ b/src/pocketmine/network/mcpe/protocol/PlayerInputPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class PlayerInputPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/PlayerListPacket.php b/src/pocketmine/network/mcpe/protocol/PlayerListPacket.php index b15f7b413b..de15f2825c 100644 --- a/src/pocketmine/network/mcpe/protocol/PlayerListPacket.php +++ b/src/pocketmine/network/mcpe/protocol/PlayerListPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; use pocketmine\network\mcpe\protocol\types\PlayerListEntry; use function count; diff --git a/src/pocketmine/network/mcpe/protocol/RemoveActorPacket.php b/src/pocketmine/network/mcpe/protocol/RemoveActorPacket.php index 6173bee92a..d888106bcb 100644 --- a/src/pocketmine/network/mcpe/protocol/RemoveActorPacket.php +++ b/src/pocketmine/network/mcpe/protocol/RemoveActorPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class RemoveActorPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/RemoveEntityPacket.php b/src/pocketmine/network/mcpe/protocol/RemoveEntityPacket.php index 82f50e158f..ca5b0a6d99 100644 --- a/src/pocketmine/network/mcpe/protocol/RemoveEntityPacket.php +++ b/src/pocketmine/network/mcpe/protocol/RemoveEntityPacket.php @@ -39,9 +39,6 @@ class RemoveEntityPacket extends DataPacket/* implements ClientboundPacket*/{ return $result; } - /** - * @return int - */ public function getUvarint1() : int{ return $this->uvarint1; } diff --git a/src/pocketmine/network/mcpe/protocol/RequestChunkRadiusPacket.php b/src/pocketmine/network/mcpe/protocol/RequestChunkRadiusPacket.php index 4c296c7574..497b39973c 100644 --- a/src/pocketmine/network/mcpe/protocol/RequestChunkRadiusPacket.php +++ b/src/pocketmine/network/mcpe/protocol/RequestChunkRadiusPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class RequestChunkRadiusPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/ResourcePackChunkDataPacket.php b/src/pocketmine/network/mcpe/protocol/ResourcePackChunkDataPacket.php index 500a878c92..0365539be8 100644 --- a/src/pocketmine/network/mcpe/protocol/ResourcePackChunkDataPacket.php +++ b/src/pocketmine/network/mcpe/protocol/ResourcePackChunkDataPacket.php @@ -21,12 +21,10 @@ declare(strict_types=1); - namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class ResourcePackChunkDataPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/ResourcePackChunkRequestPacket.php b/src/pocketmine/network/mcpe/protocol/ResourcePackChunkRequestPacket.php index e095057969..88f8313baa 100644 --- a/src/pocketmine/network/mcpe/protocol/ResourcePackChunkRequestPacket.php +++ b/src/pocketmine/network/mcpe/protocol/ResourcePackChunkRequestPacket.php @@ -21,12 +21,10 @@ declare(strict_types=1); - namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class ResourcePackChunkRequestPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/ResourcePackClientResponsePacket.php b/src/pocketmine/network/mcpe/protocol/ResourcePackClientResponsePacket.php index 677c809af1..ddec33eecd 100644 --- a/src/pocketmine/network/mcpe/protocol/ResourcePackClientResponsePacket.php +++ b/src/pocketmine/network/mcpe/protocol/ResourcePackClientResponsePacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; use function count; diff --git a/src/pocketmine/network/mcpe/protocol/ResourcePackDataInfoPacket.php b/src/pocketmine/network/mcpe/protocol/ResourcePackDataInfoPacket.php index 81bdfe702f..2a1ae104ee 100644 --- a/src/pocketmine/network/mcpe/protocol/ResourcePackDataInfoPacket.php +++ b/src/pocketmine/network/mcpe/protocol/ResourcePackDataInfoPacket.php @@ -21,12 +21,10 @@ declare(strict_types=1); - namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; use pocketmine\network\mcpe\protocol\types\ResourcePackType; diff --git a/src/pocketmine/network/mcpe/protocol/ResourcePackStackPacket.php b/src/pocketmine/network/mcpe/protocol/ResourcePackStackPacket.php index 41fd445e79..5d18356756 100644 --- a/src/pocketmine/network/mcpe/protocol/ResourcePackStackPacket.php +++ b/src/pocketmine/network/mcpe/protocol/ResourcePackStackPacket.php @@ -21,12 +21,10 @@ declare(strict_types=1); - namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; use pocketmine\resourcepacks\ResourcePack; use function count; diff --git a/src/pocketmine/network/mcpe/protocol/ResourcePacksInfoPacket.php b/src/pocketmine/network/mcpe/protocol/ResourcePacksInfoPacket.php index fd46d45d95..0144587c88 100644 --- a/src/pocketmine/network/mcpe/protocol/ResourcePacksInfoPacket.php +++ b/src/pocketmine/network/mcpe/protocol/ResourcePacksInfoPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; use pocketmine\resourcepacks\ResourcePack; use function count; diff --git a/src/pocketmine/network/mcpe/protocol/RespawnPacket.php b/src/pocketmine/network/mcpe/protocol/RespawnPacket.php index 6705877e8a..58a52bf2ff 100644 --- a/src/pocketmine/network/mcpe/protocol/RespawnPacket.php +++ b/src/pocketmine/network/mcpe/protocol/RespawnPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\math\Vector3; use pocketmine\network\mcpe\NetworkSession; diff --git a/src/pocketmine/network/mcpe/protocol/RiderJumpPacket.php b/src/pocketmine/network/mcpe/protocol/RiderJumpPacket.php index 3ee83a606f..ba108848cf 100644 --- a/src/pocketmine/network/mcpe/protocol/RiderJumpPacket.php +++ b/src/pocketmine/network/mcpe/protocol/RiderJumpPacket.php @@ -21,12 +21,10 @@ declare(strict_types=1); - namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class RiderJumpPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/ServerToClientHandshakePacket.php b/src/pocketmine/network/mcpe/protocol/ServerToClientHandshakePacket.php index ee1f401522..25449d9427 100644 --- a/src/pocketmine/network/mcpe/protocol/ServerToClientHandshakePacket.php +++ b/src/pocketmine/network/mcpe/protocol/ServerToClientHandshakePacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class ServerToClientHandshakePacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/SetActorDataPacket.php b/src/pocketmine/network/mcpe/protocol/SetActorDataPacket.php index de9639e7a9..c48c864200 100644 --- a/src/pocketmine/network/mcpe/protocol/SetActorDataPacket.php +++ b/src/pocketmine/network/mcpe/protocol/SetActorDataPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class SetActorDataPacket extends DataPacket{ @@ -33,7 +32,10 @@ class SetActorDataPacket extends DataPacket{ /** @var int */ public $entityRuntimeId; - /** @var array */ + /** + * @var mixed[][] + * @phpstan-var array + */ public $metadata; protected function decodePayload(){ diff --git a/src/pocketmine/network/mcpe/protocol/SetActorLinkPacket.php b/src/pocketmine/network/mcpe/protocol/SetActorLinkPacket.php index da8acbf583..576d2abb54 100644 --- a/src/pocketmine/network/mcpe/protocol/SetActorLinkPacket.php +++ b/src/pocketmine/network/mcpe/protocol/SetActorLinkPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; use pocketmine\network\mcpe\protocol\types\EntityLink; diff --git a/src/pocketmine/network/mcpe/protocol/SetActorMotionPacket.php b/src/pocketmine/network/mcpe/protocol/SetActorMotionPacket.php index af2f3199da..f4e1dcc2c7 100644 --- a/src/pocketmine/network/mcpe/protocol/SetActorMotionPacket.php +++ b/src/pocketmine/network/mcpe/protocol/SetActorMotionPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\math\Vector3; use pocketmine\network\mcpe\NetworkSession; diff --git a/src/pocketmine/network/mcpe/protocol/SetCommandsEnabledPacket.php b/src/pocketmine/network/mcpe/protocol/SetCommandsEnabledPacket.php index 0f3c87ce9c..f1fa52c95f 100644 --- a/src/pocketmine/network/mcpe/protocol/SetCommandsEnabledPacket.php +++ b/src/pocketmine/network/mcpe/protocol/SetCommandsEnabledPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class SetCommandsEnabledPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/SetDifficultyPacket.php b/src/pocketmine/network/mcpe/protocol/SetDifficultyPacket.php index c960e79507..c8354bf1b2 100644 --- a/src/pocketmine/network/mcpe/protocol/SetDifficultyPacket.php +++ b/src/pocketmine/network/mcpe/protocol/SetDifficultyPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class SetDifficultyPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/SetHealthPacket.php b/src/pocketmine/network/mcpe/protocol/SetHealthPacket.php index b87a0e9fb6..5daca24a39 100644 --- a/src/pocketmine/network/mcpe/protocol/SetHealthPacket.php +++ b/src/pocketmine/network/mcpe/protocol/SetHealthPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class SetHealthPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/SetPlayerGameTypePacket.php b/src/pocketmine/network/mcpe/protocol/SetPlayerGameTypePacket.php index 81a019eb5c..835c10fd97 100644 --- a/src/pocketmine/network/mcpe/protocol/SetPlayerGameTypePacket.php +++ b/src/pocketmine/network/mcpe/protocol/SetPlayerGameTypePacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class SetPlayerGameTypePacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/SetSpawnPositionPacket.php b/src/pocketmine/network/mcpe/protocol/SetSpawnPositionPacket.php index 5ba33933e6..9919f20a25 100644 --- a/src/pocketmine/network/mcpe/protocol/SetSpawnPositionPacket.php +++ b/src/pocketmine/network/mcpe/protocol/SetSpawnPositionPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class SetSpawnPositionPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/SetTitlePacket.php b/src/pocketmine/network/mcpe/protocol/SetTitlePacket.php index 6065eacdc4..346737f451 100644 --- a/src/pocketmine/network/mcpe/protocol/SetTitlePacket.php +++ b/src/pocketmine/network/mcpe/protocol/SetTitlePacket.php @@ -21,12 +21,10 @@ declare(strict_types=1); - namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class SetTitlePacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/ShowCreditsPacket.php b/src/pocketmine/network/mcpe/protocol/ShowCreditsPacket.php index 6cc5a74439..fa7f0cb5bf 100644 --- a/src/pocketmine/network/mcpe/protocol/ShowCreditsPacket.php +++ b/src/pocketmine/network/mcpe/protocol/ShowCreditsPacket.php @@ -21,12 +21,10 @@ declare(strict_types=1); - namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class ShowCreditsPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/SpawnExperienceOrbPacket.php b/src/pocketmine/network/mcpe/protocol/SpawnExperienceOrbPacket.php index cacfc0dd69..5b2bedb228 100644 --- a/src/pocketmine/network/mcpe/protocol/SpawnExperienceOrbPacket.php +++ b/src/pocketmine/network/mcpe/protocol/SpawnExperienceOrbPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\math\Vector3; use pocketmine\network\mcpe\NetworkSession; diff --git a/src/pocketmine/network/mcpe/protocol/StartGamePacket.php b/src/pocketmine/network/mcpe/protocol/StartGamePacket.php index b3273ddd0c..bcddf5bab2 100644 --- a/src/pocketmine/network/mcpe/protocol/StartGamePacket.php +++ b/src/pocketmine/network/mcpe/protocol/StartGamePacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\math\Vector3; use pocketmine\nbt\NetworkLittleEndianNBTStream; use pocketmine\nbt\tag\ListTag; @@ -103,7 +102,10 @@ class StartGamePacket extends DataPacket{ public $commandsEnabled; /** @var bool */ public $isTexturePacksRequired = true; - /** @var array */ + /** + * @var mixed[][] + * @phpstan-var array + */ public $gameRules = [ //TODO: implement this "naturalregeneration" => [1, false] //Hack for client side regeneration ]; @@ -153,7 +155,10 @@ class StartGamePacket extends DataPacket{ /** @var ListTag|null */ public $blockTable = null; - /** @var array|null string (name) => int16 (legacyID) */ + /** + * @var int[]|null string (name) => int16 (legacyID) + * @phpstan-var array|null + */ public $itemTable = null; protected function decodePayload(){ @@ -300,6 +305,10 @@ class StartGamePacket extends DataPacket{ $this->putString($this->multiplayerCorrelationId); } + /** + * @param int[] $table + * @phpstan-param array $table + */ private static function serializeItemTable(array $table) : string{ $stream = new NetworkBinaryStream(); $stream->putUnsignedVarInt(count($table)); diff --git a/src/pocketmine/network/mcpe/protocol/StopSoundPacket.php b/src/pocketmine/network/mcpe/protocol/StopSoundPacket.php index fc6dc5f3be..979ff6b297 100644 --- a/src/pocketmine/network/mcpe/protocol/StopSoundPacket.php +++ b/src/pocketmine/network/mcpe/protocol/StopSoundPacket.php @@ -21,12 +21,10 @@ declare(strict_types=1); - namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class StopSoundPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/TakeItemActorPacket.php b/src/pocketmine/network/mcpe/protocol/TakeItemActorPacket.php index 173911e05b..bb61123a24 100644 --- a/src/pocketmine/network/mcpe/protocol/TakeItemActorPacket.php +++ b/src/pocketmine/network/mcpe/protocol/TakeItemActorPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class TakeItemActorPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/TextPacket.php b/src/pocketmine/network/mcpe/protocol/TextPacket.php index 677c63cc92..799e8afc2d 100644 --- a/src/pocketmine/network/mcpe/protocol/TextPacket.php +++ b/src/pocketmine/network/mcpe/protocol/TextPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; use function count; diff --git a/src/pocketmine/network/mcpe/protocol/UnknownPacket.php b/src/pocketmine/network/mcpe/protocol/UnknownPacket.php index e110c4043f..73de061462 100644 --- a/src/pocketmine/network/mcpe/protocol/UnknownPacket.php +++ b/src/pocketmine/network/mcpe/protocol/UnknownPacket.php @@ -21,10 +21,8 @@ declare(strict_types=1); - namespace pocketmine\network\mcpe\protocol; - use pocketmine\network\mcpe\NetworkSession; use function ord; use function strlen; diff --git a/src/pocketmine/network/mcpe/protocol/UpdateAttributesPacket.php b/src/pocketmine/network/mcpe/protocol/UpdateAttributesPacket.php index 5bf84a49c0..69d2d4be38 100644 --- a/src/pocketmine/network/mcpe/protocol/UpdateAttributesPacket.php +++ b/src/pocketmine/network/mcpe/protocol/UpdateAttributesPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\entity\Attribute; use pocketmine\network\mcpe\NetworkSession; diff --git a/src/pocketmine/network/mcpe/protocol/UpdateBlockPacket.php b/src/pocketmine/network/mcpe/protocol/UpdateBlockPacket.php index e6e99cac74..9e7ca6c322 100644 --- a/src/pocketmine/network/mcpe/protocol/UpdateBlockPacket.php +++ b/src/pocketmine/network/mcpe/protocol/UpdateBlockPacket.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; class UpdateBlockPacket extends DataPacket{ diff --git a/src/pocketmine/network/mcpe/protocol/UpdateTradePacket.php b/src/pocketmine/network/mcpe/protocol/UpdateTradePacket.php index 40e15439d3..8bf01c70d9 100644 --- a/src/pocketmine/network/mcpe/protocol/UpdateTradePacket.php +++ b/src/pocketmine/network/mcpe/protocol/UpdateTradePacket.php @@ -21,12 +21,10 @@ declare(strict_types=1); - namespace pocketmine\network\mcpe\protocol; #include - use pocketmine\network\mcpe\NetworkSession; use pocketmine\network\mcpe\protocol\types\WindowTypes; diff --git a/src/pocketmine/network/mcpe/protocol/types/ChunkCacheBlob.php b/src/pocketmine/network/mcpe/protocol/types/ChunkCacheBlob.php index acf09f35fe..a20137620e 100644 --- a/src/pocketmine/network/mcpe/protocol/types/ChunkCacheBlob.php +++ b/src/pocketmine/network/mcpe/protocol/types/ChunkCacheBlob.php @@ -31,25 +31,16 @@ class ChunkCacheBlob{ /** * ChunkCacheBlob constructor. - * - * @param int $hash - * @param string $payload */ public function __construct(int $hash, string $payload){ $this->hash = $hash; $this->payload = $payload; } - /** - * @return int - */ public function getHash() : int{ return $this->hash; } - /** - * @return string - */ public function getPayload() : string{ return $this->payload; } diff --git a/src/pocketmine/network/mcpe/protocol/types/CommandEnumConstraint.php b/src/pocketmine/network/mcpe/protocol/types/CommandEnumConstraint.php index a97bb9cdaf..4b66b0a754 100644 --- a/src/pocketmine/network/mcpe/protocol/types/CommandEnumConstraint.php +++ b/src/pocketmine/network/mcpe/protocol/types/CommandEnumConstraint.php @@ -32,12 +32,10 @@ class CommandEnumConstraint{ private $constraints; //TODO: find constants /** - * @param CommandEnum $enum - * @param int $valueOffset * @param int[] $constraints */ public function __construct(CommandEnum $enum, int $valueOffset, array $constraints){ - (static function(int ...$_){})(...$constraints); + (static function(int ...$_) : void{})(...$constraints); if(!isset($enum->enumValues[$valueOffset])){ throw new \InvalidArgumentException("Invalid enum value offset $valueOffset"); } diff --git a/src/pocketmine/network/mcpe/protocol/types/LegacySkinAdapter.php b/src/pocketmine/network/mcpe/protocol/types/LegacySkinAdapter.php index e36a9493b9..3b81144cd5 100644 --- a/src/pocketmine/network/mcpe/protocol/types/LegacySkinAdapter.php +++ b/src/pocketmine/network/mcpe/protocol/types/LegacySkinAdapter.php @@ -25,7 +25,6 @@ namespace pocketmine\network\mcpe\protocol\types; use pocketmine\entity\Skin; -use function is_array; use function is_string; use function json_decode; use function json_encode; @@ -59,7 +58,7 @@ class LegacySkinAdapter implements SkinAdapter{ $geometryName = ""; $resourcePatch = json_decode($data->getResourcePatch(), true); - if(is_array($resourcePatch["geometry"]) && is_string($resourcePatch["geometry"]["default"])){ + if(isset($resourcePatch["geometry"]["default"]) && is_string($resourcePatch["geometry"]["default"])){ $geometryName = $resourcePatch["geometry"]["default"]; }else{ //TODO: Kick for invalid skin diff --git a/src/pocketmine/network/mcpe/protocol/types/MapDecoration.php b/src/pocketmine/network/mcpe/protocol/types/MapDecoration.php new file mode 100644 index 0000000000..564cdf4bf6 --- /dev/null +++ b/src/pocketmine/network/mcpe/protocol/types/MapDecoration.php @@ -0,0 +1,74 @@ +icon = $icon; + $this->rotation = $rotation; + $this->xOffset = $xOffset; + $this->yOffset = $yOffset; + $this->label = $label; + $this->color = $color; + } + + public function getIcon() : int{ + return $this->icon; + } + + public function getRotation() : int{ + return $this->rotation; + } + + public function getXOffset() : int{ + return $this->xOffset; + } + + public function getYOffset() : int{ + return $this->yOffset; + } + + public function getLabel() : string{ + return $this->label; + } + + public function getColor() : Color{ + return $this->color; + } +} diff --git a/src/pocketmine/network/mcpe/protocol/types/NetworkInventoryAction.php b/src/pocketmine/network/mcpe/protocol/types/NetworkInventoryAction.php index 54ca696826..9b2b2610ec 100644 --- a/src/pocketmine/network/mcpe/protocol/types/NetworkInventoryAction.php +++ b/src/pocketmine/network/mcpe/protocol/types/NetworkInventoryAction.php @@ -48,18 +48,12 @@ class NetworkInventoryAction{ * * Expect these to change in the future. */ - public const SOURCE_TYPE_CRAFTING_ADD_INGREDIENT = -2; - public const SOURCE_TYPE_CRAFTING_REMOVE_INGREDIENT = -3; public const SOURCE_TYPE_CRAFTING_RESULT = -4; public const SOURCE_TYPE_CRAFTING_USE_INGREDIENT = -5; - public const SOURCE_TYPE_ANVIL_INPUT = -10; - public const SOURCE_TYPE_ANVIL_MATERIAL = -11; public const SOURCE_TYPE_ANVIL_RESULT = -12; public const SOURCE_TYPE_ANVIL_OUTPUT = -13; - public const SOURCE_TYPE_ENCHANT_INPUT = -15; - public const SOURCE_TYPE_ENCHANT_MATERIAL = -16; public const SOURCE_TYPE_ENCHANT_OUTPUT = -17; public const SOURCE_TYPE_TRADING_INPUT_1 = -20; @@ -69,9 +63,6 @@ class NetworkInventoryAction{ public const SOURCE_TYPE_BEACON = -24; - /** Any client-side window dropping its contents when the player closes it */ - public const SOURCE_TYPE_CONTAINER_DROP_CONTENTS = -100; - public const ACTION_MAGIC_SLOT_CREATIVE_DELETE_ITEM = 0; public const ACTION_MAGIC_SLOT_CREATIVE_CREATE_ITEM = 1; @@ -92,8 +83,6 @@ class NetworkInventoryAction{ public $newItem; /** - * @param InventoryTransactionPacket $packet - * * @return $this */ public function read(InventoryTransactionPacket $packet){ @@ -123,7 +112,7 @@ class NetworkInventoryAction{ } /** - * @param InventoryTransactionPacket $packet + * @return void */ public function write(InventoryTransactionPacket $packet){ $packet->putUnsignedVarInt($this->sourceType); @@ -150,8 +139,6 @@ class NetworkInventoryAction{ } /** - * @param Player $player - * * @return InventoryAction|null * * @throws \UnexpectedValueException @@ -214,10 +201,6 @@ class NetworkInventoryAction{ case self::SOURCE_TODO: //These types need special handling. switch($this->windowId){ - case self::SOURCE_TYPE_CRAFTING_ADD_INGREDIENT: - case self::SOURCE_TYPE_CRAFTING_REMOVE_INGREDIENT: - case self::SOURCE_TYPE_CONTAINER_DROP_CONTENTS: //TODO: this type applies to all fake windows, not just crafting - return new SlotChangeAction($player->getCraftingGrid(), $this->inventorySlot, $this->oldItem, $this->newItem); case self::SOURCE_TYPE_CRAFTING_RESULT: case self::SOURCE_TYPE_CRAFTING_USE_INGREDIENT: return null; diff --git a/src/pocketmine/network/mcpe/protocol/types/RuntimeBlockMapping.php b/src/pocketmine/network/mcpe/protocol/types/RuntimeBlockMapping.php index 5a1bd71417..e9b5dc41c4 100644 --- a/src/pocketmine/network/mcpe/protocol/types/RuntimeBlockMapping.php +++ b/src/pocketmine/network/mcpe/protocol/types/RuntimeBlockMapping.php @@ -123,18 +123,12 @@ final class RuntimeBlockMapping{ */ private static function randomizeTable(array $table) : array{ $postSeed = mt_rand(); //save a seed to set afterwards, to avoid poor quality randoms - mt_srand(getmypid() ?: 0); //Use a seed which is the same on all threads. This isn't a secure seed, but we don't care. + mt_srand(getmypid()); //Use a seed which is the same on all threads. This isn't a secure seed, but we don't care. shuffle($table); mt_srand($postSeed); //restore a good quality seed that isn't dependent on PID return $table; } - /** - * @param int $id - * @param int $meta - * - * @return int - */ public static function toStaticRuntimeId(int $id, int $meta = 0) : int{ self::lazyInit(); /* @@ -146,8 +140,6 @@ final class RuntimeBlockMapping{ } /** - * @param int $runtimeId - * * @return int[] [id, meta] */ public static function fromStaticRuntimeId(int $runtimeId) : array{ diff --git a/src/pocketmine/network/mcpe/protocol/types/SkinAdapter.php b/src/pocketmine/network/mcpe/protocol/types/SkinAdapter.php index f030f4488a..357d7c2aba 100644 --- a/src/pocketmine/network/mcpe/protocol/types/SkinAdapter.php +++ b/src/pocketmine/network/mcpe/protocol/types/SkinAdapter.php @@ -32,17 +32,11 @@ interface SkinAdapter{ /** * Allows you to convert a skin entity to skin data. - * - * @param Skin $skin - * @return SkinData */ public function toSkinData(Skin $skin) : SkinData; /** * Allows you to convert skin data to a skin entity. - * - * @param SkinData $data - * @return Skin */ public function fromSkinData(SkinData $data) : Skin; } diff --git a/src/pocketmine/network/mcpe/protocol/types/SkinAnimation.php b/src/pocketmine/network/mcpe/protocol/types/SkinAnimation.php index 0f6726cf7c..40a9e96247 100644 --- a/src/pocketmine/network/mcpe/protocol/types/SkinAnimation.php +++ b/src/pocketmine/network/mcpe/protocol/types/SkinAnimation.php @@ -44,8 +44,6 @@ class SkinAnimation{ /** * Image of the animation. - * - * @return SkinImage */ public function getImage() : SkinImage{ return $this->image; @@ -53,8 +51,6 @@ class SkinAnimation{ /** * The type of animation you are applying. - * - * @return int */ public function getType() : int{ return $this->type; @@ -62,8 +58,6 @@ class SkinAnimation{ /** * The total amount of frames in an animation. - * - * @return float */ public function getFrames() : float{ return $this->frames; diff --git a/src/pocketmine/network/mcpe/protocol/types/SkinData.php b/src/pocketmine/network/mcpe/protocol/types/SkinData.php index 0e46d0a4f6..6ff6dfda89 100644 --- a/src/pocketmine/network/mcpe/protocol/types/SkinData.php +++ b/src/pocketmine/network/mcpe/protocol/types/SkinData.php @@ -49,17 +49,7 @@ class SkinData{ private $capeId; /** - * @param string $skinId - * @param string $resourcePatch - * @param SkinImage $skinImage * @param SkinAnimation[] $animations - * @param SkinImage|null $capeImage - * @param string $geometryData - * @param string $animationData - * @param bool $premium - * @param bool $persona - * @param bool $personaCapeOnClassic - * @param string $capeId */ public function __construct(string $skinId, string $resourcePatch, SkinImage $skinImage, array $animations = [], SkinImage $capeImage = null, string $geometryData = "", string $animationData = "", bool $premium = false, bool $persona = false, bool $personaCapeOnClassic = false, string $capeId = ""){ $this->skinId = $skinId; @@ -75,23 +65,14 @@ class SkinData{ $this->capeId = $capeId; } - /** - * @return string - */ public function getSkinId() : string{ return $this->skinId; } - /** - * @return string - */ public function getResourcePatch() : string{ return $this->resourcePatch; } - /** - * @return SkinImage - */ public function getSkinImage() : SkinImage{ return $this->skinImage; } @@ -103,51 +84,30 @@ class SkinData{ return $this->animations; } - /** - * @return SkinImage - */ public function getCapeImage() : SkinImage{ return $this->capeImage; } - /** - * @return string - */ public function getGeometryData() : string{ return $this->geometryData; } - /** - * @return string - */ public function getAnimationData() : string{ return $this->animationData; } - /** - * @return bool - */ public function isPersona() : bool{ return $this->persona; } - /** - * @return bool - */ public function isPremium() : bool{ return $this->premium; } - /** - * @return bool - */ public function isPersonaCapeOnClassic() : bool{ return $this->personaCapeOnClassic; } - /** - * @return string - */ public function getCapeId() : string{ return $this->capeId; } diff --git a/src/pocketmine/network/mcpe/protocol/types/SkinImage.php b/src/pocketmine/network/mcpe/protocol/types/SkinImage.php index fcb0c966f7..bee5632958 100644 --- a/src/pocketmine/network/mcpe/protocol/types/SkinImage.php +++ b/src/pocketmine/network/mcpe/protocol/types/SkinImage.php @@ -22,6 +22,7 @@ declare(strict_types=1); namespace pocketmine\network\mcpe\protocol\types; + use function strlen; class SkinImage{ @@ -34,6 +35,9 @@ class SkinImage{ private $data; public function __construct(int $height, int $width, string $data){ + if($height < 0 or $width < 0){ + throw new \InvalidArgumentException("Height and width cannot be negative"); + } if(($expected = $height * $width * 4) !== ($actual = strlen($data))){ throw new \InvalidArgumentException("Data should be exactly $expected bytes, got $actual bytes"); } diff --git a/src/pocketmine/network/mcpe/protocol/types/WindowTypes.php b/src/pocketmine/network/mcpe/protocol/types/WindowTypes.php index b13fd191f5..b29628ac9b 100644 --- a/src/pocketmine/network/mcpe/protocol/types/WindowTypes.php +++ b/src/pocketmine/network/mcpe/protocol/types/WindowTypes.php @@ -21,10 +21,8 @@ declare(strict_types=1); - namespace pocketmine\network\mcpe\protocol\types; - interface WindowTypes{ public const NONE = -9; diff --git a/src/pocketmine/network/query/QueryHandler.php b/src/pocketmine/network/query/QueryHandler.php index 2c605b027c..9343b67654 100644 --- a/src/pocketmine/network/query/QueryHandler.php +++ b/src/pocketmine/network/query/QueryHandler.php @@ -76,11 +76,16 @@ class QueryHandler{ /** * @deprecated + * + * @return void */ public function regenerateInfo(){ } + /** + * @return void + */ public function regenerateToken(){ $this->lastToken = $this->token; $this->token = random_bytes(16); @@ -90,6 +95,9 @@ class QueryHandler{ return Binary::readInt(substr(hash("sha512", $salt . ":" . $token, true), 7, 4)); } + /** + * @return void + */ public function handle(AdvancedSourceInterface $interface, string $address, int $port, string $packet){ $offset = 2; $packetType = ord($packet[$offset++]); diff --git a/src/pocketmine/network/rcon/RCON.php b/src/pocketmine/network/rcon/RCON.php index 01e14043ef..617f2ea9ce 100644 --- a/src/pocketmine/network/rcon/RCON.php +++ b/src/pocketmine/network/rcon/RCON.php @@ -94,12 +94,15 @@ class RCON{ $this->server->getTickSleeper()->addNotifier($notifier, function() : void{ $this->check(); }); - $this->instance = new RCONInstance($this->socket, $password, (int) max(1, $maxClients), $this->server->getLogger(), $this->ipcThreadSocket, $notifier); + $this->instance = new RCONInstance($this->socket, $password, max(1, $maxClients), $this->server->getLogger(), $this->ipcThreadSocket, $notifier); socket_getsockname($this->socket, $addr, $port); $this->server->getLogger()->info("RCON running on $addr:$port"); } + /** + * @return void + */ public function stop(){ $this->instance->close(); socket_write($this->ipcMainSocket, "\x00"); //make select() return @@ -110,6 +113,9 @@ class RCON{ @socket_close($this->ipcThreadSocket); } + /** + * @return void + */ public function check(){ $response = new RemoteConsoleCommandSender(); $command = $this->instance->cmd; @@ -122,7 +128,7 @@ class RCON{ } $this->instance->response = TextFormat::clean($response->getMessage()); - $this->instance->synchronized(function(RCONInstance $thread){ + $this->instance->synchronized(function(RCONInstance $thread) : void{ $thread->notify(); }, $this->instance); } diff --git a/src/pocketmine/network/rcon/RCONInstance.php b/src/pocketmine/network/rcon/RCONInstance.php index ee4471aa96..73999cb0d3 100644 --- a/src/pocketmine/network/rcon/RCONInstance.php +++ b/src/pocketmine/network/rcon/RCONInstance.php @@ -75,11 +75,7 @@ class RCONInstance extends Thread{ /** * @param resource $socket - * @param string $password - * @param int $maxClients - * @param \ThreadedLogger $logger * @param resource $ipcSocket - * @param null|SleeperNotifier $notifier */ public function __construct($socket, string $password, int $maxClients = 50, \ThreadedLogger $logger, $ipcSocket, ?SleeperNotifier $notifier){ $this->stop = false; @@ -95,6 +91,11 @@ class RCONInstance extends Thread{ $this->start(PTHREADS_INHERIT_NONE); } + /** + * @param resource $client + * + * @return int|false + */ private function writePacket($client, int $requestID, int $packetType, string $payload){ $pk = Binary::writeLInt($requestID) . Binary::writeLInt($packetType) @@ -103,6 +104,14 @@ class RCONInstance extends Thread{ return socket_write($client, Binary::writeLInt(strlen($pk)) . $pk); } + /** + * @param resource $client + * @param int $requestID reference parameter + * @param int $packetType reference parameter + * @param string $payload reference parameter + * + * @return bool + */ private function readPacket($client, ?int &$requestID, ?int &$packetType, ?string &$payload){ $d = @socket_read($client, 4); @@ -143,10 +152,16 @@ class RCONInstance extends Thread{ return true; } + /** + * @return void + */ public function close(){ $this->stop = true; } + /** + * @return void + */ public function run(){ $this->registerClassLoader(); @@ -193,8 +208,6 @@ class RCONInstance extends Thread{ if($p === false){ $disconnect[$id] = $sock; continue; - }elseif($p === null){ - continue; } switch($packetType){ @@ -220,7 +233,7 @@ class RCONInstance extends Thread{ } if($payload !== ""){ $this->cmd = ltrim($payload); - $this->synchronized(function(){ + $this->synchronized(function() : void{ $this->notifier->wakeupSleeper(); $this->wait(); }); @@ -251,6 +264,9 @@ class RCONInstance extends Thread{ } } + /** + * @param resource $client + */ private function disconnectClient($client) : void{ socket_getpeername($client, $ip, $port); @socket_set_option($client, SOL_SOCKET, SO_LINGER, ["l_onoff" => 1, "l_linger" => 1]); diff --git a/src/pocketmine/permission/BanEntry.php b/src/pocketmine/permission/BanEntry.php index addf5287a6..d673999259 100644 --- a/src/pocketmine/permission/BanEntry.php +++ b/src/pocketmine/permission/BanEntry.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace pocketmine\permission; use function array_shift; +use function count; use function explode; use function implode; use function strlen; @@ -31,15 +32,13 @@ use function strtolower; use function trim; class BanEntry{ - /** - * @var string - */ + /** @var string */ public static $format = "Y-m-d H:i:s O"; /** @var string */ private $name; /** @var \DateTime */ - private $creationDate = null; + private $creationDate; /** @var string */ private $source = "(Unknown)"; /** @var \DateTime|null */ @@ -60,6 +59,9 @@ class BanEntry{ return $this->creationDate; } + /** + * @return void + */ public function setCreated(\DateTime $date){ self::validateDate($date); $this->creationDate = $date; @@ -69,6 +71,9 @@ class BanEntry{ return $this->source; } + /** + * @return void + */ public function setSource(string $source){ $this->source = $source; } @@ -81,7 +86,7 @@ class BanEntry{ } /** - * @param \DateTime|null $date + * @return void */ public function setExpires(\DateTime $date = null){ if($date !== null){ @@ -100,6 +105,9 @@ class BanEntry{ return $this->reason; } + /** + * @return void + */ public function setReason(string $reason){ $this->reason = $reason; } @@ -125,8 +133,6 @@ class BanEntry{ * * @link https://bugs.php.net/bug.php?id=75992 * - * @param \DateTime $dateTime - * * @throws \RuntimeException if the argument can't be parsed from a formatted date string */ private static function validateDate(\DateTime $dateTime) : void{ @@ -134,9 +140,6 @@ class BanEntry{ } /** - * @param string $date - * - * @return \DateTime * @throws \RuntimeException */ private static function parseDate(string $date) : \DateTime{ @@ -149,9 +152,6 @@ class BanEntry{ } /** - * @param string $str - * - * @return BanEntry|null * @throws \RuntimeException */ public static function fromString(string $str) : ?BanEntry{ @@ -161,17 +161,17 @@ class BanEntry{ $str = explode("|", trim($str)); $entry = new BanEntry(trim(array_shift($str))); do{ - if(empty($str)){ + if(count($str) === 0){ break; } $entry->setCreated(self::parseDate(array_shift($str))); - if(empty($str)){ + if(count($str) === 0){ break; } $entry->setSource(trim(array_shift($str))); - if(empty($str)){ + if(count($str) === 0){ break; } @@ -179,7 +179,7 @@ class BanEntry{ if($expire !== "" and strtolower($expire) !== "forever"){ $entry->setExpires(self::parseDate($expire)); } - if(empty($str)){ + if(count($str) === 0){ break; } diff --git a/src/pocketmine/permission/BanList.php b/src/pocketmine/permission/BanList.php index de2ca150d9..71dae9c84c 100644 --- a/src/pocketmine/permission/BanList.php +++ b/src/pocketmine/permission/BanList.php @@ -45,32 +45,21 @@ class BanList{ /** @var bool */ private $enabled = true; - /** - * @param string $file - */ public function __construct(string $file){ $this->file = $file; } - /** - * @return bool - */ public function isEnabled() : bool{ return $this->enabled; } /** - * @param bool $flag + * @return void */ public function setEnabled(bool $flag){ $this->enabled = $flag; } - /** - * @param string $name - * - * @return BanEntry|null - */ public function getEntry(string $name) : ?BanEntry{ $this->removeExpired(); @@ -86,11 +75,6 @@ class BanList{ return $this->list; } - /** - * @param string $name - * - * @return bool - */ public function isBanned(string $name) : bool{ $name = strtolower($name); if(!$this->isEnabled()){ @@ -103,21 +87,13 @@ class BanList{ } /** - * @param BanEntry $entry + * @return void */ public function add(BanEntry $entry){ $this->list[$entry->getName()] = $entry; $this->save(); } - /** - * @param string $target - * @param string $reason - * @param \DateTime $expires - * @param string $source - * - * @return BanEntry - */ public function addBan(string $target, string $reason = null, \DateTime $expires = null, string $source = null) : BanEntry{ $entry = new BanEntry($target); $entry->setSource($source ?? $entry->getSource()); @@ -131,7 +107,7 @@ class BanList{ } /** - * @param string $name + * @return void */ public function remove(string $name){ $name = strtolower($name); @@ -141,6 +117,9 @@ class BanList{ } } + /** + * @return void + */ public function removeExpired(){ foreach($this->list as $name => $entry){ if($entry->hasExpired()){ @@ -149,6 +128,9 @@ class BanList{ } } + /** + * @return void + */ public function load(){ $this->list = []; $fp = @fopen($this->file, "r"); @@ -174,7 +156,7 @@ class BanList{ } /** - * @param bool $writeHeader + * @return void */ public function save(bool $writeHeader = true){ $this->removeExpired(); diff --git a/src/pocketmine/permission/DefaultPermissions.php b/src/pocketmine/permission/DefaultPermissions.php index 606e55a9ef..fa9e73ed52 100644 --- a/src/pocketmine/permission/DefaultPermissions.php +++ b/src/pocketmine/permission/DefaultPermissions.php @@ -26,12 +26,6 @@ namespace pocketmine\permission; abstract class DefaultPermissions{ public const ROOT = "pocketmine"; - /** - * @param Permission $perm - * @param Permission $parent - * - * @return Permission - */ public static function registerPermission(Permission $perm, Permission $parent = null) : Permission{ if($parent instanceof Permission){ $parent->getChildren()[$perm->getName()] = true; @@ -43,6 +37,9 @@ abstract class DefaultPermissions{ return PermissionManager::getInstance()->getPermission($perm->getName()); } + /** + * @return void + */ public static function registerCorePermissions(){ $parent = self::registerPermission(new Permission(self::ROOT, "Allows using all PocketMine commands and utilities")); diff --git a/src/pocketmine/permission/Permissible.php b/src/pocketmine/permission/Permissible.php index 517750cacc..a009cb0cf3 100644 --- a/src/pocketmine/permission/Permissible.php +++ b/src/pocketmine/permission/Permissible.php @@ -31,8 +31,6 @@ interface Permissible extends ServerOperator{ * Checks if this instance has a permission overridden * * @param string|Permission $name - * - * @return bool */ public function isPermissionSet($name) : bool; @@ -40,28 +38,16 @@ interface Permissible extends ServerOperator{ * Returns the permission value if overridden, or the default value if not * * @param string|Permission $name - * - * @return bool */ public function hasPermission($name) : bool; - /** - * @param Plugin $plugin - * @param string $name - * @param bool $value - * - * @return PermissionAttachment - */ public function addAttachment(Plugin $plugin, string $name = null, bool $value = null) : PermissionAttachment; /** - * @param PermissionAttachment $attachment - * * @return void */ public function removeAttachment(PermissionAttachment $attachment); - /** * @return void */ diff --git a/src/pocketmine/permission/PermissibleBase.php b/src/pocketmine/permission/PermissibleBase.php index 32fd74d82a..f8f6469318 100644 --- a/src/pocketmine/permission/PermissibleBase.php +++ b/src/pocketmine/permission/PermissibleBase.php @@ -32,22 +32,15 @@ class PermissibleBase implements Permissible{ /** @var ServerOperator */ private $opable; - /** @var Permissible */ + /** @var Permissible|null */ private $parent = null; - /** - * @var PermissionAttachment[] - */ + /** @var PermissionAttachment[] */ private $attachments = []; - /** - * @var PermissionAttachmentInfo[] - */ + /** @var PermissionAttachmentInfo[] */ private $permissions = []; - /** - * @param ServerOperator $opable - */ public function __construct(ServerOperator $opable){ $this->opable = $opable; if($opable instanceof Permissible){ @@ -55,34 +48,18 @@ class PermissibleBase implements Permissible{ } } - /** - * @return bool - */ public function isOp() : bool{ return $this->opable->isOp(); } - /** - * @param bool $value - */ public function setOp(bool $value){ $this->opable->setOp($value); } - /** - * @param Permission|string $name - * - * @return bool - */ public function isPermissionSet($name) : bool{ return isset($this->permissions[$name instanceof Permission ? $name->getName() : $name]); } - /** - * @param Permission|string $name - * - * @return bool - */ public function hasPermission($name) : bool{ if($name instanceof Permission){ $name = $name->getName(); @@ -104,12 +81,6 @@ class PermissibleBase implements Permissible{ /** * //TODO: tick scheduled attachments - * - * @param Plugin $plugin - * @param string $name - * @param bool $value - * - * @return PermissionAttachment */ public function addAttachment(Plugin $plugin, string $name = null, bool $value = null) : PermissionAttachment{ if(!$plugin->isEnabled()){ @@ -127,9 +98,6 @@ class PermissibleBase implements Permissible{ return $result; } - /** - * @param PermissionAttachment $attachment - */ public function removeAttachment(PermissionAttachment $attachment){ if(isset($this->attachments[spl_object_hash($attachment)])){ unset($this->attachments[spl_object_hash($attachment)]); @@ -165,6 +133,9 @@ class PermissibleBase implements Permissible{ Timings::$permissibleCalculationTimer->stopTiming(); } + /** + * @return void + */ public function clearPermissions(){ $permManager = PermissionManager::getInstance(); $permManager->unsubscribeFromAllPermissions($this->parent ?? $this); @@ -177,10 +148,8 @@ class PermissibleBase implements Permissible{ /** * @param bool[] $children - * @param bool $invert - * @param PermissionAttachment|null $attachment */ - private function calculateChildPermissions(array $children, bool $invert, ?PermissionAttachment $attachment){ + private function calculateChildPermissions(array $children, bool $invert, ?PermissionAttachment $attachment) : void{ $permManager = PermissionManager::getInstance(); foreach($children as $name => $v){ $perm = $permManager->getPermission($name); diff --git a/src/pocketmine/permission/Permission.php b/src/pocketmine/permission/Permission.php index d1eba9dcec..d2c64d900d 100644 --- a/src/pocketmine/permission/Permission.php +++ b/src/pocketmine/permission/Permission.php @@ -40,13 +40,12 @@ class Permission{ public const DEFAULT_TRUE = "true"; public const DEFAULT_FALSE = "false"; + /** @var string */ public static $DEFAULT_PERMISSION = self::DEFAULT_OP; /** * @param bool|string $value * - * @return string - * * @throws \InvalidArgumentException */ public static function getByName($value) : string{ @@ -84,8 +83,8 @@ class Permission{ } /** - * @param array $data - * @param string $default + * @param mixed[][] $data + * @phpstan-param array> $data * * @return Permission[] */ @@ -99,12 +98,9 @@ class Permission{ } /** - * @param string $name - * @param array $data - * @param string $default - * @param array $output - * - * @return Permission + * @param mixed[] $data + * @param Permission[] $output reference parameter + * @phpstan-param array $data * * @throws \Exception */ @@ -119,9 +115,7 @@ class Permission{ if(is_array($data["children"])){ foreach($data["children"] as $k => $v){ if(is_array($v)){ - if(($perm = self::loadPermission($k, $v, $default, $output)) !== null){ - $output[] = $perm; - } + $output[] = self::loadPermission($k, $v, $default, $output); } $children[$k] = true; } @@ -145,6 +139,7 @@ class Permission{ /** * @var bool[] + * @phpstan-var array */ private $children; @@ -154,10 +149,8 @@ class Permission{ /** * Creates a new Permission object to be attached to Permissible objects * - * @param string $name - * @param string $description - * @param string $defaultValue * @param bool[] $children + * @phpstan-param array $children */ public function __construct(string $name, string $description = null, string $defaultValue = null, array $children = []){ $this->name = $name; @@ -168,29 +161,24 @@ class Permission{ $this->recalculatePermissibles(); } - /** - * @return string - */ public function getName() : string{ return $this->name; } /** * @return bool[] + * @phpstan-return array */ public function &getChildren() : array{ return $this->children; } - /** - * @return string - */ public function getDefault() : string{ return $this->defaultValue; } /** - * @param string $value + * @return void */ public function setDefault(string $value){ if($value !== $this->defaultValue){ @@ -199,15 +187,12 @@ class Permission{ } } - /** - * @return string - */ public function getDescription() : string{ return $this->description; } /** - * @param string $value + * @return void */ public function setDescription(string $value){ $this->description = $value; @@ -220,6 +205,9 @@ class Permission{ return PermissionManager::getInstance()->getPermissionSubscriptions($this->name); } + /** + * @return void + */ public function recalculatePermissibles(){ $perms = $this->getPermissibles(); @@ -230,10 +218,8 @@ class Permission{ } } - /** * @param string|Permission $name - * @param bool $value * * @return Permission|null Permission if $name is a string, null if it's a Permission */ diff --git a/src/pocketmine/permission/PermissionAttachment.php b/src/pocketmine/permission/PermissionAttachment.php index 1d4693c18e..6232829465 100644 --- a/src/pocketmine/permission/PermissionAttachment.php +++ b/src/pocketmine/permission/PermissionAttachment.php @@ -27,12 +27,10 @@ use pocketmine\plugin\Plugin; use pocketmine\plugin\PluginException; class PermissionAttachment{ - /** @var PermissionRemovedExecutor */ + /** @var PermissionRemovedExecutor|null */ private $removed = null; - /** - * @var bool[] - */ + /** @var bool[] */ private $permissions = []; /** @var Permissible */ @@ -42,9 +40,6 @@ class PermissionAttachment{ private $plugin; /** - * @param Plugin $plugin - * @param Permissible $permissible - * * @throws PluginException */ public function __construct(Plugin $plugin, Permissible $permissible){ @@ -56,15 +51,12 @@ class PermissionAttachment{ $this->plugin = $plugin; } - /** - * @return Plugin - */ public function getPlugin() : Plugin{ return $this->plugin; } /** - * @param PermissionRemovedExecutor $ex + * @return void */ public function setRemovalCallback(PermissionRemovedExecutor $ex){ $this->removed = $ex; @@ -77,9 +69,6 @@ class PermissionAttachment{ return $this->removed; } - /** - * @return Permissible - */ public function getPermissible() : Permissible{ return $this->permissible; } @@ -91,6 +80,9 @@ class PermissionAttachment{ return $this->permissions; } + /** + * @return void + */ public function clearPermissions(){ $this->permissions = []; $this->permissible->recalculatePermissions(); @@ -98,16 +90,20 @@ class PermissionAttachment{ /** * @param bool[] $permissions + * + * @return void */ public function setPermissions(array $permissions){ foreach($permissions as $key => $value){ - $this->permissions[$key] = (bool) $value; + $this->permissions[$key] = $value; } $this->permissible->recalculatePermissions(); } /** * @param string[] $permissions + * + * @return void */ public function unsetPermissions(array $permissions){ foreach($permissions as $node){ @@ -118,7 +114,8 @@ class PermissionAttachment{ /** * @param string|Permission $name - * @param bool $value + * + * @return void */ public function setPermission($name, bool $value){ $name = $name instanceof Permission ? $name->getName() : $name; @@ -134,6 +131,8 @@ class PermissionAttachment{ /** * @param string|Permission $name + * + * @return void */ public function unsetPermission($name){ $name = $name instanceof Permission ? $name->getName() : $name; diff --git a/src/pocketmine/permission/PermissionAttachmentInfo.php b/src/pocketmine/permission/PermissionAttachmentInfo.php index 198f21bbfc..ac5b88074c 100644 --- a/src/pocketmine/permission/PermissionAttachmentInfo.php +++ b/src/pocketmine/permission/PermissionAttachmentInfo.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\permission; - class PermissionAttachmentInfo{ /** @var Permissible */ private $permissible; @@ -38,11 +37,6 @@ class PermissionAttachmentInfo{ private $value; /** - * @param Permissible $permissible - * @param string $permission - * @param PermissionAttachment|null $attachment - * @param bool $value - * * @throws \InvalidStateException */ public function __construct(Permissible $permissible, string $permission, PermissionAttachment $attachment = null, bool $value){ @@ -52,16 +46,10 @@ class PermissionAttachmentInfo{ $this->value = $value; } - /** - * @return Permissible - */ public function getPermissible() : Permissible{ return $this->permissible; } - /** - * @return string - */ public function getPermission() : string{ return $this->permission; } @@ -73,9 +61,6 @@ class PermissionAttachmentInfo{ return $this->attachment; } - /** - * @return bool - */ public function getValue() : bool{ return $this->value; } diff --git a/src/pocketmine/permission/PermissionManager.php b/src/pocketmine/permission/PermissionManager.php index 02d7d96648..4fe5dd65b8 100644 --- a/src/pocketmine/permission/PermissionManager.php +++ b/src/pocketmine/permission/PermissionManager.php @@ -53,19 +53,12 @@ class PermissionManager{ protected $defSubsOp = []; /** - * @param string $name - * * @return null|Permission */ public function getPermission(string $name){ return $this->permissions[$name] ?? null; } - /** - * @param Permission $permission - * - * @return bool - */ public function addPermission(Permission $permission) : bool{ if(!isset($this->permissions[$permission->getName()])){ $this->permissions[$permission->getName()] = $permission; @@ -79,6 +72,8 @@ class PermissionManager{ /** * @param string|Permission $permission + * + * @return void */ public function removePermission($permission){ if($permission instanceof Permission){ @@ -89,8 +84,6 @@ class PermissionManager{ } /** - * @param bool $op - * * @return Permission[] */ public function getDefaultPermissions(bool $op) : array{ @@ -102,7 +95,7 @@ class PermissionManager{ } /** - * @param Permission $permission + * @return void */ public function recalculatePermissionDefaults(Permission $permission){ if(isset($this->permissions[$permission->getName()])){ @@ -112,10 +105,7 @@ class PermissionManager{ } } - /** - * @param Permission $permission - */ - private function calculatePermissionDefault(Permission $permission){ + private function calculatePermissionDefault(Permission $permission) : void{ Timings::$permissionDefaultTimer->startTiming(); if($permission->getDefault() === Permission::DEFAULT_OP or $permission->getDefault() === Permission::DEFAULT_TRUE){ $this->defaultPermsOp[$permission->getName()] = $permission; @@ -129,18 +119,14 @@ class PermissionManager{ Timings::$permissionDefaultTimer->startTiming(); } - /** - * @param bool $op - */ - private function dirtyPermissibles(bool $op){ + private function dirtyPermissibles(bool $op) : void{ foreach($this->getDefaultPermSubscriptions($op) as $p){ $p->recalculatePermissions(); } } /** - * @param string $permission - * @param Permissible $permissible + * @return void */ public function subscribeToPermission(string $permission, Permissible $permissible){ if(!isset($this->permSubs[$permission])){ @@ -150,8 +136,7 @@ class PermissionManager{ } /** - * @param string $permission - * @param Permissible $permissible + * @return void */ public function unsubscribeFromPermission(string $permission, Permissible $permissible){ if(isset($this->permSubs[$permission])){ @@ -162,21 +147,16 @@ class PermissionManager{ } } - /** - * @param Permissible $permissible - */ public function unsubscribeFromAllPermissions(Permissible $permissible) : void{ foreach($this->permSubs as $permission => &$subs){ unset($subs[spl_object_hash($permissible)]); - if(empty($subs)){ + if(count($subs) === 0){ unset($this->permSubs[$permission]); } } } /** - * @param string $permission - * * @return array|Permissible[] */ public function getPermissionSubscriptions(string $permission) : array{ @@ -184,8 +164,7 @@ class PermissionManager{ } /** - * @param bool $op - * @param Permissible $permissible + * @return void */ public function subscribeToDefaultPerms(bool $op, Permissible $permissible){ if($op){ @@ -196,8 +175,7 @@ class PermissionManager{ } /** - * @param bool $op - * @param Permissible $permissible + * @return void */ public function unsubscribeFromDefaultPerms(bool $op, Permissible $permissible){ if($op){ @@ -208,8 +186,6 @@ class PermissionManager{ } /** - * @param bool $op - * * @return Permissible[] */ public function getDefaultPermSubscriptions(bool $op) : array{ diff --git a/src/pocketmine/permission/PermissionRemovedExecutor.php b/src/pocketmine/permission/PermissionRemovedExecutor.php index 3eb5598831..423f883b0a 100644 --- a/src/pocketmine/permission/PermissionRemovedExecutor.php +++ b/src/pocketmine/permission/PermissionRemovedExecutor.php @@ -23,12 +23,9 @@ declare(strict_types=1); namespace pocketmine\permission; - interface PermissionRemovedExecutor{ /** - * @param PermissionAttachment $attachment - * * @return void */ public function attachmentRemoved(PermissionAttachment $attachment); diff --git a/src/pocketmine/permission/ServerOperator.php b/src/pocketmine/permission/ServerOperator.php index a31f67d00c..ca6c9e8a0d 100644 --- a/src/pocketmine/permission/ServerOperator.php +++ b/src/pocketmine/permission/ServerOperator.php @@ -23,19 +23,16 @@ declare(strict_types=1); namespace pocketmine\permission; - interface ServerOperator{ /** * Checks if the current object has operator permissions - * - * @return bool */ public function isOp() : bool; /** * Sets the operator permission for the current object * - * @param bool $value + * @return void */ public function setOp(bool $value); } diff --git a/src/pocketmine/plugin/EventExecutor.php b/src/pocketmine/plugin/EventExecutor.php index f7697a3009..edd25a99ed 100644 --- a/src/pocketmine/plugin/EventExecutor.php +++ b/src/pocketmine/plugin/EventExecutor.php @@ -29,9 +29,6 @@ use pocketmine\event\Listener; interface EventExecutor{ /** - * @param Listener $listener - * @param Event $event - * * @return void */ public function execute(Listener $listener, Event $event); diff --git a/src/pocketmine/plugin/MethodEventExecutor.php b/src/pocketmine/plugin/MethodEventExecutor.php index aeeb012698..f25229fdb7 100644 --- a/src/pocketmine/plugin/MethodEventExecutor.php +++ b/src/pocketmine/plugin/MethodEventExecutor.php @@ -28,8 +28,12 @@ use pocketmine\event\Listener; class MethodEventExecutor implements EventExecutor{ + /** @var string */ private $method; + /** + * @param string $method + */ public function __construct($method){ $this->method = $method; } @@ -38,6 +42,9 @@ class MethodEventExecutor implements EventExecutor{ $listener->{$this->getMethod()}($event); } + /** + * @return string + */ public function getMethod(){ return $this->method; } diff --git a/src/pocketmine/plugin/PharPluginLoader.php b/src/pocketmine/plugin/PharPluginLoader.php index 3f594ace77..fd902dae8b 100644 --- a/src/pocketmine/plugin/PharPluginLoader.php +++ b/src/pocketmine/plugin/PharPluginLoader.php @@ -46,8 +46,6 @@ class PharPluginLoader implements PluginLoader{ /** * Loads the plugin contained in $file - * - * @param string $file */ public function loadPlugin(string $file) : void{ $this->loader->addPath("$file/src"); @@ -55,18 +53,11 @@ class PharPluginLoader implements PluginLoader{ /** * Gets the PluginDescription from the file - * - * @param string $file - * - * @return null|PluginDescription */ public function getPluginDescription(string $file) : ?PluginDescription{ $phar = new \Phar($file); if(isset($phar["plugin.yml"])){ - $pluginYml = $phar["plugin.yml"]; - if($pluginYml instanceof \PharFileInfo){ - return new PluginDescription($pluginYml->getContent()); - } + return new PluginDescription($phar["plugin.yml"]->getContent()); } return null; diff --git a/src/pocketmine/plugin/Plugin.php b/src/pocketmine/plugin/Plugin.php index fbef35765b..2a56aa38ac 100644 --- a/src/pocketmine/plugin/Plugin.php +++ b/src/pocketmine/plugin/Plugin.php @@ -31,7 +31,6 @@ use pocketmine\scheduler\TaskScheduler; use pocketmine\Server; use pocketmine\utils\Config; - /** * It is recommended to use PluginBase for the actual plugin */ @@ -41,17 +40,18 @@ interface Plugin extends CommandExecutor{ /** * Called when the plugin is loaded, before calling onEnable() + * + * @return void */ public function onLoad(); /** * Called when the plugin is enabled + * + * @return void */ public function onEnable(); - /** - * @return bool - */ public function isEnabled() : bool; /** @@ -60,51 +60,36 @@ interface Plugin extends CommandExecutor{ * @internal This is intended for core use only and should not be used by plugins * @see PluginManager::enablePlugin() * @see PluginManager::disablePlugin() - * - * @param bool $enabled */ public function setEnabled(bool $enabled = true) : void; /** * Called when the plugin is disabled * Use this to free open things and finish actions + * + * @return void */ public function onDisable(); - /** - * @return bool - */ public function isDisabled() : bool; /** * Gets the plugin's data folder to save files and configuration. * This directory name has a trailing slash. - * - * @return string */ public function getDataFolder() : string; - /** - * @return PluginDescription - */ public function getDescription() : PluginDescription; /** * Gets an embedded resource in the plugin file. * - * @param string $filename - * * @return null|resource Resource data, or null */ public function getResource(string $filename); /** * Saves an embedded resource to its relative location in the data folder - * - * @param string $filename - * @param bool $replace - * - * @return bool */ public function saveResource(string $filename, bool $replace = false) : bool; @@ -115,33 +100,24 @@ interface Plugin extends CommandExecutor{ */ public function getResources() : array; - /** - * @return Config - */ public function getConfig() : Config; + /** + * @return void + */ public function saveConfig(); - /** - * @return bool - */ public function saveDefaultConfig() : bool; + /** + * @return void + */ public function reloadConfig(); - /** - * @return Server - */ public function getServer() : Server; - /** - * @return string - */ public function getName() : string; - /** - * @return PluginLogger - */ public function getLogger() : PluginLogger; /** @@ -149,9 +125,6 @@ interface Plugin extends CommandExecutor{ */ public function getPluginLoader(); - /** - * @return TaskScheduler - */ public function getScheduler() : TaskScheduler; } diff --git a/src/pocketmine/plugin/PluginBase.php b/src/pocketmine/plugin/PluginBase.php index 4d8b65e69e..aac4a891ee 100644 --- a/src/pocketmine/plugin/PluginBase.php +++ b/src/pocketmine/plugin/PluginBase.php @@ -85,9 +85,6 @@ abstract class PluginBase implements Plugin{ $this->scheduler = new TaskScheduler($this->logger, $this->getFullName()); } - /** - * Called when the plugin is loaded, before calling onEnable() - */ public function onLoad(){ } @@ -100,9 +97,6 @@ abstract class PluginBase implements Plugin{ } - /** - * @return bool - */ final public function isEnabled() : bool{ return $this->isEnabled; } @@ -113,8 +107,6 @@ abstract class PluginBase implements Plugin{ * @internal This is intended for core use only and should not be used by plugins * @see PluginManager::enablePlugin() * @see PluginManager::disablePlugin() - * - * @param bool $enabled */ final public function setEnabled(bool $enabled = true) : void{ if($this->isEnabled !== $enabled){ @@ -127,9 +119,6 @@ abstract class PluginBase implements Plugin{ } } - /** - * @return bool - */ final public function isDisabled() : bool{ return !$this->isEnabled; } @@ -142,16 +131,11 @@ abstract class PluginBase implements Plugin{ return $this->description; } - /** - * @return PluginLogger - */ public function getLogger() : PluginLogger{ return $this->logger; } /** - * @param string $name - * * @return Command|PluginIdentifiableCommand|null */ public function getCommand(string $name){ @@ -168,20 +152,12 @@ abstract class PluginBase implements Plugin{ } /** - * @param CommandSender $sender - * @param Command $command - * @param string $label * @param string[] $args - * - * @return bool */ public function onCommand(CommandSender $sender, Command $command, string $label, array $args) : bool{ return false; } - /** - * @return bool - */ protected function isPhar() : bool{ return strpos($this->file, "phar://") === 0; } @@ -190,8 +166,6 @@ abstract class PluginBase implements Plugin{ * Gets an embedded resource on the plugin file. * WARNING: You must close the resource given using fclose() * - * @param string $filename - * * @return null|resource Resource data, or null */ public function getResource(string $filename){ @@ -203,12 +177,6 @@ abstract class PluginBase implements Plugin{ return null; } - /** - * @param string $filename - * @param bool $replace - * - * @return bool - */ public function saveResource(string $filename, bool $replace = false) : bool{ if(trim($filename) === ""){ return false; @@ -252,9 +220,6 @@ abstract class PluginBase implements Plugin{ return $resources; } - /** - * @return Config - */ public function getConfig() : Config{ if($this->config === null){ $this->reloadConfig(); @@ -281,30 +246,18 @@ abstract class PluginBase implements Plugin{ $this->config = new Config($this->configFile); } - /** - * @return Server - */ final public function getServer() : Server{ return $this->server; } - /** - * @return string - */ final public function getName() : string{ return $this->description->getName(); } - /** - * @return string - */ final public function getFullName() : string{ return $this->description->getFullName(); } - /** - * @return string - */ protected function getFile() : string{ return $this->file; } @@ -316,9 +269,6 @@ abstract class PluginBase implements Plugin{ return $this->loader; } - /** - * @return TaskScheduler - */ public function getScheduler() : TaskScheduler{ return $this->scheduler; } diff --git a/src/pocketmine/plugin/PluginDescription.php b/src/pocketmine/plugin/PluginDescription.php index 153c37752f..cd55c9ed4e 100644 --- a/src/pocketmine/plugin/PluginDescription.php +++ b/src/pocketmine/plugin/PluginDescription.php @@ -41,19 +41,37 @@ use function version_compare; use function yaml_parse; class PluginDescription{ + /** + * @var mixed[] + * @phpstan-var array + */ private $map; + /** @var string */ private $name; + /** @var string */ private $main; + /** @var string[] */ private $api; /** @var int[] */ private $compatibleMcpeProtocols = []; + /** + * @var string[][] + * @phpstan-var array> + */ private $extensions = []; + /** @var string[] */ private $depend = []; + /** @var string[] */ private $softDepend = []; + /** @var string[] */ private $loadBefore = []; /** @var string */ private $version; + /** + * @var mixed[][] + * @phpstan-var array> + */ private $commands = []; /** @var string */ private $description = ""; @@ -63,26 +81,26 @@ class PluginDescription{ private $website = ""; /** @var string */ private $prefix = ""; + /** @var int */ private $order = PluginLoadOrder::POSTWORLD; - /** - * @var Permission[] - */ + /** @var Permission[] */ private $permissions = []; /** - * @param string|array $yamlString + * @param string|mixed[] $yamlString + * @phpstan-param string|array $yamlString */ public function __construct($yamlString){ $this->loadMap(!is_array($yamlString) ? yaml_parse($yamlString) : $yamlString); } /** - * @param array $plugin - * + * @param mixed[] $plugin + * @phpstan-param array $plugin * @throws PluginException */ - private function loadMap(array $plugin){ + private function loadMap(array $plugin) : void{ $this->map = $plugin; $this->name = $plugin["name"]; @@ -151,15 +169,12 @@ class PluginDescription{ } } - /** - * @return string - */ public function getFullName() : string{ return $this->name . " v" . $this->version; } /** - * @return array + * @return string[] */ public function getCompatibleApis() : array{ return $this->api; @@ -179,22 +194,21 @@ class PluginDescription{ return $this->authors; } - /** - * @return string - */ public function getPrefix() : string{ return $this->prefix; } /** - * @return array + * @return mixed[][] + * @phpstan-return array> */ public function getCommands() : array{ return $this->commands; } /** - * @return array + * @return string[][] + * @phpstan-return array> */ public function getRequiredExtensions() : array{ return $this->extensions; @@ -203,6 +217,7 @@ class PluginDescription{ /** * Checks if the current PHP runtime has the extensions required by the plugin. * + * @return void * @throws PluginException if there are required extensions missing or have incompatible version, or if the version constraint cannot be parsed */ public function checkRequiredExtensions(){ @@ -211,9 +226,6 @@ class PluginDescription{ throw new PluginException("Required extension $name not loaded"); } - if(!is_array($versionConstrs)){ - $versionConstrs = [$versionConstrs]; - } $gotVersion = phpversion($name); foreach($versionConstrs as $constr){ // versionConstrs_loop if($constr === "*"){ @@ -238,43 +250,31 @@ class PluginDescription{ } /** - * @return array + * @return string[] */ public function getDepend() : array{ return $this->depend; } - /** - * @return string - */ public function getDescription() : string{ return $this->description; } /** - * @return array + * @return string[] */ public function getLoadBefore() : array{ return $this->loadBefore; } - /** - * @return string - */ public function getMain() : string{ return $this->main; } - /** - * @return string - */ public function getName() : string{ return $this->name; } - /** - * @return int - */ public function getOrder() : int{ return $this->order; } @@ -287,26 +287,24 @@ class PluginDescription{ } /** - * @return array + * @return string[] */ public function getSoftDepend() : array{ return $this->softDepend; } - /** - * @return string - */ public function getVersion() : string{ return $this->version; } - /** - * @return string - */ public function getWebsite() : string{ return $this->website; } + /** + * @return mixed[] + * @phpstan-return array + */ public function getMap() : array{ return $this->map; } diff --git a/src/pocketmine/plugin/PluginLoadOrder.php b/src/pocketmine/plugin/PluginLoadOrder.php index 1a44ed7015..ac658659d0 100644 --- a/src/pocketmine/plugin/PluginLoadOrder.php +++ b/src/pocketmine/plugin/PluginLoadOrder.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\plugin; - abstract class PluginLoadOrder{ /* * The plugin will be loaded at startup diff --git a/src/pocketmine/plugin/PluginLoader.php b/src/pocketmine/plugin/PluginLoader.php index 7e019c46c0..2bf603ddeb 100644 --- a/src/pocketmine/plugin/PluginLoader.php +++ b/src/pocketmine/plugin/PluginLoader.php @@ -30,33 +30,21 @@ interface PluginLoader{ /** * Returns whether this PluginLoader can load the plugin in the given path. - * - * @param string $path - * - * @return bool */ public function canLoadPlugin(string $path) : bool; /** * Loads the plugin contained in $file - * - * @param string $file */ public function loadPlugin(string $file) : void; /** * Gets the PluginDescription from the file - * - * @param string $file - * - * @return null|PluginDescription */ public function getPluginDescription(string $file) : ?PluginDescription; /** * Returns the protocol prefix used to access files in this plugin, e.g. file://, phar:// - * - * @return string */ public function getAccessProtocol() : string; } diff --git a/src/pocketmine/plugin/PluginLogger.php b/src/pocketmine/plugin/PluginLogger.php index 585d9da397..a7cfcdbbdb 100644 --- a/src/pocketmine/plugin/PluginLogger.php +++ b/src/pocketmine/plugin/PluginLogger.php @@ -29,6 +29,7 @@ use function spl_object_hash; class PluginLogger implements \AttachableLogger{ + /** @var string */ private $pluginName; /** @var \LoggerAttachment[] */ @@ -50,9 +51,6 @@ class PluginLogger implements \AttachableLogger{ return $this->attachments; } - /** - * @param Plugin $context - */ public function __construct(Plugin $context){ $prefix = $context->getDescription()->getPrefix(); $this->pluginName = $prefix != null ? "[$prefix] " : "[" . $context->getDescription()->getName() . "] "; diff --git a/src/pocketmine/plugin/PluginManager.php b/src/pocketmine/plugin/PluginManager.php index 6c77ddc2f9..e1c0607753 100644 --- a/src/pocketmine/plugin/PluginManager.php +++ b/src/pocketmine/plugin/PluginManager.php @@ -76,29 +76,21 @@ class PluginManager{ /** @var SimpleCommandMap */ private $commandMap; - /** - * @var Plugin[] - */ + /** @var Plugin[] */ protected $plugins = []; - /** - * @var Plugin[] - */ + /** @var Plugin[] */ protected $enabledPlugins = []; /** * @var PluginLoader[] + * @phpstan-var array, PluginLoader> */ protected $fileAssociations = []; /** @var string|null */ private $pluginDataDirectory; - /** - * @param Server $server - * @param SimpleCommandMap $commandMap - * @param null|string $pluginDataDirectory - */ public function __construct(Server $server, SimpleCommandMap $commandMap, ?string $pluginDataDirectory){ $this->server = $server; $this->commandMap = $commandMap; @@ -113,8 +105,6 @@ class PluginManager{ } /** - * @param string $name - * * @return null|Plugin */ public function getPlugin(string $name){ @@ -125,9 +115,6 @@ class PluginManager{ return null; } - /** - * @param PluginLoader $loader - */ public function registerInterface(PluginLoader $loader) : void{ $this->fileAssociations[get_class($loader)] = $loader; } @@ -147,10 +134,7 @@ class PluginManager{ } /** - * @param string $path * @param PluginLoader[] $loaders - * - * @return Plugin|null */ public function loadPlugin(string $path, array $loaders = null) : ?Plugin{ foreach($loaders ?? $this->fileAssociations as $loader){ @@ -215,8 +199,8 @@ class PluginManager{ } /** - * @param string $directory - * @param array $newLoaders + * @param string[]|null $newLoaders + * @phpstan-param list> $newLoaders * * @return Plugin[] */ @@ -304,7 +288,6 @@ class PluginManager{ } } - while(count($plugins) > 0){ $loadedThisLoop = 0; foreach($plugins as $name => $file){ @@ -349,7 +332,7 @@ class PluginManager{ if(!isset($dependencies[$name]) and !isset($softDependencies[$name])){ unset($plugins[$name]); $loadedThisLoop++; - if($plugin = $this->loadPlugin($file, $loaders) and $plugin instanceof Plugin){ + if(($plugin = $this->loadPlugin($file, $loaders)) instanceof Plugin){ $loadedPlugins[$name] = $plugin; }else{ $this->server->getLogger()->critical($this->server->getLanguage()->translateString("pocketmine.plugin.genericLoadError", [$name])); @@ -373,8 +356,6 @@ class PluginManager{ * Returns whether a specified API version string is considered compatible with the server's API version. * * @param string ...$versions - * - * @return bool */ public function isCompatibleApi(string ...$versions) : bool{ $serverString = $this->server->getApiVersion(); @@ -416,8 +397,6 @@ class PluginManager{ * @deprecated * @see PermissionManager::getPermission() * - * @param string $name - * * @return null|Permission */ public function getPermission(string $name){ @@ -427,10 +406,6 @@ class PluginManager{ /** * @deprecated * @see PermissionManager::addPermission() - * - * @param Permission $permission - * - * @return bool */ public function addPermission(Permission $permission) : bool{ return PermissionManager::getInstance()->addPermission($permission); @@ -441,6 +416,8 @@ class PluginManager{ * @see PermissionManager::removePermission() * * @param string|Permission $permission + * + * @return void */ public function removePermission($permission){ PermissionManager::getInstance()->removePermission($permission); @@ -450,8 +427,6 @@ class PluginManager{ * @deprecated * @see PermissionManager::getDefaultPermissions() * - * @param bool $op - * * @return Permission[] */ public function getDefaultPermissions(bool $op) : array{ @@ -462,7 +437,7 @@ class PluginManager{ * @deprecated * @see PermissionManager::recalculatePermissionDefaults() * - * @param Permission $permission + * @return void */ public function recalculatePermissionDefaults(Permission $permission){ PermissionManager::getInstance()->recalculatePermissionDefaults($permission); @@ -472,8 +447,7 @@ class PluginManager{ * @deprecated * @see PermissionManager::subscribeToPermission() * - * @param string $permission - * @param Permissible $permissible + * @return void */ public function subscribeToPermission(string $permission, Permissible $permissible){ PermissionManager::getInstance()->subscribeToPermission($permission, $permissible); @@ -483,8 +457,7 @@ class PluginManager{ * @deprecated * @see PermissionManager::unsubscribeFromPermission() * - * @param string $permission - * @param Permissible $permissible + * @return void */ public function unsubscribeFromPermission(string $permission, Permissible $permissible){ PermissionManager::getInstance()->unsubscribeFromPermission($permission, $permissible); @@ -493,8 +466,6 @@ class PluginManager{ /** * @deprecated * @see PermissionManager::unsubscribeFromAllPermissions() - * - * @param Permissible $permissible */ public function unsubscribeFromAllPermissions(Permissible $permissible) : void{ PermissionManager::getInstance()->unsubscribeFromAllPermissions($permissible); @@ -504,8 +475,6 @@ class PluginManager{ * @deprecated * @see PermissionManager::getPermissionSubscriptions() * - * @param string $permission - * * @return array|Permissible[] */ public function getPermissionSubscriptions(string $permission) : array{ @@ -516,8 +485,7 @@ class PluginManager{ * @deprecated * @see PermissionManager::subscribeToDefaultPerms() * - * @param bool $op - * @param Permissible $permissible + * @return void */ public function subscribeToDefaultPerms(bool $op, Permissible $permissible){ PermissionManager::getInstance()->subscribeToDefaultPerms($op, $permissible); @@ -527,8 +495,7 @@ class PluginManager{ * @deprecated * @see PermissionManager::unsubscribeFromDefaultPerms() * - * @param bool $op - * @param Permissible $permissible + * @return void */ public function unsubscribeFromDefaultPerms(bool $op, Permissible $permissible){ PermissionManager::getInstance()->unsubscribeFromDefaultPerms($op, $permissible); @@ -538,8 +505,6 @@ class PluginManager{ * @deprecated * @see PermissionManager::getDefaultPermSubscriptions() * - * @param bool $op - * * @return Permissible[] */ public function getDefaultPermSubscriptions(bool $op) : array{ @@ -556,17 +521,12 @@ class PluginManager{ return PermissionManager::getInstance()->getPermissions(); } - /** - * @param Plugin $plugin - * - * @return bool - */ public function isPluginEnabled(Plugin $plugin) : bool{ return isset($this->plugins[$plugin->getDescription()->getName()]) and $plugin->isEnabled(); } /** - * @param Plugin $plugin + * @return void */ public function enablePlugin(Plugin $plugin){ if(!$plugin->isEnabled()){ @@ -591,8 +551,6 @@ class PluginManager{ } /** - * @param Plugin $plugin - * * @return PluginCommand[] */ protected function parseYamlCommands(Plugin $plugin) : array{ @@ -647,6 +605,9 @@ class PluginManager{ return $pluginCmds; } + /** + * @return void + */ public function disablePlugins(){ foreach($this->getPlugins() as $plugin){ $this->disablePlugin($plugin); @@ -654,7 +615,7 @@ class PluginManager{ } /** - * @param Plugin $plugin + * @return void */ public function disablePlugin(Plugin $plugin){ if($plugin->isEnabled()){ @@ -683,6 +644,9 @@ class PluginManager{ } } + /** + * @return void + */ public function clearPlugins(){ $this->disablePlugins(); $this->plugins = []; @@ -696,7 +660,7 @@ class PluginManager{ * @deprecated * @see Event::call() * - * @param Event $event + * @return void */ public function callEvent(Event $event){ $event->call(); @@ -705,9 +669,6 @@ class PluginManager{ /** * Registers all the events in the given Listener class * - * @param Listener $listener - * @param Plugin $plugin - * * @throws PluginException */ public function registerEvents(Listener $listener, Plugin $plugin) : void{ @@ -771,12 +732,8 @@ class PluginManager{ } /** - * @param string $event Class name that extends Event - * @param Listener $listener - * @param int $priority - * @param EventExecutor $executor - * @param Plugin $plugin - * @param bool $ignoreCancelled + * @param string $event Class name that extends Event + * @phpstan-param class-string $event * * @throws PluginException */ @@ -794,11 +751,6 @@ class PluginManager{ $this->getEventListeners($event)->register(new RegisteredListener($listener, $executor, $priority, $plugin, $ignoreCancelled, $timings)); } - /** - * @param string $event - * - * @return HandlerList - */ private function getEventListeners(string $event) : HandlerList{ $list = HandlerList::getHandlerListFor($event); if($list === null){ diff --git a/src/pocketmine/plugin/RegisteredListener.php b/src/pocketmine/plugin/RegisteredListener.php index 7db4cadea6..25c286bc1e 100644 --- a/src/pocketmine/plugin/RegisteredListener.php +++ b/src/pocketmine/plugin/RegisteredListener.php @@ -48,15 +48,6 @@ class RegisteredListener{ /** @var TimingsHandler */ private $timings; - - /** - * @param Listener $listener - * @param EventExecutor $executor - * @param int $priority - * @param Plugin $plugin - * @param bool $ignoreCancelled - * @param TimingsHandler $timings - */ public function __construct(Listener $listener, EventExecutor $executor, int $priority, Plugin $plugin, bool $ignoreCancelled, TimingsHandler $timings){ $this->listener = $listener; $this->priority = $priority; @@ -66,29 +57,20 @@ class RegisteredListener{ $this->timings = $timings; } - /** - * @return Listener - */ public function getListener() : Listener{ return $this->listener; } - /** - * @return Plugin - */ public function getPlugin() : Plugin{ return $this->plugin; } - /** - * @return int - */ public function getPriority() : int{ return $this->priority; } /** - * @param Event $event + * @return void */ public function callEvent(Event $event){ if($event instanceof Cancellable and $event->isCancelled() and $this->isIgnoringCancelled()){ @@ -103,9 +85,6 @@ class RegisteredListener{ $this->timings->remove(); } - /** - * @return bool - */ public function isIgnoringCancelled() : bool{ return $this->ignoreCancelled; } diff --git a/src/pocketmine/plugin/ScriptPluginLoader.php b/src/pocketmine/plugin/ScriptPluginLoader.php index b714c67b53..126f66de27 100644 --- a/src/pocketmine/plugin/ScriptPluginLoader.php +++ b/src/pocketmine/plugin/ScriptPluginLoader.php @@ -46,8 +46,6 @@ class ScriptPluginLoader implements PluginLoader{ /** * Loads the plugin contained in $file - * - * @param string $file */ public function loadPlugin(string $file) : void{ include_once $file; @@ -55,10 +53,6 @@ class ScriptPluginLoader implements PluginLoader{ /** * Gets the PluginDescription from the file - * - * @param string $file - * - * @return null|PluginDescription */ public function getPluginDescription(string $file) : ?PluginDescription{ $content = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); diff --git a/src/pocketmine/resourcepacks/ResourcePack.php b/src/pocketmine/resourcepacks/ResourcePack.php index c411c8fa6a..aee9cf2c2c 100644 --- a/src/pocketmine/resourcepacks/ResourcePack.php +++ b/src/pocketmine/resourcepacks/ResourcePack.php @@ -21,39 +21,32 @@ declare(strict_types=1); - namespace pocketmine\resourcepacks; - interface ResourcePack{ /** * Returns the path to the resource pack. This might be a file or a directory, depending on the type of pack. - * @return string */ public function getPath() : string; /** * Returns the human-readable name of the resource pack - * @return string */ public function getPackName() : string; /** * Returns the pack's UUID as a human-readable string - * @return string */ public function getPackId() : string; /** * Returns the size of the pack on disk in bytes. - * @return int */ public function getPackSize() : int; /** * Returns a version number for the pack in the format major.minor.patch - * @return string */ public function getPackVersion() : string; diff --git a/src/pocketmine/resourcepacks/ResourcePackInfoEntry.php b/src/pocketmine/resourcepacks/ResourcePackInfoEntry.php index 3b6e7a3e97..1da3b40b32 100644 --- a/src/pocketmine/resourcepacks/ResourcePackInfoEntry.php +++ b/src/pocketmine/resourcepacks/ResourcePackInfoEntry.php @@ -24,8 +24,11 @@ declare(strict_types=1); namespace pocketmine\resourcepacks; class ResourcePackInfoEntry{ + /** @var string */ protected $packId; //UUID + /** @var string */ protected $version; + /** @var int */ protected $packSize; public function __construct(string $packId, string $version, int $packSize = 0){ diff --git a/src/pocketmine/resourcepacks/ResourcePackManager.php b/src/pocketmine/resourcepacks/ResourcePackManager.php index f004df611f..aa21079d5f 100644 --- a/src/pocketmine/resourcepacks/ResourcePackManager.php +++ b/src/pocketmine/resourcepacks/ResourcePackManager.php @@ -21,7 +21,6 @@ declare(strict_types=1); - namespace pocketmine\resourcepacks; use pocketmine\utils\Config; @@ -52,7 +51,6 @@ class ResourcePackManager{ /** * @param string $path Path to resource-packs directory. - * @param \Logger $logger */ public function __construct(string $path, \Logger $logger){ $this->path = $path; @@ -122,7 +120,6 @@ class ResourcePackManager{ /** * Returns the directory which resource packs are loaded from. - * @return string */ public function getPath() : string{ return $this->path; @@ -130,7 +127,6 @@ class ResourcePackManager{ /** * Returns whether players must accept resource packs in order to join. - * @return bool */ public function resourcePacksRequired() : bool{ return $this->serverForceResources; @@ -147,8 +143,6 @@ class ResourcePackManager{ /** * Returns the resource pack matching the specified UUID string, or null if the ID was not recognized. * - * @param string $id - * * @return ResourcePack|null */ public function getPackById(string $id){ diff --git a/src/pocketmine/resourcepacks/ZippedResourcePack.php b/src/pocketmine/resourcepacks/ZippedResourcePack.php index 6a12ad12b0..3a4ba556a5 100644 --- a/src/pocketmine/resourcepacks/ZippedResourcePack.php +++ b/src/pocketmine/resourcepacks/ZippedResourcePack.php @@ -21,10 +21,8 @@ declare(strict_types=1); - namespace pocketmine\resourcepacks; - use Ahc\Json\Comment as CommentedJsonDecoder; use function count; use function fclose; @@ -43,10 +41,6 @@ class ZippedResourcePack implements ResourcePack{ /** * Performs basic validation checks on a resource pack's manifest.json. * TODO: add more manifest validation - * - * @param \stdClass $manifest - * - * @return bool */ public static function verifyManifest(\stdClass $manifest) : bool{ if(!isset($manifest->format_version) or !isset($manifest->header) or !isset($manifest->modules)){ @@ -68,7 +62,7 @@ class ZippedResourcePack implements ResourcePack{ /** @var \stdClass */ protected $manifest; - /** @var string */ + /** @var string|null */ protected $sha256 = null; /** @var resource */ diff --git a/src/pocketmine/scheduler/AsyncPool.php b/src/pocketmine/scheduler/AsyncPool.php index 069da62de3..fb3de98241 100644 --- a/src/pocketmine/scheduler/AsyncPool.php +++ b/src/pocketmine/scheduler/AsyncPool.php @@ -67,7 +67,10 @@ class AsyncPool{ /** @var int[] */ private $workerLastUsed = []; - /** @var \Closure[] */ + /** + * @var \Closure[] + * @phpstan-var (\Closure(int $workerId) : void)[] + */ private $workerStartHooks = []; public function __construct(Server $server, int $size, int $workerMemoryLimit, \ClassLoader $classLoader, \ThreadedLogger $logger){ @@ -80,8 +83,6 @@ class AsyncPool{ /** * Returns the maximum size of the pool. Note that there may be less active workers than this number. - * - * @return int */ public function getSize() : int{ return $this->size; @@ -89,8 +90,6 @@ class AsyncPool{ /** * Increases the maximum size of the pool to the specified amount. This does not immediately start new workers. - * - * @param int $newSize */ public function increaseSize(int $newSize) : void{ if($newSize > $this->size){ @@ -104,7 +103,7 @@ class AsyncPool{ * * This function will call the hook for every already-running worker. * - * @param \Closure $hook + * @phpstan-param \Closure(int $workerId) : void $hook */ public function addWorkerStartHook(\Closure $hook) : void{ Utils::validateCallableSignature(function(int $worker) : void{}, $hook); @@ -117,7 +116,7 @@ class AsyncPool{ /** * Removes a previously-registered callback listening for workers being started. * - * @param \Closure $hook + * @phpstan-param \Closure(int $workerId) : void $hook */ public function removeWorkerStartHook(\Closure $hook) : void{ unset($this->workerStartHooks[spl_object_hash($hook)]); @@ -135,10 +134,6 @@ class AsyncPool{ /** * Fetches the worker with the specified ID, starting it if it does not exist, and firing any registered worker * start hooks. - * - * @param int $worker - * - * @return AsyncWorker */ private function getWorker(int $worker) : AsyncWorker{ if(!isset($this->workers[$worker])){ @@ -157,9 +152,6 @@ class AsyncPool{ /** * Submits an AsyncTask to an arbitrary worker. - * - * @param AsyncTask $task - * @param int $worker */ public function submitTaskToWorker(AsyncTask $task, int $worker) : void{ if($worker < 0 or $worker >= $this->size){ @@ -186,8 +178,6 @@ class AsyncPool{ * - if an idle worker is found, it will be selected * - else, if the worker pool is not full, a new worker will be selected * - else, the worker with the smallest backlog is chosen. - * - * @return int */ public function selectWorker() : int{ $worker = null; @@ -218,10 +208,6 @@ class AsyncPool{ /** * Submits an AsyncTask to the worker with the least load. If all workers are busy and the pool is not full, a new * worker may be started. - * - * @param AsyncTask $task - * - * @return int */ public function submitTask(AsyncTask $task) : int{ if($task->getTaskId() !== null){ @@ -235,9 +221,6 @@ class AsyncPool{ /** * Removes a completed or crashed task from the pool. - * - * @param AsyncTask $task - * @param bool $force */ private function removeTask(AsyncTask $task, bool $force = false) : void{ if(isset($this->taskWorkers[$task->getTaskId()])){ diff --git a/src/pocketmine/scheduler/AsyncTask.php b/src/pocketmine/scheduler/AsyncTask.php index 0e3a4d9914..0b36831ff1 100644 --- a/src/pocketmine/scheduler/AsyncTask.php +++ b/src/pocketmine/scheduler/AsyncTask.php @@ -53,20 +53,27 @@ abstract class AsyncTask extends Collectable{ */ private static $threadLocalStorage; - /** @var AsyncWorker $worker */ + /** @var AsyncWorker|null $worker */ public $worker = null; /** @var \Threaded */ public $progressUpdates; + /** @var scalar|null */ private $result = null; + /** @var bool */ private $serialized = false; + /** @var bool */ private $cancelRun = false; /** @var int|null */ private $taskId = null; + /** @var bool */ private $crashed = false; + /** + * @return void + */ public function run(){ $this->result = null; @@ -93,6 +100,9 @@ abstract class AsyncTask extends Collectable{ return $this->serialized ? unserialize($this->result) : $this->result; } + /** + * @return void + */ public function cancelRun(){ $this->cancelRun = true; } @@ -101,20 +111,22 @@ abstract class AsyncTask extends Collectable{ return $this->cancelRun; } - /** - * @return bool - */ public function hasResult() : bool{ return $this->result !== null; } /** * @param mixed $result + * + * @return void */ public function setResult($result){ $this->result = ($this->serialized = !is_scalar($result)) ? serialize($result) : $result; } + /** + * @return void + */ public function setTaskId(int $taskId){ $this->taskId = $taskId; } @@ -130,8 +142,6 @@ abstract class AsyncTask extends Collectable{ * @deprecated * @see AsyncWorker::getFromThreadStore() * - * @param string $identifier - * * @return mixed */ public function getFromThreadStore(string $identifier){ @@ -145,8 +155,9 @@ abstract class AsyncTask extends Collectable{ * @deprecated * @see AsyncWorker::saveToThreadStore() * - * @param string $identifier * @param mixed $value + * + * @return void */ public function saveToThreadStore(string $identifier, $value){ if($this->worker === null or $this->isGarbage()){ @@ -158,8 +169,6 @@ abstract class AsyncTask extends Collectable{ /** * @deprecated * @see AsyncWorker::removeFromThreadStore() - * - * @param string $identifier */ public function removeFromThreadStore(string $identifier) : void{ if($this->worker === null or $this->isGarbage()){ @@ -179,8 +188,6 @@ abstract class AsyncTask extends Collectable{ * Actions to execute when completed (on main thread) * Implement this if you want to handle the data in your AsyncTask after it has been processed * - * @param Server $server - * * @return void */ public function onCompletion(Server $server){ @@ -192,6 +199,8 @@ abstract class AsyncTask extends Collectable{ * {@link AsyncTask::onProgressUpdate} from the main thread with the given progress parameter. * * @param mixed $progress A value that can be safely serialize()'ed. + * + * @return void */ public function publishProgress($progress){ $this->progressUpdates[] = serialize($progress); @@ -200,7 +209,7 @@ abstract class AsyncTask extends Collectable{ /** * @internal Only call from AsyncPool.php on the main thread * - * @param Server $server + * @return void */ public function checkProgressUpdates(Server $server){ while($this->progressUpdates->count() !== 0){ @@ -214,9 +223,10 @@ abstract class AsyncTask extends Collectable{ * All {@link AsyncTask::publishProgress} calls should result in {@link AsyncTask::onProgressUpdate} calls before * {@link AsyncTask::onCompletion} is called. * - * @param Server $server * @param mixed $progress The parameter passed to {@link AsyncTask::publishProgress}. It is serialize()'ed * and then unserialize()'ed, as if it has been cloned. + * + * @return void */ public function onProgressUpdate(Server $server, $progress){ @@ -233,6 +243,7 @@ abstract class AsyncTask extends Collectable{ * * @param mixed $complexData the data to store * + * @return void * @throws \BadMethodCallException if called from any thread except the main thread */ protected function storeLocal($complexData){ diff --git a/src/pocketmine/scheduler/AsyncWorker.php b/src/pocketmine/scheduler/AsyncWorker.php index c7026a46f6..16931ee04b 100644 --- a/src/pocketmine/scheduler/AsyncWorker.php +++ b/src/pocketmine/scheduler/AsyncWorker.php @@ -35,7 +35,9 @@ class AsyncWorker extends Worker{ /** @var mixed[] */ private static $store = []; + /** @var \ThreadedLogger */ private $logger; + /** @var int */ private $id; /** @var int */ @@ -47,6 +49,9 @@ class AsyncWorker extends Worker{ $this->memoryLimit = $memoryLimit; } + /** + * @return void + */ public function run(){ error_reporting(-1); @@ -74,6 +79,9 @@ class AsyncWorker extends Worker{ return $this->logger; } + /** + * @return void + */ public function handleException(\Throwable $e){ $this->logger->logException($e); } @@ -90,7 +98,6 @@ class AsyncWorker extends Worker{ * Saves mixed data into the worker's thread-local object store. This can be used to store objects which you * want to use on this worker thread from multiple AsyncTasks. * - * @param string $identifier * @param mixed $value */ public function saveToThreadStore(string $identifier, $value) : void{ @@ -105,8 +112,6 @@ class AsyncWorker extends Worker{ * * Objects stored in this storage may ONLY be retrieved while the task is running. * - * @param string $identifier - * * @return mixed */ public function getFromThreadStore(string $identifier){ @@ -115,8 +120,6 @@ class AsyncWorker extends Worker{ /** * Removes previously-stored mixed data from the worker's thread-local object store. - * - * @param string $identifier */ public function removeFromThreadStore(string $identifier) : void{ unset(self::$store[$identifier]); diff --git a/src/pocketmine/scheduler/BulkCurlTask.php b/src/pocketmine/scheduler/BulkCurlTask.php index 56fc3aa5bc..0b1fb12e93 100644 --- a/src/pocketmine/scheduler/BulkCurlTask.php +++ b/src/pocketmine/scheduler/BulkCurlTask.php @@ -34,6 +34,7 @@ use function unserialize; * The result of this AsyncTask is an array of arrays (returned from {@link Internet::simpleCurl}) or InternetException objects. */ class BulkCurlTask extends AsyncTask{ + /** @var string */ private $operations; /** @@ -43,8 +44,9 @@ class BulkCurlTask extends AsyncTask{ * "timeout", "extraHeaders" and "extraOpts". Documentation of these options are same as those in * {@link Utils::simpleCurl}. * - * @param array $operations + * @param mixed[][] $operations * @param mixed|null $complexData + * @phpstan-param list, extraOpts?: array}> $operations */ public function __construct(array $operations, $complexData = null){ $this->storeLocal($complexData); @@ -52,6 +54,7 @@ class BulkCurlTask extends AsyncTask{ } public function onRun(){ + /** @phpstan-var list, extraOpts?: array}> $operations */ $operations = unserialize($this->operations); $results = []; foreach($operations as $op){ diff --git a/src/pocketmine/scheduler/ClosureTask.php b/src/pocketmine/scheduler/ClosureTask.php index 84d44d2a2f..57f560e77d 100644 --- a/src/pocketmine/scheduler/ClosureTask.php +++ b/src/pocketmine/scheduler/ClosureTask.php @@ -38,11 +38,15 @@ use pocketmine\utils\Utils; */ class ClosureTask extends Task{ - /** @var \Closure */ + /** + * @var \Closure + * @phpstan-var \Closure(int) : void + */ private $closure; /** * @param \Closure $closure Must accept only ONE parameter, $currentTick + * @phpstan-param \Closure(int) : void $closure */ public function __construct(\Closure $closure){ Utils::validateCallableSignature(function(int $currentTick){}, $closure); diff --git a/src/pocketmine/scheduler/DumpWorkerMemoryTask.php b/src/pocketmine/scheduler/DumpWorkerMemoryTask.php index 0e47030ce3..e45d421d2c 100644 --- a/src/pocketmine/scheduler/DumpWorkerMemoryTask.php +++ b/src/pocketmine/scheduler/DumpWorkerMemoryTask.php @@ -37,11 +37,6 @@ class DumpWorkerMemoryTask extends AsyncTask{ /** @var int */ private $maxStringSize; - /** - * @param string $outputFolder - * @param int $maxNesting - * @param int $maxStringSize - */ public function __construct(string $outputFolder, int $maxNesting, int $maxStringSize){ $this->outputFolder = $outputFolder; $this->maxNesting = $maxNesting; diff --git a/src/pocketmine/scheduler/FileWriteTask.php b/src/pocketmine/scheduler/FileWriteTask.php index 0247280e0a..c20819fce7 100644 --- a/src/pocketmine/scheduler/FileWriteTask.php +++ b/src/pocketmine/scheduler/FileWriteTask.php @@ -35,9 +35,7 @@ class FileWriteTask extends AsyncTask{ private $flags; /** - * @param string $path * @param mixed $contents - * @param int $flags */ public function __construct(string $path, $contents, int $flags = 0){ $this->path = $path; diff --git a/src/pocketmine/scheduler/SendUsageTask.php b/src/pocketmine/scheduler/SendUsageTask.php index a566364a9c..a92c0eb7f5 100644 --- a/src/pocketmine/scheduler/SendUsageTask.php +++ b/src/pocketmine/scheduler/SendUsageTask.php @@ -45,13 +45,14 @@ class SendUsageTask extends AsyncTask{ public const TYPE_STATUS = 2; public const TYPE_CLOSE = 3; + /** @var string */ public $endpoint; + /** @var string */ public $data; /** - * @param Server $server - * @param int $type - * @param array $playerList + * @param string[] $playerList + * @phpstan-param array $playerList */ public function __construct(Server $server, int $type, array $playerList = []){ $endpoint = "http://" . $server->getProperty("anonymous-statistics.host", "stats.pocketmine.net") . "/"; @@ -116,7 +117,6 @@ class SendUsageTask extends AsyncTask{ "ticks" => $server->getTick() ]; - //This anonymizes the user ids so they cannot be reversed to the original foreach($playerList as $k => $v){ $playerList[$k] = md5($v); diff --git a/src/pocketmine/scheduler/Task.php b/src/pocketmine/scheduler/Task.php index f2ad1d862d..3cdbe01158 100644 --- a/src/pocketmine/scheduler/Task.php +++ b/src/pocketmine/scheduler/Task.php @@ -37,9 +37,6 @@ abstract class Task{ return $this->taskHandler; } - /** - * @return int - */ final public function getTaskId() : int{ if($this->taskHandler !== null){ return $this->taskHandler->getTaskId(); @@ -53,7 +50,7 @@ abstract class Task{ } /** - * @param TaskHandler|null $taskHandler + * @return void */ final public function setHandler(TaskHandler $taskHandler = null){ if($this->taskHandler === null or $taskHandler === null){ @@ -64,14 +61,14 @@ abstract class Task{ /** * Actions to execute when run * - * @param int $currentTick - * * @return void */ abstract public function onRun(int $currentTick); /** * Actions to execute if the Task is cancelled + * + * @return void */ public function onCancel(){ diff --git a/src/pocketmine/scheduler/TaskHandler.php b/src/pocketmine/scheduler/TaskHandler.php index e2188af1e5..ddecf16eb2 100644 --- a/src/pocketmine/scheduler/TaskHandler.php +++ b/src/pocketmine/scheduler/TaskHandler.php @@ -54,13 +54,6 @@ class TaskHandler{ /** @var string */ private $ownerName; - /** - * @param Task $task - * @param int $taskId - * @param int $delay - * @param int $period - * @param string|null $ownerName - */ public function __construct(Task $task, int $taskId, int $delay = -1, int $period = -1, ?string $ownerName = null){ $this->task = $task; $this->taskId = $taskId; @@ -72,69 +65,48 @@ class TaskHandler{ $this->task->setHandler($this); } - /** - * @return bool - */ public function isCancelled() : bool{ return $this->cancelled; } - /** - * @return int - */ public function getNextRun() : int{ return $this->nextRun; } /** - * @param int $ticks + * @return void */ public function setNextRun(int $ticks){ $this->nextRun = $ticks; } - /** - * @return int - */ public function getTaskId() : int{ return $this->taskId; } - /** - * @return Task - */ public function getTask() : Task{ return $this->task; } - /** - * @return int - */ public function getDelay() : int{ return $this->delay; } - /** - * @return bool - */ public function isDelayed() : bool{ return $this->delay > 0; } - /** - * @return bool - */ public function isRepeating() : bool{ return $this->period > 0; } - /** - * @return int - */ public function getPeriod() : int{ return $this->period; } + /** + * @return void + */ public function cancel(){ try{ if(!$this->isCancelled()){ @@ -145,13 +117,16 @@ class TaskHandler{ } } + /** + * @return void + */ public function remove(){ $this->cancelled = true; $this->task->setHandler(null); } /** - * @param int $currentTick + * @return void */ public function run(int $currentTick){ $this->timings->startTiming(); @@ -162,9 +137,6 @@ class TaskHandler{ } } - /** - * @return string - */ public function getTaskName() : string{ return $this->taskName; } diff --git a/src/pocketmine/scheduler/TaskScheduler.php b/src/pocketmine/scheduler/TaskScheduler.php index c8581d6788..60e4b1b605 100644 --- a/src/pocketmine/scheduler/TaskScheduler.php +++ b/src/pocketmine/scheduler/TaskScheduler.php @@ -36,14 +36,10 @@ class TaskScheduler{ /** @var bool */ private $enabled = true; - /** - * @var ReversePriorityQueue - */ + /** @var ReversePriorityQueue */ protected $queue; - /** - * @var TaskHandler[] - */ + /** @var TaskHandler[] */ protected $tasks = []; /** @var int */ @@ -54,7 +50,6 @@ class TaskScheduler{ /** * @param \Logger $logger @deprecated - * @param null|string $owner */ public function __construct(\Logger $logger, ?string $owner = null){ $this->owner = $owner; @@ -62,8 +57,6 @@ class TaskScheduler{ } /** - * @param Task $task - * * @return TaskHandler */ public function scheduleTask(Task $task){ @@ -71,9 +64,6 @@ class TaskScheduler{ } /** - * @param Task $task - * @param int $delay - * * @return TaskHandler */ public function scheduleDelayedTask(Task $task, int $delay){ @@ -81,9 +71,6 @@ class TaskScheduler{ } /** - * @param Task $task - * @param int $period - * * @return TaskHandler */ public function scheduleRepeatingTask(Task $task, int $period){ @@ -91,10 +78,6 @@ class TaskScheduler{ } /** - * @param Task $task - * @param int $delay - * @param int $period - * * @return TaskHandler */ public function scheduleDelayedRepeatingTask(Task $task, int $delay, int $period){ @@ -102,7 +85,7 @@ class TaskScheduler{ } /** - * @param int $taskId + * @return void */ public function cancelTask(int $taskId){ if(isset($this->tasks[$taskId])){ @@ -114,6 +97,9 @@ class TaskScheduler{ } } + /** + * @return void + */ public function cancelAllTasks(){ foreach($this->tasks as $id => $task){ $this->cancelTask($id); @@ -125,20 +111,11 @@ class TaskScheduler{ $this->ids = 1; } - /** - * @param int $taskId - * - * @return bool - */ public function isQueued(int $taskId) : bool{ return isset($this->tasks[$taskId]); } /** - * @param Task $task - * @param int $delay - * @param int $period - * * @return TaskHandler * * @throws \InvalidStateException @@ -185,7 +162,7 @@ class TaskScheduler{ } /** - * @param int $currentTick + * @return void */ public function mainThreadHeartbeat(int $currentTick){ $this->currentTick = $currentTick; @@ -211,9 +188,6 @@ class TaskScheduler{ return !$this->queue->isEmpty() and $this->queue->current()->getNextRun() <= $currentTick; } - /** - * @return int - */ private function nextId() : int{ return $this->ids++; } diff --git a/src/pocketmine/tile/Banner.php b/src/pocketmine/tile/Banner.php index 1330d1ea18..2037b2ce0a 100644 --- a/src/pocketmine/tile/Banner.php +++ b/src/pocketmine/tile/Banner.php @@ -127,8 +127,6 @@ class Banner extends Spawnable implements Nameable{ /** * Returns the color of the banner base. - * - * @return int */ public function getBaseColor() : int{ return $this->baseColor; @@ -136,8 +134,6 @@ class Banner extends Spawnable implements Nameable{ /** * Sets the color of the banner base. - * - * @param int $color */ public function setBaseColor(int $color) : void{ $this->baseColor = $color; @@ -147,9 +143,6 @@ class Banner extends Spawnable implements Nameable{ /** * Applies a new pattern on the banner with the given color. * - * @param string $pattern - * @param int $color - * * @return int ID of pattern. */ public function addPattern(string $pattern, int $color) : int{ @@ -164,10 +157,6 @@ class Banner extends Spawnable implements Nameable{ /** * Returns whether a pattern with the given ID exists on the banner or not. - * - * @param int $patternId - * - * @return bool */ public function patternExists(int $patternId) : bool{ return $this->patterns->isset($patternId); @@ -176,9 +165,8 @@ class Banner extends Spawnable implements Nameable{ /** * Returns the data of a pattern with the given ID. * - * @param int $patternId - * - * @return array + * @return mixed[] + * @phpstan-return array{Color?: int, Pattern?: string} */ public function getPatternData(int $patternId) : array{ if(!$this->patternExists($patternId)){ @@ -197,10 +185,6 @@ class Banner extends Spawnable implements Nameable{ /** * Changes the pattern of a previously existing pattern. * - * @param int $patternId - * @param string $pattern - * @param int $color - * * @return bool indicating success. */ public function changePattern(int $patternId, string $pattern, int $color) : bool{ @@ -220,8 +204,6 @@ class Banner extends Spawnable implements Nameable{ /** * Deletes a pattern from the banner with the given ID. * - * @param int $patternId - * * @return bool indicating whether the pattern existed or not. */ public function deletePattern(int $patternId) : bool{ @@ -255,16 +237,11 @@ class Banner extends Spawnable implements Nameable{ /** * Returns the total count of patterns on this banner. - * - * @return int */ public function getPatternCount() : int{ return $this->patterns->count(); } - /** - * @return ListTag - */ public function getPatterns() : ListTag{ return $this->patterns; } diff --git a/src/pocketmine/tile/Bed.php b/src/pocketmine/tile/Bed.php index b53c3de271..e70784892d 100644 --- a/src/pocketmine/tile/Bed.php +++ b/src/pocketmine/tile/Bed.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\tile; - use pocketmine\item\Item; use pocketmine\math\Vector3; use pocketmine\nbt\tag\CompoundTag; @@ -38,6 +37,9 @@ class Bed extends Spawnable{ return $this->color; } + /** + * @return void + */ public function setColor(int $color){ $this->color = $color & 0xf; $this->onChanged(); diff --git a/src/pocketmine/tile/Chest.php b/src/pocketmine/tile/Chest.php index f8e57ea19a..8066d69d9f 100644 --- a/src/pocketmine/tile/Chest.php +++ b/src/pocketmine/tile/Chest.php @@ -117,6 +117,9 @@ class Chest extends Spawnable implements InventoryHolder, Container, Nameable{ return $this->inventory; } + /** + * @return void + */ protected function checkPairing(){ if($this->isPaired() and !$this->getLevel()->isInLoadedTerrain(new Vector3($this->pairX, $this->y, $this->pairZ))){ //paired to a tile in an unloaded chunk @@ -144,20 +147,17 @@ class Chest extends Spawnable implements InventoryHolder, Container, Nameable{ } } - /** - * @return string - */ public function getDefaultName() : string{ return "Chest"; } + /** + * @return bool + */ public function isPaired(){ return $this->pairX !== null and $this->pairZ !== null; } - /** - * @return Chest|null - */ public function getPair() : ?Chest{ if($this->isPaired()){ $tile = $this->getLevel()->getTileAt($this->pairX, $this->y, $this->pairZ); @@ -169,6 +169,9 @@ class Chest extends Spawnable implements InventoryHolder, Container, Nameable{ return null; } + /** + * @return bool + */ public function pairWith(Chest $tile){ if($this->isPaired() or $tile->isPaired()){ return false; @@ -183,7 +186,7 @@ class Chest extends Spawnable implements InventoryHolder, Container, Nameable{ return true; } - private function createPair(Chest $tile){ + private function createPair(Chest $tile) : void{ $this->pairX = $tile->x; $this->pairZ = $tile->z; @@ -191,6 +194,9 @@ class Chest extends Spawnable implements InventoryHolder, Container, Nameable{ $tile->pairZ = $this->z; } + /** + * @return bool + */ public function unpair(){ if(!$this->isPaired()){ return false; diff --git a/src/pocketmine/tile/Container.php b/src/pocketmine/tile/Container.php index 1e98dc5a12..7fc9949b63 100644 --- a/src/pocketmine/tile/Container.php +++ b/src/pocketmine/tile/Container.php @@ -41,10 +41,6 @@ interface Container{ /** * Returns whether this container can be opened by an item with the given custom name. - * - * @param string $key - * - * @return bool */ public function canOpenWith(string $key) : bool; } diff --git a/src/pocketmine/tile/ContainerTrait.php b/src/pocketmine/tile/ContainerTrait.php index 3300924605..ecfc5d0895 100644 --- a/src/pocketmine/tile/ContainerTrait.php +++ b/src/pocketmine/tile/ContainerTrait.php @@ -73,10 +73,6 @@ trait ContainerTrait{ /** * @see Container::canOpenWith() - * - * @param string $key - * - * @return bool */ public function canOpenWith(string $key) : bool{ return $this->lock === null or $this->lock === $key; diff --git a/src/pocketmine/tile/EnchantTable.php b/src/pocketmine/tile/EnchantTable.php index e2618a8ff8..204d9bd6af 100644 --- a/src/pocketmine/tile/EnchantTable.php +++ b/src/pocketmine/tile/EnchantTable.php @@ -29,9 +29,6 @@ class EnchantTable extends Spawnable implements Nameable{ saveName as writeSaveData; } - /** - * @return string - */ public function getDefaultName() : string{ return "Enchanting Table"; } diff --git a/src/pocketmine/tile/FlowerPot.php b/src/pocketmine/tile/FlowerPot.php index 7b69d69afd..1070d0d70d 100644 --- a/src/pocketmine/tile/FlowerPot.php +++ b/src/pocketmine/tile/FlowerPot.php @@ -70,11 +70,17 @@ class FlowerPot extends Spawnable{ return clone $this->item; } + /** + * @return void + */ public function setItem(Item $item){ $this->item = clone $item; $this->onChanged(); } + /** + * @return void + */ public function removeItem(){ $this->setItem(ItemFactory::get(Item::AIR, 0, 0)); } diff --git a/src/pocketmine/tile/Furnace.php b/src/pocketmine/tile/Furnace.php index d729b2b58f..984141c7a9 100644 --- a/src/pocketmine/tile/Furnace.php +++ b/src/pocketmine/tile/Furnace.php @@ -38,6 +38,7 @@ use pocketmine\level\Level; use pocketmine\nbt\tag\CompoundTag; use pocketmine\network\mcpe\protocol\ContainerSetDataPacket; use function ceil; +use function count; use function max; class Furnace extends Spawnable implements InventoryHolder, Container, Nameable{ @@ -107,9 +108,6 @@ class Furnace extends Spawnable implements InventoryHolder, Container, Nameable{ $this->saveItems($nbt); } - /** - * @return string - */ public function getDefaultName() : string{ return "Furnace"; } @@ -137,6 +135,9 @@ class Furnace extends Spawnable implements InventoryHolder, Container, Nameable{ return $this->getInventory(); } + /** + * @return void + */ protected function checkFuel(Item $fuel){ $ev = new FurnaceBurnEvent($this, $fuel, $fuel->getFuelTime()); $ev->call(); @@ -232,7 +233,7 @@ class Furnace extends Spawnable implements InventoryHolder, Container, Nameable{ $packets[] = $pk; } - if(!empty($packets)){ + if(count($packets) > 0){ foreach($this->getInventory()->getViewers() as $player){ $windowId = $player->getWindowId($this->getInventory()); if($windowId > 0){ diff --git a/src/pocketmine/tile/ItemFrame.php b/src/pocketmine/tile/ItemFrame.php index 4b573395fb..faafe1dd29 100644 --- a/src/pocketmine/tile/ItemFrame.php +++ b/src/pocketmine/tile/ItemFrame.php @@ -63,6 +63,9 @@ class ItemFrame extends Spawnable{ return clone $this->item; } + /** + * @return void + */ public function setItem(Item $item = null){ if($item !== null and !$item->isNull()){ $this->item = clone $item; @@ -76,6 +79,9 @@ class ItemFrame extends Spawnable{ return $this->itemRotation; } + /** + * @return void + */ public function setItemRotation(int $rotation){ $this->itemRotation = $rotation; $this->onChanged(); @@ -85,6 +91,9 @@ class ItemFrame extends Spawnable{ return $this->itemDropChance; } + /** + * @return void + */ public function setItemDropChance(float $chance){ $this->itemDropChance = $chance; $this->onChanged(); diff --git a/src/pocketmine/tile/Nameable.php b/src/pocketmine/tile/Nameable.php index ab66b101c3..aedb7c699b 100644 --- a/src/pocketmine/tile/Nameable.php +++ b/src/pocketmine/tile/Nameable.php @@ -26,23 +26,14 @@ namespace pocketmine\tile; interface Nameable{ public const TAG_CUSTOM_NAME = "CustomName"; - /** - * @return string - */ public function getDefaultName() : string; - /** - * @return string - */ public function getName() : string; /** - * @param string $str + * @return void */ public function setName(string $str); - /** - * @return bool - */ public function hasName() : bool; } diff --git a/src/pocketmine/tile/NameableTrait.php b/src/pocketmine/tile/NameableTrait.php index d1a62593c1..acd2454a4f 100644 --- a/src/pocketmine/tile/NameableTrait.php +++ b/src/pocketmine/tile/NameableTrait.php @@ -36,21 +36,12 @@ trait NameableTrait{ /** @var string|null */ private $customName; - /** - * @return string - */ abstract public function getDefaultName() : string; - /** - * @return string - */ public function getName() : string{ return $this->customName ?? $this->getDefaultName(); } - /** - * @param string $name - */ public function setName(string $name) : void{ if($name === ""){ $this->customName = null; @@ -59,9 +50,6 @@ trait NameableTrait{ } } - /** - * @return bool - */ public function hasName() : bool{ return $this->customName !== null; } diff --git a/src/pocketmine/tile/Sign.php b/src/pocketmine/tile/Sign.php index 5cf3fd8da9..edfcf37358 100644 --- a/src/pocketmine/tile/Sign.php +++ b/src/pocketmine/tile/Sign.php @@ -42,6 +42,9 @@ class Sign extends Spawnable{ public const TAG_TEXT_BLOB = "Text"; public const TAG_TEXT_LINE = "Text%d"; //sprintf()able + /** + * @return string[] + */ private static function fixTextBlob(string $blob) : array{ return array_slice(array_pad(explode("\n", $blob), 4, ""), 0, 4); } @@ -77,11 +80,6 @@ class Sign extends Spawnable{ /** * Changes contents of the specific lines to the string provided. * Leaves contents of the specific lines as is if null is provided. - * - * @param null|string $line1 - * @param null|string $line2 - * @param null|string $line3 - * @param null|string $line4 */ public function setText(?string $line1 = "", ?string $line2 = "", ?string $line3 = "", ?string $line4 = "") : void{ if($line1 !== null){ @@ -102,8 +100,6 @@ class Sign extends Spawnable{ /** * @param int $index 0-3 - * @param string $line - * @param bool $update */ public function setLine(int $index, string $line, bool $update = true) : void{ if($index < 0 or $index > 3){ @@ -121,8 +117,6 @@ class Sign extends Spawnable{ /** * @param int $index 0-3 - * - * @return string */ public function getLine(int $index) : string{ if($index < 0 or $index > 3){ @@ -163,7 +157,7 @@ class Sign extends Spawnable{ $removeFormat = $player->getRemoveFormat(); - $ev = new SignChangeEvent($this->getBlock(), $player, array_map(function(string $line) use ($removeFormat){ return TextFormat::clean($line, $removeFormat); }, $lines)); + $ev = new SignChangeEvent($this->getBlock(), $player, array_map(function(string $line) use ($removeFormat) : string{ return TextFormat::clean($line, $removeFormat); }, $lines)); $ev->call(); if(!$ev->isCancelled()){ diff --git a/src/pocketmine/tile/Skull.php b/src/pocketmine/tile/Skull.php index 2e7210284d..0568c8373c 100644 --- a/src/pocketmine/tile/Skull.php +++ b/src/pocketmine/tile/Skull.php @@ -57,6 +57,9 @@ class Skull extends Spawnable{ $nbt->setByte(self::TAG_ROT, $this->skullRotation); } + /** + * @return void + */ public function setType(int $type){ $this->skullType = $type; $this->onChanged(); diff --git a/src/pocketmine/tile/Spawnable.php b/src/pocketmine/tile/Spawnable.php index bcad010b54..6d416650a6 100644 --- a/src/pocketmine/tile/Spawnable.php +++ b/src/pocketmine/tile/Spawnable.php @@ -62,6 +62,9 @@ abstract class Spawnable extends Tile{ $this->spawnToAll(); } + /** + * @return void + */ public function spawnToAll(){ if($this->closed){ return; @@ -99,9 +102,6 @@ abstract class Spawnable extends Tile{ return $this->spawnCompoundCache; } - /** - * @return CompoundTag - */ final public function getSpawnCompound() : CompoundTag{ $nbt = new CompoundTag("", [ new StringTag(self::TAG_ID, static::getSaveId()), @@ -116,8 +116,6 @@ abstract class Spawnable extends Tile{ /** * An extension to getSpawnCompound() for * further modifying the generic tile NBT. - * - * @param CompoundTag $nbt */ abstract protected function addAdditionalSpawnData(CompoundTag $nbt) : void; @@ -125,9 +123,6 @@ abstract class Spawnable extends Tile{ * Called when a player updates a block entity's NBT data * for example when writing on a sign. * - * @param CompoundTag $nbt - * @param Player $player - * * @return bool indication of success, will respawn the tile to the player if false. */ public function updateCompoundTag(CompoundTag $nbt, Player $player) : bool{ diff --git a/src/pocketmine/tile/Tile.php b/src/pocketmine/tile/Tile.php index 5dcb70a0ae..ac044a8406 100644 --- a/src/pocketmine/tile/Tile.php +++ b/src/pocketmine/tile/Tile.php @@ -68,9 +68,15 @@ abstract class Tile extends Position{ /** @var int */ public static $tileCount = 1; - /** @var string[] classes that extend Tile */ + /** + * @var string[] classes that extend Tile + * @phpstan-var array> + */ private static $knownTiles = []; - /** @var string[][] */ + /** + * @var string[][] + * @phpstan-var array, list> + */ private static $saveNames = []; /** @var string */ @@ -84,6 +90,9 @@ abstract class Tile extends Position{ /** @var TimingsHandler */ protected $timings; + /** + * @return void + */ public static function init(){ self::registerTile(Banner::class, [self::BANNER, "minecraft:banner"]); self::registerTile(Bed::class, [self::BED, "minecraft:bed"]); @@ -99,11 +108,7 @@ abstract class Tile extends Position{ /** * @param string $type - * @param Level $level - * @param CompoundTag $nbt * @param mixed ...$args - * - * @return Tile|null */ public static function createTile($type, Level $level, CompoundTag $nbt, ...$args) : ?Tile{ if(isset(self::$knownTiles[$type])){ @@ -116,10 +121,9 @@ abstract class Tile extends Position{ } /** - * @param string $className - * @param array $saveNames + * @param string[] $saveNames + * @phpstan-param class-string $className * - * @return bool * @throws \ReflectionException */ public static function registerTile(string $className, array $saveNames = []) : bool{ @@ -136,7 +140,6 @@ abstract class Tile extends Position{ self::$saveNames[$className] = $saveNames; - return true; } @@ -145,7 +148,6 @@ abstract class Tile extends Position{ /** * Returns the short save name - * @return string */ public static function getSaveId() : string{ if(!isset(self::$saveNames[static::class])){ @@ -175,15 +177,11 @@ abstract class Tile extends Position{ /** * Reads additional data from the CompoundTag on tile creation. - * - * @param CompoundTag $nbt */ abstract protected function readSaveData(CompoundTag $nbt) : void; /** * Writes additional save data to a CompoundTag, not including generic things like ID and coordinates. - * - * @param CompoundTag $nbt */ abstract protected function writeSaveData(CompoundTag $nbt) : void; @@ -205,13 +203,6 @@ abstract class Tile extends Position{ /** * Creates and returns a CompoundTag containing the necessary information to spawn a tile of this type. - * - * @param Vector3 $pos - * @param int|null $face - * @param Item|null $item - * @param Player|null $player - * - * @return CompoundTag */ public static function createNBT(Vector3 $pos, ?int $face = null, ?Item $item = null, ?Player $player = null) : CompoundTag{ if(static::class === self::class){ @@ -240,27 +231,15 @@ abstract class Tile extends Position{ /** * Called by createNBT() to allow descendent classes to add their own base NBT using the parameters provided. - * - * @param CompoundTag $nbt - * @param Vector3 $pos - * @param int|null $face - * @param Item|null $item - * @param Player|null $player */ protected static function createAdditionalNBT(CompoundTag $nbt, Vector3 $pos, ?int $face = null, ?Item $item = null, ?Player $player = null) : void{ } - /** - * @return Block - */ public function getBlock() : Block{ return $this->level->getBlockAt($this->x, $this->y, $this->z); } - /** - * @return bool - */ public function onUpdate() : bool{ return false; } diff --git a/src/pocketmine/timings/Timings.php b/src/pocketmine/timings/Timings.php index 5192728f50..ce046a9dd3 100644 --- a/src/pocketmine/timings/Timings.php +++ b/src/pocketmine/timings/Timings.php @@ -105,6 +105,9 @@ abstract class Timings{ /** @var TimingsHandler[] */ public static $pluginTaskTimingMap = []; + /** + * @return void + */ public static function init(){ if(self::$initialized){ return; @@ -145,12 +148,6 @@ abstract class Timings{ } - /** - * @param TaskHandler $task - * @param int $period - * - * @return TimingsHandler - */ public static function getScheduledTaskTimings(TaskHandler $task, int $period) : TimingsHandler{ $name = "Task: " . ($task->getOwnerName() ?? "Unknown") . " Runnable: " . $task->getTaskName(); @@ -167,11 +164,6 @@ abstract class Timings{ return self::$pluginTaskTimingMap[$name]; } - /** - * @param Entity $entity - * - * @return TimingsHandler - */ public static function getEntityTimings(Entity $entity) : TimingsHandler{ $entityType = (new \ReflectionClass($entity))->getShortName(); if(!isset(self::$entityTypeTimingMap[$entityType])){ @@ -185,11 +177,6 @@ abstract class Timings{ return self::$entityTypeTimingMap[$entityType]; } - /** - * @param Tile $tile - * - * @return TimingsHandler - */ public static function getTileEntityTimings(Tile $tile) : TimingsHandler{ $tileType = (new \ReflectionClass($tile))->getShortName(); if(!isset(self::$tileEntityTypeTimingMap[$tileType])){ @@ -199,11 +186,6 @@ abstract class Timings{ return self::$tileEntityTypeTimingMap[$tileType]; } - /** - * @param DataPacket $pk - * - * @return TimingsHandler - */ public static function getReceiveDataPacketTimings(DataPacket $pk) : TimingsHandler{ if(!isset(self::$packetReceiveTimingMap[$pk::NETWORK_ID])){ $pkName = (new \ReflectionClass($pk))->getShortName(); @@ -213,12 +195,6 @@ abstract class Timings{ return self::$packetReceiveTimingMap[$pk::NETWORK_ID]; } - - /** - * @param DataPacket $pk - * - * @return TimingsHandler - */ public static function getSendDataPacketTimings(DataPacket $pk) : TimingsHandler{ if(!isset(self::$packetSendTimingMap[$pk::NETWORK_ID])){ $pkName = (new \ReflectionClass($pk))->getShortName(); diff --git a/src/pocketmine/timings/TimingsHandler.php b/src/pocketmine/timings/TimingsHandler.php index 87a6100c55..5538c070f8 100644 --- a/src/pocketmine/timings/TimingsHandler.php +++ b/src/pocketmine/timings/TimingsHandler.php @@ -43,6 +43,8 @@ class TimingsHandler{ /** * @param resource $fp + * + * @return void */ public static function printTimings($fp){ fwrite($fp, "Minecraft" . PHP_EOL); @@ -93,6 +95,9 @@ class TimingsHandler{ return self::$timingStart; } + /** + * @return void + */ public static function reload(){ if(self::$enabled){ foreach(self::$HANDLERS as $timings){ @@ -102,6 +107,9 @@ class TimingsHandler{ } } + /** + * @return void + */ public static function tick(bool $measure = true){ if(self::$enabled){ if($measure){ @@ -128,7 +136,7 @@ class TimingsHandler{ /** @var string */ private $name; - /** @var TimingsHandler */ + /** @var TimingsHandler|null */ private $parent = null; /** @var int */ @@ -146,10 +154,6 @@ class TimingsHandler{ /** @var int */ private $violations = 0; - /** - * @param string $name - * @param TimingsHandler $parent - */ public function __construct(string $name, TimingsHandler $parent = null){ $this->name = $name; $this->parent = $parent; @@ -157,33 +161,58 @@ class TimingsHandler{ self::$HANDLERS[spl_object_hash($this)] = $this; } + /** + * @return void + */ public function startTiming(){ - if(self::$enabled and ++$this->timingDepth === 1){ - $this->start = microtime(true); - if($this->parent !== null and ++$this->parent->timingDepth === 1){ - $this->parent->start = $this->start; + if(self::$enabled){ + $this->internalStartTiming(microtime(true)); + } + } + + private function internalStartTiming(float $now) : void{ + if(++$this->timingDepth === 1){ + $this->start = $now; + if($this->parent !== null){ + $this->parent->internalStartTiming($now); } } } + /** + * @return void + */ public function stopTiming(){ if(self::$enabled){ - if(--$this->timingDepth !== 0 or $this->start == 0){ - return; - } - - $diff = microtime(true) - $this->start; - $this->totalTime += $diff; - $this->curTickTotal += $diff; - ++$this->curCount; - ++$this->count; - $this->start = 0; - if($this->parent !== null){ - $this->parent->stopTiming(); - } + $this->internalStopTiming(microtime(true)); } } + private function internalStopTiming(float $now) : void{ + if($this->timingDepth === 0){ + //TODO: it would be nice to bail here, but since we'd have to track timing depth across resets + //and enable/disable, it would have a performance impact. Therefore, considering the limited + //usefulness of bailing here anyway, we don't currently bother. + return; + } + if(--$this->timingDepth !== 0 or $this->start == 0){ + return; + } + + $diff = $now - $this->start; + $this->totalTime += $diff; + $this->curTickTotal += $diff; + ++$this->curCount; + ++$this->count; + $this->start = 0; + if($this->parent !== null){ + $this->parent->internalStopTiming($now); + } + } + + /** + * @return void + */ public function reset(){ $this->count = 0; $this->curCount = 0; @@ -194,6 +223,9 @@ class TimingsHandler{ $this->timingDepth = 0; } + /** + * @return void + */ public function remove(){ unset(self::$HANDLERS[spl_object_hash($this)]); } diff --git a/src/pocketmine/updater/AutoUpdater.php b/src/pocketmine/updater/AutoUpdater.php index d2efe12906..e0d35adccd 100644 --- a/src/pocketmine/updater/AutoUpdater.php +++ b/src/pocketmine/updater/AutoUpdater.php @@ -41,20 +41,19 @@ class AutoUpdater{ protected $server; /** @var string */ protected $endpoint; - /** @var array|null */ + /** + * @var mixed[]|null + * @phpstan-var array|null + */ protected $updateInfo = null; /** @var VersionString|null */ protected $newVersion; - /** - * @param Server $server - * @param string $endpoint - */ public function __construct(Server $server, string $endpoint){ $this->server = $server; $this->endpoint = "http://$endpoint/api/"; - if($server->getProperty("auto-updater.enabled", true)){ + if((bool) $server->getProperty("auto-updater.enabled", true)){ $this->doCheck(); } } @@ -62,17 +61,20 @@ class AutoUpdater{ /** * Callback used at the end of the update checking task * - * @param array $updateInfo + * @param mixed[] $updateInfo + * @phpstan-param array $updateInfo + * + * @return void */ public function checkUpdateCallback(array $updateInfo){ $this->updateInfo = $updateInfo; $this->checkUpdate(); if($this->hasUpdate()){ (new UpdateNotifyEvent($this))->call(); - if($this->server->getProperty("auto-updater.on-update.warn-console", true)){ + if((bool) $this->server->getProperty("auto-updater.on-update.warn-console", true)){ $this->showConsoleUpdate(); } - }elseif($this->server->getProperty("auto-updater.preferred-channel", true)){ + }else{ if(!\pocketmine\IS_DEVELOPMENT_BUILD and $this->getChannel() !== "stable"){ $this->showChannelSuggestionStable(); }elseif(\pocketmine\IS_DEVELOPMENT_BUILD and $this->getChannel() === "stable"){ @@ -83,8 +85,6 @@ class AutoUpdater{ /** * Returns whether there is an update available. - * - * @return bool */ public function hasUpdate() : bool{ return $this->newVersion !== null; @@ -92,6 +92,8 @@ class AutoUpdater{ /** * Posts a warning to the console to tell the user there is an update available + * + * @return void */ public function showConsoleUpdate(){ $messages = [ @@ -108,13 +110,16 @@ class AutoUpdater{ /** * Shows a warning to a player to tell them there is an update available * - * @param Player $player + * @return void */ public function showPlayerUpdate(Player $player){ $player->sendMessage(TextFormat::DARK_PURPLE . "The version of " . $this->server->getName() . " that this server is running is out of date. Please consider updating to the latest version."); $player->sendMessage(TextFormat::DARK_PURPLE . "Check the console for more details."); } + /** + * @return void + */ protected function showChannelSuggestionStable(){ $this->printConsoleMessage([ "It appears you're running a Stable build, when you've specified that you prefer to run " . ucfirst($this->getChannel()) . " builds.", @@ -122,6 +127,9 @@ class AutoUpdater{ ]); } + /** + * @return void + */ protected function showChannelSuggestionBeta(){ $this->printConsoleMessage([ "It appears you're running a Beta build, when you've specified that you prefer to run Stable builds.", @@ -129,6 +137,11 @@ class AutoUpdater{ ]); } + /** + * @param string[] $lines + * + * @return void + */ protected function printConsoleMessage(array $lines, string $logLevel = \LogLevel::INFO){ $logger = $this->server->getLogger(); @@ -143,7 +156,8 @@ class AutoUpdater{ /** * Returns the last retrieved update data. * - * @return array|null + * @return mixed[]|null + * @phpstan-return array|null */ public function getUpdateInfo(){ return $this->updateInfo; @@ -151,6 +165,8 @@ class AutoUpdater{ /** * Schedules an AsyncTask to check for an update. + * + * @return void */ public function doCheck(){ $this->server->getAsyncPool()->submitTask(new UpdateCheckTask($this->endpoint, $this->getChannel())); @@ -158,6 +174,8 @@ class AutoUpdater{ /** * Checks the update information against the current server version to decide if there's an update + * + * @return void */ protected function checkUpdate(){ if($this->updateInfo === null){ @@ -179,8 +197,6 @@ class AutoUpdater{ /** * Returns the channel used for update checking (stable, beta, dev) - * - * @return string */ public function getChannel() : string{ $channel = strtolower($this->server->getProperty("auto-updater.preferred-channel", "stable")); @@ -193,8 +209,6 @@ class AutoUpdater{ /** * Returns the host used for update checks. - * - * @return string */ public function getEndpoint() : string{ return $this->endpoint; diff --git a/src/pocketmine/updater/UpdateCheckTask.php b/src/pocketmine/updater/UpdateCheckTask.php index 2a1c2fc11b..23fc75f27b 100644 --- a/src/pocketmine/updater/UpdateCheckTask.php +++ b/src/pocketmine/updater/UpdateCheckTask.php @@ -21,10 +21,8 @@ declare(strict_types=1); - namespace pocketmine\updater; - use pocketmine\scheduler\AsyncTask; use pocketmine\Server; use pocketmine\utils\Internet; diff --git a/src/pocketmine/utils/Color.php b/src/pocketmine/utils/Color.php index 895ebd59b7..1522c20c12 100644 --- a/src/pocketmine/utils/Color.php +++ b/src/pocketmine/utils/Color.php @@ -21,10 +21,8 @@ declare(strict_types=1); - namespace pocketmine\utils; - use function count; class Color{ @@ -47,7 +45,6 @@ class Color{ /** * Returns the alpha (opacity) value of this colour. - * @return int */ public function getA() : int{ return $this->a; @@ -56,7 +53,7 @@ class Color{ /** * Sets the alpha (opacity) value of this colour, lower = more transparent * - * @param int $a + * @return void */ public function setA(int $a){ $this->a = $a & 0xff; @@ -64,7 +61,6 @@ class Color{ /** * Retuns the red value of this colour. - * @return int */ public function getR() : int{ return $this->r; @@ -73,7 +69,7 @@ class Color{ /** * Sets the red value of this colour. * - * @param int $r + * @return void */ public function setR(int $r){ $this->r = $r & 0xff; @@ -81,7 +77,6 @@ class Color{ /** * Returns the green value of this colour. - * @return int */ public function getG() : int{ return $this->g; @@ -90,7 +85,7 @@ class Color{ /** * Sets the green value of this colour. * - * @param int $g + * @return void */ public function setG(int $g){ $this->g = $g & 0xff; @@ -98,7 +93,6 @@ class Color{ /** * Returns the blue value of this colour. - * @return int */ public function getB() : int{ return $this->b; @@ -107,7 +101,7 @@ class Color{ /** * Sets the blue value of this colour. * - * @param int $b + * @return void */ public function setB(int $b){ $this->b = $b & 0xff; @@ -117,8 +111,6 @@ class Color{ * Mixes the supplied list of colours together to produce a result colour. * * @param Color ...$colors - * - * @return Color */ public static function mix(Color ...$colors) : Color{ $count = count($colors); @@ -141,8 +133,6 @@ class Color{ /** * Returns a Color from the supplied RGB colour code (24-bit) * - * @param int $code - * * @return Color */ public static function fromRGB(int $code){ @@ -152,8 +142,6 @@ class Color{ /** * Returns a Color from the supplied ARGB colour code (32-bit) * - * @param int $code - * * @return Color */ public static function fromARGB(int $code){ @@ -162,7 +150,6 @@ class Color{ /** * Returns an ARGB 32-bit colour value. - * @return int */ public function toARGB() : int{ return ($this->a << 24) | ($this->r << 16) | ($this->g << 8) | $this->b; @@ -170,7 +157,6 @@ class Color{ /** * Returns a little-endian ARGB 32-bit colour value. - * @return int */ public function toBGRA() : int{ return ($this->b << 24) | ($this->g << 16) | ($this->r << 8) | $this->a; @@ -178,7 +164,6 @@ class Color{ /** * Returns an RGBA 32-bit colour value. - * @return int */ public function toRGBA() : int{ return ($this->r << 24) | ($this->g << 16) | ($this->b << 8) | $this->a; @@ -186,12 +171,14 @@ class Color{ /** * Returns a little-endian RGBA colour value. - * @return int */ public function toABGR() : int{ return ($this->a << 24) | ($this->b << 16) | ($this->g << 8) | $this->r; } + /** + * @return Color + */ public static function fromABGR(int $code){ return new Color($code & 0xff, ($code >> 8) & 0xff, ($code >> 16) & 0xff, ($code >> 24) & 0xff); } diff --git a/src/pocketmine/utils/Config.php b/src/pocketmine/utils/Config.php index 9fbd06bb62..0c984c6195 100644 --- a/src/pocketmine/utils/Config.php +++ b/src/pocketmine/utils/Config.php @@ -68,9 +68,16 @@ class Config{ public const ENUM = 5; // .txt, .list, .enum public const ENUMERATION = Config::ENUM; - /** @var array */ + /** + * @var mixed[] + * @phpstan-var array + */ private $config = []; + /** + * @var mixed[] + * @phpstan-var array + */ private $nestedCache = []; /** @var string */ @@ -85,6 +92,7 @@ class Config{ /** @var bool */ private $changed = false; + /** @var int[] */ public static $formats = [ "properties" => Config::PROPERTIES, "cnf" => Config::CNF, @@ -104,10 +112,11 @@ class Config{ ]; /** - * @param string $file Path of the file to be loaded - * @param int $type Config type to load, -1 by default (detect) - * @param array $default Array with the default values that will be written to the file if it did not exist - * @param null &$correct Sets correct to true if everything has been loaded correctly + * @param string $file Path of the file to be loaded + * @param int $type Config type to load, -1 by default (detect) + * @param mixed[] $default Array with the default values that will be written to the file if it did not exist + * @param null $correct reference parameter, Sets correct to true if everything has been loaded correctly + * @phpstan-param array $default */ public function __construct(string $file, int $type = Config::DETECT, array $default = [], &$correct = null){ $this->load($file, $type, $default); @@ -116,6 +125,8 @@ class Config{ /** * Removes all the changes in memory and loads the file again + * + * @return void */ public function reload(){ $this->config = []; @@ -132,21 +143,13 @@ class Config{ $this->changed = $changed; } - /** - * @param string $str - * - * @return string - */ public static function fixYAMLIndexes(string $str) : string{ return preg_replace("#^( *)(y|Y|yes|Yes|YES|n|N|no|No|NO|true|True|TRUE|false|False|FALSE|on|On|ON|off|Off|OFF)( *)\:#m", "$1\"$2\"$3:", $str); } /** - * @param string $file - * @param int $type - * @param array $default - * - * @return bool + * @param mixed[] $default + * @phpstan-param array $default */ public function load(string $file, int $type = Config::DETECT, array $default = []) : bool{ $this->correct = true; @@ -169,31 +172,30 @@ class Config{ }else{ if($this->correct){ $content = file_get_contents($this->file); + $config = null; switch($this->type){ case Config::PROPERTIES: - $this->parseProperties($content); + $config = $this->parseProperties($content); break; case Config::JSON: - $this->config = json_decode($content, true); + $config = json_decode($content, true); break; case Config::YAML: $content = self::fixYAMLIndexes($content); - $this->config = yaml_parse($content); + $config = yaml_parse($content); break; case Config::SERIALIZED: - $this->config = unserialize($content); + $config = unserialize($content); break; case Config::ENUM: - $this->parseList($content); + $config = self::parseList($content); break; default: $this->correct = false; return false; } - if(!is_array($this->config)){ - $this->config = $default; - } + $this->config = is_array($config) ? $config : $default; if($this->fillDefaults($default, $this->config) > 0){ $this->save(); } @@ -205,16 +207,10 @@ class Config{ return true; } - /** - * @return bool - */ public function check() : bool{ return $this->correct; } - /** - * @return bool - */ public function save() : bool{ if($this->correct){ $content = null; @@ -260,8 +256,6 @@ class Config{ /** * Sets the options for the JSON encoding when saving * - * @param int $options - * * @return Config $this * @throws \RuntimeException if the Config is not in JSON * @see json_encode @@ -279,8 +273,6 @@ class Config{ /** * Enables the given option in addition to the currently set JSON options * - * @param int $option - * * @return Config $this * @throws \RuntimeException if the Config is not in JSON * @see json_encode @@ -298,8 +290,6 @@ class Config{ /** * Disables the given option for the JSON encoding when saving * - * @param int $option - * * @return Config $this * @throws \RuntimeException if the Config is not in JSON * @see json_encode @@ -317,7 +307,6 @@ class Config{ /** * Returns the options for the JSON encoding when saving * - * @return int * @throws \RuntimeException if the Config is not in JSON * @see json_encode */ @@ -340,6 +329,8 @@ class Config{ /** * @param string $k * @param mixed $v + * + * @return void */ public function __set($k, $v){ $this->set($k, $v); @@ -364,6 +355,8 @@ class Config{ /** * @param string $key * @param mixed $value + * + * @return void */ public function setNested($key, $value){ $vars = explode(".", $key); @@ -429,7 +422,7 @@ class Config{ while(count($vars) > 0){ $nodeName = array_shift($vars); if(isset($currentNode[$nodeName])){ - if(empty($vars)){ //final node + if(count($vars) === 0){ //final node unset($currentNode[$nodeName]); }elseif(is_array($currentNode[$nodeName])){ $currentNode =& $currentNode[$nodeName]; @@ -453,6 +446,8 @@ class Config{ /** * @param string $k key to be set * @param mixed $v value to set key + * + * @return void */ public function set($k, $v = true){ $this->config[$k] = $v; @@ -465,7 +460,10 @@ class Config{ } /** - * @param array $v + * @param mixed[] $v + * @phpstan-param array $v + * + * @return void */ public function setAll(array $v){ $this->config = $v; @@ -475,8 +473,6 @@ class Config{ /** * @param string $k * @param bool $lowercase If set, searches Config in single-case / lowercase. - * - * @return bool */ public function exists($k, bool $lowercase = false) : bool{ if($lowercase){ @@ -490,6 +486,8 @@ class Config{ /** * @param string $k + * + * @return void */ public function remove($k){ unset($this->config[$k]); @@ -497,26 +495,28 @@ class Config{ } /** - * @param bool $keys - * - * @return array + * @return mixed[] + * @phpstan-return list|array */ public function getAll(bool $keys = false) : array{ return ($keys ? array_keys($this->config) : $this->config); } /** - * @param array $defaults + * @param mixed[] $defaults + * @phpstan-param array $defaults + * + * @return void */ public function setDefaults(array $defaults){ $this->fillDefaults($defaults, $this->config); } /** - * @param array $default - * @param array &$data - * - * @return int + * @param mixed[] $default + * @param mixed[] $data reference parameter + * @phpstan-param array $default + * @phpstan-param array $data */ private function fillDefaults(array $default, &$data) : int{ $changed = 0; @@ -540,21 +540,21 @@ class Config{ } /** - * @param string $content + * @return true[] + * @phpstan-return array */ - private function parseList(string $content){ + private static function parseList(string $content) : array{ + $result = []; foreach(explode("\n", trim(str_replace("\r\n", "\n", $content))) as $v){ $v = trim($v); if($v == ""){ continue; } - $this->config[$v] = true; + $result[$v] = true; } + return $result; } - /** - * @return string - */ private function writeProperties() : string{ $content = "#Properties Config file\r\n#" . date("D M j H:i:s T Y") . "\r\n"; foreach($this->config as $k => $v){ @@ -570,9 +570,11 @@ class Config{ } /** - * @param string $content + * @return mixed[] + * @phpstan-return array */ - private function parseProperties(string $content){ + private function parseProperties(string $content) : array{ + $result = []; if(preg_match_all('/^\s*([a-zA-Z0-9\-_\.]+)[ \t]*=([^\r\n]*)/um', $content, $matches) > 0){ //false or 0 matches foreach($matches[1] as $i => $k){ $v = trim($matches[2][$i]); @@ -588,11 +590,13 @@ class Config{ $v = false; break; } - if(isset($this->config[$k])){ + if(isset($result[$k])){ MainLogger::getLogger()->debug("[Config] Repeated property " . $k . " on file " . $this->file); } - $this->config[$k] = $v; + $result[$k] = $v; } } + + return $result; } } diff --git a/src/pocketmine/utils/Git.php b/src/pocketmine/utils/Git.php new file mode 100644 index 0000000000..f3e8fb1c1c --- /dev/null +++ b/src/pocketmine/utils/Git.php @@ -0,0 +1,63 @@ + $extraHeaders + * @phpstan-param array $headers * - * @return bool|mixed false if an error occurred, mixed data if successful. + * @return string|false */ public static function getURL(string $page, int $timeout = 10, array $extraHeaders = [], &$err = null, &$headers = null, &$httpCode = null){ try{ @@ -156,15 +158,16 @@ class Internet{ * POSTs data to an URL * NOTE: This is a blocking operation and can take a significant amount of time. It is inadvisable to use this method on the main thread. * - * @param string $page - * @param array|string $args - * @param int $timeout - * @param array $extraHeaders - * @param string &$err Will be set to the output of curl_error(). Use this to retrieve errors that occured during the operation. - * @param array[] &$headers - * @param int &$httpCode + * @param string[]|string $args + * @param string[] $extraHeaders + * @param string $err reference parameter, will be set to the output of curl_error(). Use this to retrieve errors that occured during the operation. + * @param string[] $headers reference parameter + * @param int $httpCode reference parameter + * @phpstan-param string|array $args + * @phpstan-param list $extraHeaders + * @phpstan-param array $headers * - * @return bool|mixed false if an error occurred, mixed data if successful. + * @return string|false */ public static function postURL(string $page, $args, int $timeout = 10, array $extraHeaders = [], &$err = null, &$headers = null, &$httpCode = null){ try{ @@ -183,13 +186,16 @@ class Internet{ * General cURL shorthand function. * NOTE: This is a blocking operation and can take a significant amount of time. It is inadvisable to use this method on the main thread. * - * @param string $page * @param float|int $timeout The maximum connect timeout and timeout in seconds, correct to ms. * @param string[] $extraHeaders extra headers to send as a plain string array * @param array $extraOpts extra CURLOPT_* to set as an [opt => value] map * @param callable|null $onSuccess function to be called if there is no error. Accepts a resource argument as the cURL handle. + * @phpstan-param array $extraOpts + * @phpstan-param list $extraHeaders + * @phpstan-param (callable(resource) : void)|null $onSuccess * - * @return array a plain array of three [result body : string, headers : array[], HTTP response code : int]. Headers are grouped by requests with strtolower(header name) as keys and header value as values + * @return array a plain array of three [result body : string, headers : string[][], HTTP response code : int]. Headers are grouped by requests with strtolower(header name) as keys and header value as values + * @phpstan-return array{string, list>, int} * * @throws InternetException if a cURL error occurs */ diff --git a/src/pocketmine/utils/MainLogger.php b/src/pocketmine/utils/MainLogger.php index a7824be88a..4bb3e27700 100644 --- a/src/pocketmine/utils/MainLogger.php +++ b/src/pocketmine/utils/MainLogger.php @@ -79,9 +79,6 @@ class MainLogger extends \AttachableThreadedLogger{ private $timezone; /** - * @param string $logFile - * @param bool $logDebug - * * @throws \RuntimeException */ public function __construct(string $logFile, bool $logDebug = false){ @@ -101,16 +98,12 @@ class MainLogger extends \AttachableThreadedLogger{ $this->start(PTHREADS_INHERIT_NONE); } - /** - * @return MainLogger - */ public static function getLogger() : MainLogger{ return static::$logger; } /** * Returns whether a MainLogger instance is statically registered on this thread. - * @return bool */ public static function isRegisteredStatic() : bool{ return static::$logger !== null; @@ -121,6 +114,8 @@ class MainLogger extends \AttachableThreadedLogger{ * * WARNING: Because static properties are thread-local, this MUST be called from the body of every Thread if you * want the logger to be accessible via {@link MainLogger#getLogger}. + * + * @return void */ public function registerStatic(){ if(static::$logger === null){ @@ -130,8 +125,6 @@ class MainLogger extends \AttachableThreadedLogger{ /** * Returns the current logger format used for console output. - * - * @return string */ public function getFormat() : string{ return $this->format; @@ -147,8 +140,6 @@ class MainLogger extends \AttachableThreadedLogger{ * - message * * @see http://php.net/manual/en/function.sprintf.php - * - * @param string $format */ public function setFormat(string $format) : void{ $this->format = $format; @@ -190,26 +181,41 @@ class MainLogger extends \AttachableThreadedLogger{ } /** - * @param bool $logDebug + * @return void */ public function setLogDebug(bool $logDebug){ $this->logDebug = $logDebug; } /** - * @param \Throwable $e - * @param array|null $trace + * @param mixed[][]|null $trace + * @phpstan-param list>|null $trace + * + * @return void */ public function logException(\Throwable $e, $trace = null){ if($trace === null){ $trace = $e->getTrace(); } - $errstr = $e->getMessage(); - $errfile = $e->getFile(); - $errno = $e->getCode(); - $errline = $e->getLine(); - $errorConversion = [ + $this->synchronized(function() use ($e, $trace) : void{ + $this->critical(self::printExceptionMessage($e)); + foreach(Utils::printableTrace($trace) as $line){ + $this->debug($line, true); + } + for($prev = $e->getPrevious(); $prev !== null; $prev = $prev->getPrevious()){ + $this->debug("Previous: " . self::printExceptionMessage($prev), true); + foreach(Utils::printableTrace($prev->getTrace()) as $line){ + $this->debug(" " . $line, true); + } + } + }); + + $this->syncFlushBuffer(); + } + + private static function printExceptionMessage(\Throwable $e) : string{ + static $errorConversion = [ 0 => "EXCEPTION", E_ERROR => "E_ERROR", E_WARNING => "E_WARNING", @@ -227,26 +233,16 @@ class MainLogger extends \AttachableThreadedLogger{ E_DEPRECATED => "E_DEPRECATED", E_USER_DEPRECATED => "E_USER_DEPRECATED" ]; - if($errno === 0){ - $type = LogLevel::CRITICAL; - }else{ - $type = ($errno === E_ERROR or $errno === E_USER_ERROR) ? LogLevel::ERROR : (($errno === E_USER_WARNING or $errno === E_WARNING) ? LogLevel::WARNING : LogLevel::NOTICE); - } + + $errstr = preg_replace('/\s+/', ' ', trim($e->getMessage())); + + $errno = $e->getCode(); $errno = $errorConversion[$errno] ?? $errno; - $errstr = preg_replace('/\s+/', ' ', trim($errstr)); - $errfile = Utils::cleanPath($errfile); - $message = get_class($e) . ": \"$errstr\" ($errno) in \"$errfile\" at line $errline"; - $stack = Utils::printableTrace($trace); + $errfile = Utils::cleanPath($e->getFile()); + $errline = $e->getLine(); - $this->synchronized(function() use ($type, $message, $stack) : void{ - $this->log($type, $message); - foreach($stack as $line){ - $this->debug($line, true); - } - }); - - $this->syncFlushBuffer(); + return get_class($e) . ": \"$errstr\" ($errno) in \"$errfile\" at line $errline"; } public function log($level, $message){ @@ -278,11 +274,22 @@ class MainLogger extends \AttachableThreadedLogger{ } } + /** + * @return void + */ public function shutdown(){ $this->shutdown = true; $this->notify(); } + /** + * @param string $message + * @param string $level + * @param string $prefix + * @param string $color + * + * @return void + */ protected function send($message, $level, $prefix, $color){ /** @var \DateTime|null $time */ static $time = null; @@ -317,9 +324,12 @@ class MainLogger extends \AttachableThreadedLogger{ }); } + /** + * @return void + */ public function syncFlushBuffer(){ $this->syncFlush = true; - $this->synchronized(function(){ + $this->synchronized(function() : void{ $this->notify(); //write immediately while($this->syncFlush){ @@ -331,7 +341,7 @@ class MainLogger extends \AttachableThreadedLogger{ /** * @param resource $logResource */ - private function writeLogStream($logResource){ + private function writeLogStream($logResource) : void{ while($this->logStream->count() > 0){ $chunk = $this->logStream->shift(); fwrite($logResource, $chunk); @@ -343,6 +353,9 @@ class MainLogger extends \AttachableThreadedLogger{ } } + /** + * @return void + */ public function run(){ $logResource = fopen($this->logFile, "ab"); if(!is_resource($logResource)){ @@ -351,7 +364,7 @@ class MainLogger extends \AttachableThreadedLogger{ while(!$this->shutdown){ $this->writeLogStream($logResource); - $this->synchronized(function(){ + $this->synchronized(function() : void{ $this->wait(25000); }); } diff --git a/src/pocketmine/utils/Process.php b/src/pocketmine/utils/Process.php index f5df0f703f..bd95da3cfe 100644 --- a/src/pocketmine/utils/Process.php +++ b/src/pocketmine/utils/Process.php @@ -118,13 +118,16 @@ final class Process{ return count(ThreadManager::getInstance()->getAll()) + 3; //RakLib + MainLogger + Main Thread } + /** + * @param int $pid + */ public static function kill($pid) : void{ if(MainLogger::isRegisteredStatic()){ MainLogger::getLogger()->syncFlushBuffer(); } switch(Utils::getOS()){ case "win": - exec("taskkill.exe /F /PID " . ((int) $pid) . " > NUL"); + exec("taskkill.exe /F /PID $pid > NUL"); break; case "mac": case "linux": @@ -132,15 +135,15 @@ final class Process{ if(function_exists("posix_kill")){ posix_kill($pid, 9); //SIGKILL }else{ - exec("kill -9 " . ((int) $pid) . " > /dev/null 2>&1"); + exec("kill -9 $pid > /dev/null 2>&1"); } } } /** * @param string $command Command to execute - * @param string|null &$stdout Reference parameter to write stdout to - * @param string|null &$stderr Reference parameter to write stderr to + * @param string|null $stdout Reference parameter to write stdout to + * @param string|null $stderr Reference parameter to write stderr to * * @return int process exit code */ diff --git a/src/pocketmine/utils/Random.php b/src/pocketmine/utils/Random.php index b927631256..b5680a69ba 100644 --- a/src/pocketmine/utils/Random.php +++ b/src/pocketmine/utils/Random.php @@ -35,24 +35,16 @@ class Random{ public const Z = 521288629; public const W = 88675123; - /** - * @var int - */ + /** @var int */ private $x; - /** - * @var int - */ + /** @var int */ private $y; - /** - * @var int - */ + /** @var int */ private $z; - /** - * @var int - */ + /** @var int */ private $w; /** @var int */ @@ -71,6 +63,8 @@ class Random{ /** * @param int $seed Integer to be used as seed. + * + * @return void */ public function setSeed(int $seed){ $this->seed = $seed; @@ -86,8 +80,6 @@ class Random{ /** * Returns an 31-bit integer (not signed) - * - * @return int */ public function nextInt() : int{ return $this->nextSignedInt() & 0x7fffffff; @@ -95,8 +87,6 @@ class Random{ /** * Returns a 32-bit integer (signed) - * - * @return int */ public function nextSignedInt() : int{ $t = ($this->x ^ ($this->x << 11)) & 0xffffffff; @@ -112,8 +102,6 @@ class Random{ /** * Returns a float between 0.0 and 1.0 (inclusive) - * - * @return float */ public function nextFloat() : float{ return $this->nextInt() / 0x7fffffff; @@ -121,8 +109,6 @@ class Random{ /** * Returns a float between -1.0 and 1.0 (inclusive) - * - * @return float */ public function nextSignedFloat() : float{ return $this->nextSignedInt() / 0x7fffffff; @@ -130,8 +116,6 @@ class Random{ /** * Returns a random boolean - * - * @return bool */ public function nextBoolean() : bool{ return ($this->nextSignedInt() & 0x01) === 0; @@ -142,8 +126,6 @@ class Random{ * * @param int $start default 0 * @param int $end default 0x7fffffff - * - * @return int */ public function nextRange(int $start = 0, int $end = 0x7fffffff) : int{ return $start + ($this->nextInt() % ($end + 1 - $start)); diff --git a/src/pocketmine/utils/ReversePriorityQueue.php b/src/pocketmine/utils/ReversePriorityQueue.php index 0c1aafd2cb..d9fa2d0e07 100644 --- a/src/pocketmine/utils/ReversePriorityQueue.php +++ b/src/pocketmine/utils/ReversePriorityQueue.php @@ -25,7 +25,14 @@ namespace pocketmine\utils; class ReversePriorityQueue extends \SplPriorityQueue{ + /** + * @param mixed $priority1 + * @param mixed $priority2 + * + * @return int + */ public function compare($priority1, $priority2){ + //TODO: this will crash if non-numeric priorities are used return (int) -($priority1 - $priority2); } } diff --git a/src/pocketmine/utils/ServerKiller.php b/src/pocketmine/utils/ServerKiller.php index 539f00af87..67d0562bc9 100644 --- a/src/pocketmine/utils/ServerKiller.php +++ b/src/pocketmine/utils/ServerKiller.php @@ -29,19 +29,26 @@ use function time; class ServerKiller extends Thread{ + /** @var int */ public $time; /** @var bool */ private $stopped = false; + /** + * @param int $time + */ public function __construct($time = 15){ $this->time = $time; } + /** + * @return void + */ public function run(){ $this->registerClassLoader(); $start = time(); - $this->synchronized(function(){ + $this->synchronized(function() : void{ if(!$this->stopped){ $this->wait($this->time * 1000000); } diff --git a/src/pocketmine/utils/Terminal.php b/src/pocketmine/utils/Terminal.php index 67e89226b9..94d4be6d6c 100644 --- a/src/pocketmine/utils/Terminal.php +++ b/src/pocketmine/utils/Terminal.php @@ -31,29 +31,51 @@ use function is_array; use function stream_isatty; abstract class Terminal{ + /** @var string */ public static $FORMAT_BOLD = ""; + /** @var string */ public static $FORMAT_OBFUSCATED = ""; + /** @var string */ public static $FORMAT_ITALIC = ""; + /** @var string */ public static $FORMAT_UNDERLINE = ""; + /** @var string */ public static $FORMAT_STRIKETHROUGH = ""; + /** @var string */ public static $FORMAT_RESET = ""; + /** @var string */ public static $COLOR_BLACK = ""; + /** @var string */ public static $COLOR_DARK_BLUE = ""; + /** @var string */ public static $COLOR_DARK_GREEN = ""; + /** @var string */ public static $COLOR_DARK_AQUA = ""; + /** @var string */ public static $COLOR_DARK_RED = ""; + /** @var string */ public static $COLOR_PURPLE = ""; + /** @var string */ public static $COLOR_GOLD = ""; + /** @var string */ public static $COLOR_GRAY = ""; + /** @var string */ public static $COLOR_DARK_GRAY = ""; + /** @var string */ public static $COLOR_BLUE = ""; + /** @var string */ public static $COLOR_GREEN = ""; + /** @var string */ public static $COLOR_AQUA = ""; + /** @var string */ public static $COLOR_RED = ""; + /** @var string */ public static $COLOR_LIGHT_PURPLE = ""; + /** @var string */ public static $COLOR_YELLOW = ""; + /** @var string */ public static $COLOR_WHITE = ""; /** @var bool|null */ @@ -79,6 +101,9 @@ abstract class Terminal{ return $result; } + /** + * @return void + */ protected static function getFallbackEscapeCodes(){ self::$FORMAT_BOLD = "\x1b[1m"; self::$FORMAT_OBFUSCATED = ""; @@ -106,6 +131,9 @@ abstract class Terminal{ self::$COLOR_WHITE = "\x1b[38;5;231m"; } + /** + * @return void + */ protected static function getEscapeCodes(){ self::$FORMAT_BOLD = `tput bold`; self::$FORMAT_OBFUSCATED = `tput smacs`; @@ -175,9 +203,7 @@ abstract class Terminal{ * Returns a string with colorized ANSI Escape codes for the current terminal * Note that this is platform-dependent and might produce different results depending on the terminal type and/or OS. * - * @param string|array $string - * - * @return string + * @param string|string[] $string */ public static function toANSI($string) : string{ if(!is_array($string)){ diff --git a/src/pocketmine/utils/TextFormat.php b/src/pocketmine/utils/TextFormat.php index bea431abd9..d02973c9bd 100644 --- a/src/pocketmine/utils/TextFormat.php +++ b/src/pocketmine/utils/TextFormat.php @@ -69,9 +69,7 @@ abstract class TextFormat{ /** * Splits the string by Format tokens * - * @param string $string - * - * @return array + * @return string[] */ public static function tokenize(string $string) : array{ return preg_split("/(" . TextFormat::ESCAPE . "[0-9a-fk-or])/u", $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); @@ -80,9 +78,6 @@ abstract class TextFormat{ /** * Cleans the string from Minecraft codes, ANSI Escape Codes and invalid UTF-8 characters * - * @param string $string - * @param bool $removeFormat - * * @return string valid clean UTF-8 */ public static function clean(string $string, bool $removeFormat = true) : string{ @@ -97,10 +92,7 @@ abstract class TextFormat{ /** * Replaces placeholders of § with the correct character. Only valid codes (as in the constants of the TextFormat class) will be converted. * - * @param string $string * @param string $placeholder default "&" - * - * @return string */ public static function colorize(string $string, string $placeholder = "&") : string{ return preg_replace('/' . preg_quote($placeholder, "/") . '([0-9a-fk-or])/u', TextFormat::ESCAPE . '$1', $string); @@ -109,9 +101,7 @@ abstract class TextFormat{ /** * Returns an JSON-formatted string with colors/markup * - * @param string|array $string - * - * @return string + * @param string|string[] $string */ public static function toJSON($string) : string{ if(!is_array($string)){ @@ -297,9 +287,7 @@ abstract class TextFormat{ /** * Returns an HTML-formatted string with colors/markup * - * @param string|array $string - * - * @return string + * @param string|string[] $string */ public static function toHTML($string) : string{ if(!is_array($string)){ diff --git a/src/pocketmine/utils/Timezone.php b/src/pocketmine/utils/Timezone.php index 2d6781bd71..11d260925c 100644 --- a/src/pocketmine/utils/Timezone.php +++ b/src/pocketmine/utils/Timezone.php @@ -33,6 +33,7 @@ use function implode; use function ini_get; use function ini_set; use function is_link; +use function is_string; use function json_decode; use function parse_ini_file; use function preg_match; @@ -50,6 +51,9 @@ abstract class Timezone{ return ini_get('date.timezone'); } + /** + * @return string[] + */ public static function init() : array{ $messages = []; do{ @@ -100,6 +104,9 @@ abstract class Timezone{ return $messages; } + /** + * @return string|false + */ public static function detectSystemTimezone(){ switch(Utils::getOS()){ case 'win': @@ -149,7 +156,7 @@ abstract class Timezone{ // RHEL / CentOS if(file_exists('/etc/sysconfig/clock')){ $data = parse_ini_file('/etc/sysconfig/clock'); - if(!empty($data['ZONE'])){ + if(isset($data['ZONE']) and is_string($data['ZONE'])){ return trim($data['ZONE']); } } @@ -178,7 +185,6 @@ abstract class Timezone{ } } - /** * @param string $offset In the format of +09:00, +02:00, -04:00 etc. * diff --git a/src/pocketmine/utils/UUID.php b/src/pocketmine/utils/UUID.php index 21432ad1f3..d5792bc0da 100644 --- a/src/pocketmine/utils/UUID.php +++ b/src/pocketmine/utils/UUID.php @@ -59,11 +59,6 @@ class UUID{ /** * Creates an UUID from an hexadecimal representation - * - * @param string $uuid - * @param int $version - * - * @return UUID */ public static function fromString(string $uuid, int $version = null) : UUID{ return self::fromBinary(hex2bin(str_replace("-", "", trim($uuid))), $version); @@ -72,11 +67,6 @@ class UUID{ /** * Creates an UUID from a binary representation * - * @param string $uuid - * @param int $version - * - * @return UUID - * * @throws \InvalidArgumentException */ public static function fromBinary(string $uuid, int $version = null) : UUID{ @@ -91,8 +81,6 @@ class UUID{ * Creates an UUIDv3 from binary data or list of binary data * * @param string ...$data - * - * @return UUID */ public static function fromData(string ...$data) : UUID{ $hash = hash("md5", implode($data), true); @@ -119,6 +107,10 @@ class UUID{ return $this->toString(); } + /** + * @return int + * @throws \InvalidArgumentException + */ public function getPart(int $partNumber){ if($partNumber < 0 or $partNumber > 3){ throw new \InvalidArgumentException("Invalid UUID part index $partNumber"); @@ -126,6 +118,9 @@ class UUID{ return $this->parts[$partNumber]; } + /** + * @return int[] + */ public function getParts() : array{ return $this->parts; } diff --git a/src/pocketmine/utils/Utils.php b/src/pocketmine/utils/Utils.php index 86f0977e6d..e2871ccdf3 100644 --- a/src/pocketmine/utils/Utils.php +++ b/src/pocketmine/utils/Utils.php @@ -98,6 +98,7 @@ use const STR_PAD_RIGHT; * Big collection of functions */ class Utils{ + /** @var string|null */ public static $os; /** @var UUID|null */ private static $serverUniqueId = null; @@ -105,8 +106,6 @@ class Utils{ /** * Generates an unique identifier to a callable * - * @param callable $variable - * * @return string */ public static function getCallableIdentifier(callable $variable){ @@ -120,9 +119,6 @@ class Utils{ /** * Returns a readable identifier for the given Closure, including file and line. * - * @param \Closure $closure - * - * @return string * @throws \ReflectionException */ public static function getNiceClosureName(\Closure $closure) : string{ @@ -148,9 +144,6 @@ class Utils{ /** * Returns a readable identifier for the class of the given object. Sanitizes class names for anonymous classes. * - * @param object $obj - * - * @return string * @throws \ReflectionException */ public static function getNiceClassName(object $obj) : string{ @@ -169,8 +162,6 @@ class Utils{ * The rest of the hash will change depending on other factors. * * @param string $extra optional, additional data to identify the machine - * - * @return UUID */ public static function getMachineUniqueId(string $extra = "") : UUID{ if(self::$serverUniqueId !== null and $extra === ""){ @@ -251,10 +242,6 @@ class Utils{ * Linux => Linux * BSD => bsd * Other => other - * - * @param bool $recalculate - * - * @return string */ public static function getOS(bool $recalculate = false) : string{ if(self::$os === null or $recalculate){ @@ -297,8 +284,6 @@ class Utils{ * @deprecated * @see Process::getMemoryUsage() * - * @param bool $advanced - * * @return int[]|int */ public static function getMemoryUsage(bool $advanced = false){ @@ -315,11 +300,6 @@ class Utils{ return Process::getThreadCount(); } - /** - * @param bool $recalculate - * - * @return int - */ public static function getCoreCount(bool $recalculate = false) : int{ static $processors = 0; @@ -357,10 +337,6 @@ class Utils{ /** * Returns a prettified hexdump - * - * @param string $bin - * - * @return string */ public static function hexdump(string $bin) : string{ $output = ""; @@ -374,13 +350,10 @@ class Utils{ return $output; } - /** * Returns a string that can be printed, replaces non-printable characters * * @param mixed $str - * - * @return string */ public static function printable($str) : string{ if(!is_string($str)){ @@ -406,14 +379,15 @@ class Utils{ * @deprecated * @see Internet::getURL() * - * @param string $page - * @param int $timeout default 10 - * @param array $extraHeaders - * @param string &$err Will be set to the output of curl_error(). Use this to retrieve errors that occured during the operation. - * @param array[] &$headers - * @param int &$httpCode + * @param int $timeout default 10 + * @param string[] $extraHeaders + * @param string $err reference parameter, will be set to the output of curl_error(). Use this to retrieve errors that occured during the operation. + * @param string[] $headers reference parameter + * @param int $httpCode reference parameter + * @phpstan-param list $extraHeaders + * @phpstan-param array $headers * - * @return bool|mixed false if an error occurred, mixed data if successful. + * @return string|false */ public static function getURL(string $page, int $timeout = 10, array $extraHeaders = [], &$err = null, &$headers = null, &$httpCode = null){ return Internet::getURL($page, $timeout, $extraHeaders, $err, $headers, $httpCode); @@ -423,15 +397,16 @@ class Utils{ * @deprecated * @see Internet::postURL() * - * @param string $page - * @param array|string $args - * @param int $timeout - * @param array $extraHeaders - * @param string &$err Will be set to the output of curl_error(). Use this to retrieve errors that occured during the operation. - * @param array[] &$headers - * @param int &$httpCode + * @param string[]|string $args + * @param string[] $extraHeaders + * @param string $err reference parameter, will be set to the output of curl_error(). Use this to retrieve errors that occured during the operation. + * @param string[] $headers reference parameter + * @param int $httpCode reference parameter + * @phpstan-param string|array $args + * @phpstan-param list $extraHeaders + * @phpstan-param array $headers * - * @return bool|mixed false if an error occurred, mixed data if successful. + * @return string|false */ public static function postURL(string $page, $args, int $timeout = 10, array $extraHeaders = [], &$err = null, &$headers = null, &$httpCode = null){ return Internet::postURL($page, $args, $timeout, $extraHeaders, $err, $headers, $httpCode); @@ -441,13 +416,16 @@ class Utils{ * @deprecated * @see Internet::simpleCurl() * - * @param string $page * @param float|int $timeout The maximum connect timeout and timeout in seconds, correct to ms. * @param string[] $extraHeaders extra headers to send as a plain string array * @param array $extraOpts extra CURLOPT_* to set as an [opt => value] map * @param callable|null $onSuccess function to be called if there is no error. Accepts a resource argument as the cURL handle. + * @phpstan-param array $extraOpts + * @phpstan-param list $extraHeaders + * @phpstan-param (callable(resource) : void)|null $onSuccess * - * @return array a plain array of three [result body : string, headers : array[], HTTP response code : int]. Headers are grouped by requests with strtolower(header name) as keys and header value as values + * @return array a plain array of three [result body : string, headers : string[][], HTTP response code : int]. Headers are grouped by requests with strtolower(header name) as keys and header value as values + * @phpstan-return array{string, list>, int} * * @throws \RuntimeException if a cURL error occurs */ @@ -459,7 +437,7 @@ class Utils{ $hash = 0; for($i = 0, $len = strlen($string); $i < $len; $i++){ $ord = ord($string[$i]); - if($ord & 0x80){ + if(($ord & 0x80) !== 0){ $ord -= 0x100; } $hash = 31 * $hash + $ord; @@ -474,14 +452,13 @@ class Utils{ return $hash; } - /** * @deprecated * @see Process::execute() * * @param string $command Command to execute - * @param string|null &$stdout Reference parameter to write stdout to - * @param string|null &$stderr Reference parameter to write stderr to + * @param string|null $stdout Reference parameter to write stdout to + * @param string|null $stderr Reference parameter to write stderr to * * @return int process exit code */ @@ -489,6 +466,10 @@ class Utils{ return Process::execute($command, $stdout, $stderr); } + /** + * @return mixed[] + * @phpstan-return array + */ public static function decodeJWT(string $token) : array{ list($headB64, $payloadB64, $sigB64) = explode(".", $token); @@ -507,7 +488,6 @@ class Utils{ /** * @param object $value - * @param bool $includeCurrent * * @return int */ @@ -524,10 +504,10 @@ class Utils{ } /** - * @param array $trace - * @param int $maxStringLength + * @param mixed[][] $trace + * @phpstan-param list> $trace * - * @return array + * @return string[] */ public static function printableTrace(array $trace, int $maxStringLength = 80) : array{ $messages = []; @@ -540,7 +520,7 @@ class Utils{ $args = $trace[$i]["params"]; } - $params = implode(", ", array_map(function($value) use($maxStringLength){ + $params = implode(", ", array_map(function($value) use($maxStringLength) : string{ if(is_object($value)){ return "object " . self::getNiceClassName($value); } @@ -559,9 +539,8 @@ class Utils{ } /** - * @param int $skipFrames - * - * @return array + * @return mixed[][] + * @phpstan-return list> */ public static function currentTrace(int $skipFrames = 0) : array{ ++$skipFrames; //omit this frame from trace, in addition to other skipped frames @@ -578,14 +557,17 @@ class Utils{ } /** - * @param int $skipFrames - * - * @return array + * @return string[] */ public static function printableCurrentTrace(int $skipFrames = 0) : array{ return self::printableTrace(self::currentTrace(++$skipFrames)); } + /** + * @param string $path + * + * @return string + */ public static function cleanPath($path){ $result = str_replace(["\\", ".php", "phar://"], ["/", "", ""], $path); @@ -607,8 +589,6 @@ class Utils{ /** * Extracts one-line tags from the doc-comment * - * @param string $docComment - * * @return string[] an array of tagName => tag value. If the tag has no value, an empty string is used as the value. */ public static function parseDocComment(string $docComment) : array{ @@ -618,16 +598,10 @@ class Utils{ } /** - * @param int $severity - * @param string $message - * @param string $file - * @param int $line - * - * @return bool * @throws \ErrorException */ public static function errorExceptionHandler(int $severity, string $message, string $file, int $line) : bool{ - if(error_reporting() & $severity){ + if((error_reporting() & $severity) !== 0){ throw new \ErrorException($message, 0, $severity, $file, $line); } diff --git a/src/pocketmine/utils/VersionString.php b/src/pocketmine/utils/VersionString.php index e9a5f3c60b..ca100a8434 100644 --- a/src/pocketmine/utils/VersionString.php +++ b/src/pocketmine/utils/VersionString.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace pocketmine\utils; - use function count; use function preg_match; @@ -48,11 +47,6 @@ class VersionString{ /** @var bool */ private $development = false; - /** - * @param string $baseVersion - * @param bool $isDevBuild - * @param int $buildNumber - */ public function __construct(string $baseVersion, bool $isDevBuild = false, int $buildNumber = 0){ $this->baseVersion = $baseVersion; $this->development = $isDevBuild; @@ -117,12 +111,6 @@ class VersionString{ return $this->getFullVersion(); } - /** - * @param VersionString $target - * @param bool $diff - * - * @return int - */ public function compare(VersionString $target, bool $diff = false) : int{ $number = $this->getNumber(); $tNumber = $target->getNumber(); diff --git a/src/pocketmine/wizard/SetupWizard.php b/src/pocketmine/wizard/SetupWizard.php index 8c0baed73d..8afc640a4c 100644 --- a/src/pocketmine/wizard/SetupWizard.php +++ b/src/pocketmine/wizard/SetupWizard.php @@ -33,6 +33,7 @@ use pocketmine\utils\Config; use pocketmine\utils\Internet; use pocketmine\utils\InternetException; use function base64_encode; +use function count; use function fgets; use function random_bytes; use function sleep; @@ -59,7 +60,7 @@ class SetupWizard{ $this->message(\pocketmine\NAME . " set-up wizard"); $langs = BaseLang::getLanguageList(); - if(empty($langs)){ + if(count($langs) === 0){ $this->error("No language files found, please use provided builds or clone the repository recursively."); return false; } @@ -127,13 +128,13 @@ LICENSE; return true; } - private function welcome(){ + private function welcome() : void{ $this->message($this->lang->get("setting_up_server_now")); $this->message($this->lang->get("default_values_info")); $this->message($this->lang->get("server_properties")); } - private function generateBaseConfig(){ + private function generateBaseConfig() : void{ $config = new Config(\pocketmine\DATA . "server.properties", Config::PROPERTIES); $config->set("motd", ($name = $this->getInput($this->lang->get("name_your_server"), self::DEFAULT_NAME))); @@ -172,7 +173,7 @@ LICENSE; $config->save(); } - private function generateUserFiles(){ + private function generateUserFiles() : void{ $this->message($this->lang->get("op_info")); $op = strtolower($this->getInput($this->lang->get("op_who"), "")); @@ -196,7 +197,7 @@ LICENSE; $config->save(); } - private function networkFunctions(){ + private function networkFunctions() : void{ $config = new Config(\pocketmine\DATA . "server.properties", Config::PROPERTIES); $this->error($this->lang->get("query_warning1")); $this->error($this->lang->get("query_warning2")); @@ -218,7 +219,6 @@ LICENSE; $config->save(); - $this->message($this->lang->get("ip_get")); $externalIP = Internet::getIP(); @@ -236,7 +236,7 @@ LICENSE; $this->readLine(); } - private function endWizard(){ + private function endWizard() : void{ $this->message($this->lang->get("you_have_finished")); $this->message($this->lang->get("pocketmine_plugins")); $this->message($this->lang->translateString("pocketmine_will_start", [\pocketmine\NAME])); @@ -247,7 +247,7 @@ LICENSE; sleep(4); } - private function writeLine(string $line = ""){ + private function writeLine(string $line = "") : void{ echo $line . PHP_EOL; } @@ -255,11 +255,11 @@ LICENSE; return trim((string) fgets(STDIN)); } - private function message(string $message){ + private function message(string $message) : void{ $this->writeLine("[*] " . $message); } - private function error(string $message){ + private function error(string $message) : void{ $this->writeLine("[!] " . $message); } diff --git a/tests/lint.sh b/tests/lint.sh deleted file mode 100755 index 6e5547f881..0000000000 --- a/tests/lint.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/bin/bash - -PHP_BINARY="php" -DIR="" -FIND="find" - -while getopts "p:d:f:" OPTION 2> /dev/null; do - case ${OPTION} in - p) - PHP_BINARY="$OPTARG" - ;; - d) - DIR="$OPTARG" - ;; - f) - FIND="$OPTARG" - ;; - esac -done - -if [ "$DIR" == "" ]; then - echo No directory specified - exit 1 -fi - -echo Running PHP lint scans on \"$DIR\"... - -OUTPUT=`$FIND "$DIR" -name "*.php" -print0 | xargs -0 -n1 -P4 "$PHP_BINARY" -l` - -if [ $? -ne 0 ]; then - echo $OUTPUT | grep -v "No syntax errors" - exit 1 -fi - -echo Lint scan completed successfully. diff --git a/tests/phpstan/configs/com-dotnet-magic.neon b/tests/phpstan/configs/com-dotnet-magic.neon new file mode 100644 index 0000000000..bb0f2cbadd --- /dev/null +++ b/tests/phpstan/configs/com-dotnet-magic.neon @@ -0,0 +1,7 @@ +parameters: + ignoreErrors: + - + message: "#^Access to an undefined property COM\\:\\:\\$StaticPortMappingCollection\\.$#" + count: 2 + path: ../../../src/pocketmine/network/upnp/UPnP.php + diff --git a/tests/phpstan/configs/custom-leveldb.neon b/tests/phpstan/configs/custom-leveldb.neon new file mode 100644 index 0000000000..05e8a77021 --- /dev/null +++ b/tests/phpstan/configs/custom-leveldb.neon @@ -0,0 +1,12 @@ +parameters: + ignoreErrors: + #TODO: use custom stubs + - + message: "#^Used constant LEVELDB_ZLIB_RAW_COMPRESSION not found\\.$#" + count: 1 + path: ../../../src/pocketmine/level/format/io/leveldb/LevelDB.php + + - + message: "#^Constant LEVELDB_ZLIB_RAW_COMPRESSION not found\\.$#" + count: 1 + path: ../../../src/pocketmine/level/format/io/leveldb/LevelDB.php diff --git a/tests/phpstan/configs/debug-const-checks.neon b/tests/phpstan/configs/debug-const-checks.neon deleted file mode 100644 index bfe2fa5c63..0000000000 --- a/tests/phpstan/configs/debug-const-checks.neon +++ /dev/null @@ -1,21 +0,0 @@ -parameters: - ignoreErrors: - - - message: "#^If condition is always true\\.$#" - count: 1 - path: ../../../src/pocketmine/Server.php - - - - message: "#^Ternary operator condition is always true\\.$#" - count: 1 - path: ../../../src/pocketmine/Server.php - - - - message: "#^If condition is always false\\.$#" - count: 1 - path: ../../../src/pocketmine/updater/AutoUpdater.php - - - - message: "#^Negated boolean expression is always false\\.$#" - count: 1 - path: ../../../src/pocketmine/updater/AutoUpdater.php diff --git a/tests/phpstan/configs/optional-com-dotnet.neon b/tests/phpstan/configs/optional-com-dotnet.neon deleted file mode 100644 index fb725539c7..0000000000 --- a/tests/phpstan/configs/optional-com-dotnet.neon +++ /dev/null @@ -1,12 +0,0 @@ -parameters: - ignoreErrors: - - - message: "#^Instantiated class COM not found\\.$#" - count: 2 - path: ../../../src/pocketmine/network/upnp/UPnP.php - - - - message: "#^Access to property \\$StaticPortMappingCollection on an unknown class COM\\.$#" - count: 4 - path: ../../../src/pocketmine/network/upnp/UPnP.php - diff --git a/tests/phpstan/configs/optional-leveldb.neon b/tests/phpstan/configs/optional-leveldb.neon deleted file mode 100644 index 91ff01bb55..0000000000 --- a/tests/phpstan/configs/optional-leveldb.neon +++ /dev/null @@ -1,30 +0,0 @@ -parameters: - ignoreErrors: - - - message: "#^Used constant LEVELDB_ZLIB_RAW_COMPRESSION not found\\.$#" - path: ../../../src/pocketmine/level/format/io/leveldb/LevelDB.php - - - - message: "#^Constant LEVELDB_ZLIB_RAW_COMPRESSION not found\\.$#" - path: ../../../src/pocketmine/level/format/io/leveldb/LevelDB.php - - - - message: "#^Instantiated class LevelDB not found\\.$#" - path: ../../../src/pocketmine/level/format/io/leveldb/LevelDB.php - - - - message: "#^Return typehint of method pocketmine\\\\level\\\\format\\\\io\\\\leveldb\\\\LevelDB\\:\\:createDB\\(\\) has invalid type LevelDB\\.$#" - path: ../../../src/pocketmine/level/format/io/leveldb/LevelDB.php - - - - message: "#^Return typehint of method pocketmine\\\\level\\\\format\\\\io\\\\leveldb\\\\LevelDB\\:\\:getDatabase\\(\\) has invalid type LevelDB\\.$#" - path: ../../../src/pocketmine/level/format/io/leveldb/LevelDB.php - - - - message: "#^Property pocketmine\\\\level\\\\format\\\\io\\\\leveldb\\\\LevelDB\\:\\:\\$db has unknown class LevelDB as its type\\.$#" - path: ../../../src/pocketmine/level/format/io/leveldb/LevelDB.php - - - - message: "#^Call to method (get|put|delete|close)\\(\\) on an unknown class LevelDB\\.$#" - path: ../../../src/pocketmine/level/format/io/leveldb/LevelDB.php - diff --git a/tests/phpstan/configs/php-bugs.neon b/tests/phpstan/configs/php-bugs.neon new file mode 100644 index 0000000000..0f82334e14 --- /dev/null +++ b/tests/phpstan/configs/php-bugs.neon @@ -0,0 +1,3 @@ +parameters: + ignoreErrors: + - "#^Method ReflectionMethod\\:\\:getClosure\\(\\) invoked with 0 parameters, 1 required\\.$#" diff --git a/tests/phpstan/configs/phpstan-bugs.neon b/tests/phpstan/configs/phpstan-bugs.neon index 2efbbb37b9..998fde5ad2 100644 --- a/tests/phpstan/configs/phpstan-bugs.neon +++ b/tests/phpstan/configs/phpstan-bugs.neon @@ -1,21 +1,10 @@ parameters: ignoreErrors: - - - message: "#^PHPDoc tag @param has invalid value \\(.+\\)\\: Unexpected token \"&\", expected variable at offset \\d+$#" - path: ../../../src - + - "#^Call to function is_resource\\(\\) with resource will always evaluate to true\\.$#" - message: "#^Default value of the parameter \\#\\d+ \\$[A-Za-z\\d_]+ \\(\\-?\\d+\\) of method .+\\(\\) is incompatible with type float\\.$#" path: ../../../src - - - message: "#^Cannot access an offset on Threaded\\.$#" - path: ../../../src - - - - message: "#^Cannot assign new offset to Threaded\\.$#" - path: ../../../src - - message: "#^Offset string does not exist on array\\(\\)\\.$#" count: 3 @@ -38,10 +27,16 @@ parameters: path: ../../../src/pocketmine/block/Liquid.php - - #$class::NETWORK_ID false positive - message: "#^Strict comparison using \\!\\=\\= between \\-1 and \\-1 will always evaluate to false\\.$#" + #readline() may return false + message: "#^Strict comparison using \\!\\=\\= between string and false will always evaluate to true\\.$#" count: 1 - path: ../../../src/pocketmine/entity/Entity.php + path: ../../../src/pocketmine/command/CommandReader.php + + - + #generics corruption, this might show up in other forms too + message: "#^Parameter \\#1 \\$offset \\(int\\) of method pocketmine\\\\entity\\\\AttributeMap\\:\\:offsetGet\\(\\) should be contravariant with parameter \\$offset \\(mixed\\) of method ArrayAccess\\\\:\\:offsetGet\\(\\)$#" + count: 1 + path: ../../../src/pocketmine/entity/AttributeMap.php - message: "#^Call to function assert\\(\\) with false and 'unknown hit type' will always evaluate to false\\.$#" @@ -49,23 +44,12 @@ parameters: path: ../../../src/pocketmine/entity/projectile/Projectile.php - - message: "#^Strict comparison using \\=\\=\\= between int\\ and 4 will always evaluate to false\\.$#" + message: "#^Call to function method_exists\\(\\) with pocketmine\\\\network\\\\mcpe\\\\CachedEncapsulatedPacket and '__toString' will always evaluate to true\\.$#" count: 1 - path: ../../../src/pocketmine/level/Level.php + path: ../../../src/pocketmine/network/mcpe/protocol/DataPacket.php - - message: "#^Instanceof between int and PharFileInfo will always evaluate to false\\.$#" + #phpstan doesn't understand that SplFixedArray may contain null + message: "#^Call to static method PHPUnit\\\\Framework\\\\Assert\\:\\:assertNotNull\\(\\) with int and string will always evaluate to true\\.$#" count: 1 - path: ../../../src/pocketmine/plugin/PharPluginLoader.php - - - - #ReflectionFunction::getClosureThis() should be nullable - message: "#^Else branch is unreachable because ternary operator condition is always true\\.$#" - count: 1 - path: ../../../src/pocketmine/utils/Utils.php - - - - #ReflectionFunction::getClosureScopeClass() should be nullable - message: "#^Unreachable statement \\- code above always terminates\\.$#" - count: 1 - path: ../../../src/pocketmine/utils/Utils.php + path: ../../../tests/phpunit/block/BlockTest.php diff --git a/tests/phpstan/configs/phpunit-wiring-tests.neon b/tests/phpstan/configs/phpunit-wiring-tests.neon new file mode 100644 index 0000000000..11f82d563f --- /dev/null +++ b/tests/phpstan/configs/phpunit-wiring-tests.neon @@ -0,0 +1,6 @@ +parameters: + ignoreErrors: + - + message: "#^Parameter \\#1 \\$class of static method pocketmine\\\\level\\\\format\\\\io\\\\LevelProviderManager\\:\\:addProvider\\(\\) expects class\\-string\\, string given\\.$#" + count: 2 + path: ../../phpunit/level/format/io/LevelProviderManagerTest.php diff --git a/tests/phpstan/configs/runtime-type-checks.neon b/tests/phpstan/configs/runtime-type-checks.neon index 7d48cacd90..0474cff399 100644 --- a/tests/phpstan/configs/runtime-type-checks.neon +++ b/tests/phpstan/configs/runtime-type-checks.neon @@ -1,11 +1,31 @@ parameters: ignoreErrors: + - + message: "#^Call to function is_subclass_of\\(\\) with class\\-string\\ and 'pocketmine\\\\\\\\level…' will always evaluate to true\\.$#" + count: 1 + path: ../../../src/pocketmine/Server.php + - #::add() / ::remove() thread parameter message: "#^If condition is always true\\.$#" count: 2 path: ../../../src/pocketmine/ThreadManager.php + - + message: "#^Instanceof between pocketmine\\\\Worker and pocketmine\\\\Worker will always evaluate to true\\.$#" + count: 2 + path: ../../../src/pocketmine/ThreadManager.php + + - + message: "#^Instanceof between pocketmine\\\\plugin\\\\RegisteredListener and pocketmine\\\\plugin\\\\RegisteredListener will always evaluate to true\\.$#" + count: 1 + path: ../../../src/pocketmine/event/HandlerList.php + + - + #jsonDeserialize(), not currently validated + message: "#^Casting to int something that's already int\\.$#" + count: 3 + path: ../../../src/pocketmine/item/Item.php - #::get() tags parameter message: "#^If condition is always false\\.$#" @@ -24,8 +44,44 @@ parameters: count: 1 path: ../../../src/pocketmine/item/ItemFactory.php + - + message: "#^Call to function is_object\\(\\) with \\*NEVER\\* will always evaluate to true\\.$#" + count: 1 + path: ../../../src/pocketmine/item/ItemFactory.php + - #->sendBlocks() blocks parameter message: "#^Else branch is unreachable because ternary operator condition is always true\\.$#" count: 2 path: ../../../src/pocketmine/level/Level.php + + - + message: "#^Instanceof between pocketmine\\\\math\\\\Vector3 and pocketmine\\\\math\\\\Vector3 will always evaluate to true\\.$#" + count: 2 + path: ../../../src/pocketmine/level/Level.php + + - + message: "#^Call to function is_object\\(\\) with \\*NEVER\\* will always evaluate to true\\.$#" + count: 2 + path: ../../../src/pocketmine/level/Level.php + + - + message: "#^Call to function assert\\(\\) with bool will always evaluate to true\\.$#" + count: 1 + path: ../../../src/pocketmine/level/Level.php + + - + message: "#^Call to function is_subclass_of\\(\\) with class\\-string\\ and 'pocketmine\\\\\\\\level…' will always evaluate to true\\.$#" + count: 1 + path: ../../../src/pocketmine/level/generator/GeneratorManager.php + + - + #commands plugin.yml not currently validated, can't be sure + message: "#^Call to function is_array\\(\\) with array\\ will always evaluate to true\\.$#" + count: 1 + path: ../../../src/pocketmine/plugin/PluginManager.php + + - + message: "#^Call to function is_subclass_of\\(\\) with class\\-string\\ and 'pocketmine\\\\\\\\event…' will always evaluate to true\\.$#" + count: 1 + path: ../../../src/pocketmine/plugin/PluginManager.php diff --git a/tests/phpstan/stubs/chunkutils.stub b/tests/phpstan/stubs/chunkutils.stub new file mode 100644 index 0000000000..245c6ae04c --- /dev/null +++ b/tests/phpstan/stubs/chunkutils.stub @@ -0,0 +1,26 @@ + + */ +class Threaded implements \Traversable{} diff --git a/tests/phpunit/block/BlockTest.php b/tests/phpunit/block/BlockTest.php index 222a4cc6c7..5dc6f944df 100644 --- a/tests/phpunit/block/BlockTest.php +++ b/tests/phpunit/block/BlockTest.php @@ -62,7 +62,7 @@ class BlockTest extends TestCase{ } } - self::assertTrue(false, "Can't test registering new blocks because no unused spaces left"); + throw new \RuntimeException("Can't test registering new blocks because no unused spaces left"); } /** @@ -95,7 +95,8 @@ class BlockTest extends TestCase{ } /** - * @return array + * @return int[][] + * @phpstan-return list */ public function blockGetProvider() : array{ return [ diff --git a/tests/phpunit/inventory/BaseInventoryTest.php b/tests/phpunit/inventory/BaseInventoryTest.php index ade55f317b..b4c8361871 100644 --- a/tests/phpunit/inventory/BaseInventoryTest.php +++ b/tests/phpunit/inventory/BaseInventoryTest.php @@ -29,7 +29,7 @@ use pocketmine\item\ItemFactory; class BaseInventoryTest extends TestCase{ - public static function setUpBeforeClass(){ + public static function setUpBeforeClass() : void{ ItemFactory::init(); } diff --git a/tests/phpunit/item/ItemTest.php b/tests/phpunit/item/ItemTest.php index b519dcaaa1..d844492691 100644 --- a/tests/phpunit/item/ItemTest.php +++ b/tests/phpunit/item/ItemTest.php @@ -61,6 +61,10 @@ class ItemTest extends TestCase{ } } + /** + * @return mixed[][] + * @phpstan-return list + */ public function itemFromStringProvider() : array{ return [ ["dye:4", ItemIds::DYE, 4], diff --git a/tests/phpunit/level/format/io/region/RegionLoaderTest.php b/tests/phpunit/level/format/io/region/RegionLoaderTest.php index 5eed6482cf..87145144cf 100644 --- a/tests/phpunit/level/format/io/region/RegionLoaderTest.php +++ b/tests/phpunit/level/format/io/region/RegionLoaderTest.php @@ -38,7 +38,7 @@ class RegionLoaderTest extends TestCase{ /** @var RegionLoader */ private $region; - public function setUp(){ + public function setUp() : void{ $this->regionPath = sys_get_temp_dir() . '/test.testregion'; if(file_exists($this->regionPath)){ unlink($this->regionPath); @@ -47,7 +47,7 @@ class RegionLoaderTest extends TestCase{ $this->region->open(); } - public function tearDown(){ + public function tearDown() : void{ $this->region->close(); if(file_exists($this->regionPath)){ unlink($this->regionPath); @@ -69,6 +69,10 @@ class RegionLoaderTest extends TestCase{ self::assertSame($data, $r->readChunk(0, 0)); } + /** + * @return \Generator|int[][] + * @phpstan-return \Generator + */ public function outOfBoundsCoordsProvider() : \Generator{ yield [-1, -1]; yield [32, 32]; diff --git a/tests/phpunit/network/mcpe/StupidJsonDecodeTest.php b/tests/phpunit/network/mcpe/StupidJsonDecodeTest.php index ac9940032b..4e1f3a749f 100644 --- a/tests/phpunit/network/mcpe/StupidJsonDecodeTest.php +++ b/tests/phpunit/network/mcpe/StupidJsonDecodeTest.php @@ -33,6 +33,10 @@ class StupidJsonDecodeTest extends TestCase{ $this->stupidJsonDecodeFunc = (new \ReflectionMethod(PlayerNetworkSessionAdapter::class, 'stupid_json_decode'))->getClosure(); } + /** + * @return mixed[][] + * @phpstan-return list + */ public function stupidJsonDecodeProvider() : array{ return [ ["[\n \"a\",\"b,c,d,e\\\" \",,0,1,2, false, 0.001]", ['a', 'b,c,d,e" ', '', 0, 1, 2, false, 0.001]], @@ -55,7 +59,7 @@ class StupidJsonDecodeTest extends TestCase{ * * @throws \ReflectionException */ - public function testStupidJsonDecode(string $brokenJson, $expect){ + public function testStupidJsonDecode(string $brokenJson, $expect) : void{ $decoded = ($this->stupidJsonDecodeFunc)($brokenJson, true); self::assertEquals($expect, $decoded); } diff --git a/tests/phpunit/utils/ConfigTest.php b/tests/phpunit/utils/ConfigTest.php index 7c48562ec4..3e1487358e 100644 --- a/tests/phpunit/utils/ConfigTest.php +++ b/tests/phpunit/utils/ConfigTest.php @@ -28,7 +28,8 @@ use PHPUnit\Framework\TestCase; class ConfigTest extends TestCase{ /** - * @return \Generator + * @return \Generator|mixed[][] + * @phpstan-return \Generator */ public function fixYamlIndexesProvider() : \Generator{ yield ["x: 1\ny: 2\nz: 3\n", [ @@ -60,8 +61,8 @@ class ConfigTest extends TestCase{ /** * @dataProvider fixYamlIndexesProvider * - * @param string $test - * @param array $expected + * @param string $test + * @param mixed[] $expected */ public function testFixYamlIndexes(string $test, array $expected) : void{ $fixed = Config::fixYAMLIndexes($test); diff --git a/tests/phpunit/utils/UtilsTest.php b/tests/phpunit/utils/UtilsTest.php index ae7844c449..a1a64dd57c 100644 --- a/tests/phpunit/utils/UtilsTest.php +++ b/tests/phpunit/utils/UtilsTest.php @@ -29,7 +29,7 @@ use function defined; class UtilsTest extends TestCase{ - public function setUp(){ + public function setUp() : void{ if(!defined('pocketmine\PATH')){ define('pocketmine\PATH', 'dummy'); } @@ -38,6 +38,10 @@ class UtilsTest extends TestCase{ } } + /** + * @return string[][] + * @phpstan-return list + */ public function parseDocCommentNewlineProvider() : array{ return [ ["\t/**\r\n\t * @param PlayerJoinEvent \$event\r\n\t * @priority HIGHEST\r\n\t * @notHandler\r\n\t */"], @@ -61,6 +65,6 @@ class UtilsTest extends TestCase{ public function testNamespacedNiceClosureName() : void{ //be careful with this test. The closure has to be declared on the same line as the assertion. - self::assertSame('closure@' . Utils::cleanPath(__FILE__) . '#L' . __LINE__, Utils::getNiceClosureName(function(){})); + self::assertSame('closure@' . Utils::cleanPath(__FILE__) . '#L' . __LINE__, Utils::getNiceClosureName(function() : void{})); } } diff --git a/tests/plugins/PocketMine-DevTools b/tests/plugins/PocketMine-DevTools index 73c96dfdba..8f5f3009f9 160000 --- a/tests/plugins/PocketMine-DevTools +++ b/tests/plugins/PocketMine-DevTools @@ -1 +1 @@ -Subproject commit 73c96dfdbac9c9d44f3b10192540d7ff71a1051b +Subproject commit 8f5f3009f98980c49226871d149d103e77089e08 diff --git a/tests/travis.sh b/tests/travis.sh index ee50532626..3259be3033 100755 --- a/tests/travis.sh +++ b/tests/travis.sh @@ -1,33 +1,15 @@ #!/bin/bash -PHP_BINARY="php" PM_WORKERS="auto" -while getopts "p:t:" OPTION 2> /dev/null; do +while getopts "t:" OPTION 2> /dev/null; do case ${OPTION} in - p) - PHP_BINARY="$OPTARG" - ;; t) - PM_WORKERS="$OPTARG" - ;; + PM_WORKERS="$OPTARG" + ;; esac done -./tests/lint.sh -p "$PHP_BINARY" -d ./src/pocketmine - -if [ $? -ne 0 ]; then - echo Lint scan failed! - exit 1 -fi - -[ ! -f phpstan.phar ] && echo "Downloading PHPStan..." && curl -sSLO https://github.com/phpstan/phpstan/releases/download/0.12.2/phpstan.phar -"$PHP_BINARY" phpstan.phar analyze --no-progress --memory-limit=2G || exit 1 -echo "PHPStan scan succeeded" - -[ ! -f phpunit.phar ] && echo "Downloading PHPUnit..." && curl https://phar.phpunit.de/phpunit-7.phar --silent --location -o phpunit.phar -"$PHP_BINARY" phpunit.phar --bootstrap vendor/autoload.php --fail-on-warning tests/phpunit || exit 1 - #Run-the-server tests DATA_DIR="test_data" PLUGINS_DIR="$DATA_DIR/plugins" @@ -36,10 +18,10 @@ rm -rf "$DATA_DIR" rm PocketMine-MP.phar 2> /dev/null cd tests/plugins/PocketMine-DevTools -"$PHP_BINARY" -dphar.readonly=0 ./src/DevTools/ConsoleScript.php --make ./ --relative ./ --out ../../../DevTools.phar +php -dphar.readonly=0 ./src/DevTools/ConsoleScript.php --make ./ --relative ./ --out ../../../DevTools.phar cd ../../.. -"$PHP_BINARY" -dphar.readonly=0 DevTools.phar --make src,vendor --relative ./ --entry src/pocketmine/PocketMine.php --out PocketMine-MP.phar +php -dphar.readonly=0 ./build/server-phar.php ./PocketMine-MP.phar if [ -f PocketMine-MP.phar ]; then echo Server phar created successfully. else @@ -51,7 +33,7 @@ mkdir "$DATA_DIR" mkdir "$PLUGINS_DIR" mv DevTools.phar "$PLUGINS_DIR" cp -r tests/plugins/TesterPlugin "$PLUGINS_DIR" -echo -e "stop\n" | "$PHP_BINARY" PocketMine-MP.phar --no-wizard --disable-ansi --disable-readline --debug.level=2 --data="$DATA_DIR" --plugins="$PLUGINS_DIR" --anonymous-statistics.enabled=0 --settings.async-workers="$PM_WORKERS" --settings.enable-dev-builds=1 +echo -e "stop\n" | php PocketMine-MP.phar --no-wizard --disable-ansi --disable-readline --debug.level=2 --data="$DATA_DIR" --plugins="$PLUGINS_DIR" --anonymous-statistics.enabled=0 --settings.async-workers="$PM_WORKERS" --settings.enable-dev-builds=1 output=$(grep '\[TesterPlugin\]' "$DATA_DIR/server.log") if [ "$output" == "" ]; then