Merge branch 'next-major' into modern-world-support

This commit is contained in:
Dylan K. Taylor 2022-05-20 11:21:35 +01:00
commit 68491be847
No known key found for this signature in database
GPG Key ID: 8927471A91CAFD3D
173 changed files with 911 additions and 1294 deletions

View File

@ -11,3 +11,8 @@ updates:
directory: "/" directory: "/"
schedule: schedule:
interval: daily interval: daily
- package-ecosystem: github-actions
directory: "/"
schedule:
interval: daily

View File

@ -12,16 +12,16 @@ jobs:
steps: steps:
- name: Set up Docker Buildx - name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1 uses: docker/setup-buildx-action@v2
- name: Login to DockerHub - name: Login to DockerHub
uses: docker/login-action@v1 uses: docker/login-action@v2
with: with:
username: ${{ secrets.DOCKERHUB_USERNAME }} username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }} password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Clone pmmp/PocketMine-Docker repository - name: Clone pmmp/PocketMine-Docker repository
uses: actions/checkout@v2 uses: actions/checkout@v3
with: with:
repository: pmmp/PocketMine-Docker repository: pmmp/PocketMine-Docker
fetch-depth: 1 fetch-depth: 1
@ -46,7 +46,7 @@ jobs:
run: echo ::set-output name=NAME::$(echo "${GITHUB_REPOSITORY,,}") run: echo ::set-output name=NAME::$(echo "${GITHUB_REPOSITORY,,}")
- name: Build image for tag - name: Build image for tag
uses: docker/build-push-action@v2.10.0 uses: docker/build-push-action@v3.0.0
with: with:
push: true push: true
context: ./pocketmine-mp context: ./pocketmine-mp
@ -59,7 +59,7 @@ jobs:
- name: Build image for major tag - name: Build image for major tag
if: steps.channel.outputs.CHANNEL == 'stable' if: steps.channel.outputs.CHANNEL == 'stable'
uses: docker/build-push-action@v2.10.0 uses: docker/build-push-action@v3.0.0
with: with:
push: true push: true
context: ./pocketmine-mp context: ./pocketmine-mp
@ -72,7 +72,7 @@ jobs:
- name: Build image for minor tag - name: Build image for minor tag
if: steps.channel.outputs.CHANNEL == 'stable' if: steps.channel.outputs.CHANNEL == 'stable'
uses: docker/build-push-action@v2.10.0 uses: docker/build-push-action@v3.0.0
with: with:
push: true push: true
context: ./pocketmine-mp context: ./pocketmine-mp
@ -85,7 +85,7 @@ jobs:
- name: Build image for latest tag - name: Build image for latest tag
if: steps.channel.outputs.CHANNEL == 'stable' if: steps.channel.outputs.CHANNEL == 'stable'
uses: docker/build-push-action@v2.10.0 uses: docker/build-push-action@v3.0.0
with: with:
push: true push: true
context: ./pocketmine-mp context: ./pocketmine-mp

View File

@ -13,17 +13,17 @@ jobs:
fail-fast: false fail-fast: false
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v3
with: with:
submodules: true submodules: true
- name: Setup PHP - name: Setup PHP
uses: shivammathur/setup-php@2.12.0 uses: shivammathur/setup-php@2.18.1
with: with:
php-version: 8.0 php-version: 8.0
- name: Restore Composer package cache - name: Restore Composer package cache
uses: actions/cache@v2 uses: actions/cache@v3
with: with:
path: | path: |
~/.cache/composer/files ~/.cache/composer/files
@ -60,7 +60,7 @@ jobs:
run: php build/generate-build-info-json.php ${{ github.sha }} ${{ steps.get-pm-version.outputs.PM_VERSION }} ${{ github.repository }} ${{ steps.build-number.outputs.BUILD_NUMBER }} > build_info.json run: php build/generate-build-info-json.php ${{ github.sha }} ${{ steps.get-pm-version.outputs.PM_VERSION }} ${{ github.repository }} ${{ steps.build-number.outputs.BUILD_NUMBER }} > build_info.json
- name: Upload release artifacts - name: Upload release artifacts
uses: actions/upload-artifact@v2 uses: actions/upload-artifact@v3
with: with:
name: release_artifacts name: release_artifacts
path: | path: |
@ -69,7 +69,7 @@ jobs:
${{ github.workspace }}/build_info.json ${{ github.workspace }}/build_info.json
- name: Create draft release - name: Create draft release
uses: ncipollo/release-action@v1.8.6 uses: ncipollo/release-action@v1.10.0
with: with:
artifacts: ${{ github.workspace }}/PocketMine-MP.phar,${{ github.workspace }}/start.*,${{ github.workspace }}/build_info.json artifacts: ${{ github.workspace }}/PocketMine-MP.phar,${{ github.workspace }}/start.*,${{ github.workspace }}/build_info.json
commit: ${{ github.sha }} commit: ${{ github.sha }}

View File

@ -34,7 +34,7 @@ jobs:
php: [8.0.18] php: [8.0.18]
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v3
- name: Setup PHP - name: Setup PHP
uses: pmmp/setup-php-action@aa636a4fe0c1c035fd9a3f05e360eadd86e06440 uses: pmmp/setup-php-action@aa636a4fe0c1c035fd9a3f05e360eadd86e06440
@ -46,7 +46,7 @@ jobs:
run: curl -sS https://getcomposer.org/installer | php run: curl -sS https://getcomposer.org/installer | php
- name: Restore Composer package cache - name: Restore Composer package cache
uses: actions/cache@v2 uses: actions/cache@v3
with: with:
path: | path: |
~/.cache/composer/files ~/.cache/composer/files
@ -72,7 +72,7 @@ jobs:
php: [8.0.18] php: [8.0.18]
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v3
- name: Setup PHP - name: Setup PHP
uses: pmmp/setup-php-action@aa636a4fe0c1c035fd9a3f05e360eadd86e06440 uses: pmmp/setup-php-action@aa636a4fe0c1c035fd9a3f05e360eadd86e06440
@ -84,7 +84,7 @@ jobs:
run: curl -sS https://getcomposer.org/installer | php run: curl -sS https://getcomposer.org/installer | php
- name: Restore Composer package cache - name: Restore Composer package cache
uses: actions/cache@v2 uses: actions/cache@v3
with: with:
path: | path: |
~/.cache/composer/files ~/.cache/composer/files
@ -110,7 +110,7 @@ jobs:
php: [8.0.18] php: [8.0.18]
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v3
with: with:
submodules: true submodules: true
@ -124,7 +124,7 @@ jobs:
run: curl -sS https://getcomposer.org/installer | php run: curl -sS https://getcomposer.org/installer | php
- name: Restore Composer package cache - name: Restore Composer package cache
uses: actions/cache@v2 uses: actions/cache@v3
with: with:
path: | path: |
~/.cache/composer/files ~/.cache/composer/files
@ -150,7 +150,7 @@ jobs:
php: [8.0.18] php: [8.0.18]
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v3
- name: Setup PHP - name: Setup PHP
uses: pmmp/setup-php-action@aa636a4fe0c1c035fd9a3f05e360eadd86e06440 uses: pmmp/setup-php-action@aa636a4fe0c1c035fd9a3f05e360eadd86e06440
@ -162,7 +162,7 @@ jobs:
run: curl -sS https://getcomposer.org/installer | php run: curl -sS https://getcomposer.org/installer | php
- name: Restore Composer package cache - name: Restore Composer package cache
uses: actions/cache@v2 uses: actions/cache@v3
with: with:
path: | path: |
~/.cache/composer/files ~/.cache/composer/files
@ -192,10 +192,10 @@ jobs:
fail-fast: false fail-fast: false
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v3
- name: Setup PHP and tools - name: Setup PHP and tools
uses: shivammathur/setup-php@2.15.0 uses: shivammathur/setup-php@2.18.1
with: with:
php-version: 8.0 php-version: 8.0
tools: php-cs-fixer:3.2 tools: php-cs-fixer:3.2

View File

@ -13,7 +13,7 @@ jobs:
- name: Install jq - name: Install jq
run: sudo apt update && sudo apt install jq -y run: sudo apt update && sudo apt install jq -y
- uses: actions/checkout@v2 - uses: actions/checkout@v3
with: with:
repository: pmmp/update.pmmp.io repository: pmmp/update.pmmp.io
ssh-key: ${{ secrets.UPDATE_PMMP_IO_DEPLOY_KEY }} ssh-key: ${{ secrets.UPDATE_PMMP_IO_DEPLOY_KEY }}

View File

@ -69,9 +69,6 @@ use const JSON_UNESCAPED_SLASHES;
use const SORT_NUMERIC; use const SORT_NUMERIC;
class MemoryManager{ class MemoryManager{
private Server $server;
private int $memoryLimit; private int $memoryLimit;
private int $globalMemoryLimit; private int $globalMemoryLimit;
private int $checkRate; private int $checkRate;
@ -98,8 +95,9 @@ class MemoryManager{
private \Logger $logger; private \Logger $logger;
public function __construct(Server $server){ public function __construct(
$this->server = $server; private Server $server
){
$this->logger = new \PrefixedLogger($server->getLogger(), "Memory Manager"); $this->logger = new \PrefixedLogger($server->getLogger(), "Memory Manager");
$this->init($server->getConfigGroup()); $this->init($server->getConfigGroup());

View File

@ -223,8 +223,6 @@ class Server{
private int $sendUsageTicker = 0; private int $sendUsageTicker = 0;
private \AttachableThreadedLogger $logger;
private MemoryManager $memoryManager; private MemoryManager $memoryManager;
private ConsoleReaderThread $console; private ConsoleReaderThread $console;
@ -249,7 +247,6 @@ class Server{
private UuidInterface $serverID; private UuidInterface $serverID;
private \DynamicClassLoader $autoloader;
private string $dataPath; private string $dataPath;
private string $pluginPath; private string $pluginPath;
@ -766,7 +763,12 @@ class Server{
return self::$instance; return self::$instance;
} }
public function __construct(\DynamicClassLoader $autoloader, \AttachableThreadedLogger $logger, string $dataPath, string $pluginPath){ public function __construct(
private \DynamicClassLoader $autoloader,
private \AttachableThreadedLogger $logger,
string $dataPath,
string $pluginPath
){
if(self::$instance !== null){ if(self::$instance !== null){
throw new \LogicException("Only one server instance can exist at once"); throw new \LogicException("Only one server instance can exist at once");
} }
@ -774,8 +776,6 @@ class Server{
$this->startTime = microtime(true); $this->startTime = microtime(true);
$this->tickSleeper = new SleeperHandler(); $this->tickSleeper = new SleeperHandler();
$this->autoloader = $autoloader;
$this->logger = $logger;
$this->signalHandler = new SignalHandler(function() : void{ $this->signalHandler = new SignalHandler(function() : void{
$this->logger->info("Received signal interrupt, stopping the server"); $this->logger->info("Received signal interrupt, stopping the server");

View File

@ -32,20 +32,16 @@ use function is_string;
use function strtolower; use function strtolower;
final class ServerConfigGroup{ final class ServerConfigGroup{
private Config $pocketmineYml;
private Config $serverProperties;
/** /**
* @var mixed[] * @var mixed[]
* @phpstan-var array<string, mixed> * @phpstan-var array<string, mixed>
*/ */
private array $propertyCache = []; private array $propertyCache = [];
public function __construct(Config $pocketmineYml, Config $serverProperties){ public function __construct(
$this->pocketmineYml = $pocketmineYml; private Config $pocketmineYml,
$this->serverProperties = $serverProperties; private Config $serverProperties
} ){}
/** /**
* @param mixed $defaultValue * @param mixed $defaultValue

View File

@ -38,18 +38,17 @@ class BlockBreakInfo{
*/ */
public const INCOMPATIBLE_TOOL_MULTIPLIER = 5.0; public const INCOMPATIBLE_TOOL_MULTIPLIER = 5.0;
private float $hardness;
private float $blastResistance; private float $blastResistance;
private int $toolType;
private int $toolHarvestLevel;
/** /**
* @param float|null $blastResistance default 5x hardness * @param float|null $blastResistance default 5x hardness
*/ */
public function __construct(float $hardness, int $toolType = BlockToolType::NONE, int $toolHarvestLevel = 0, ?float $blastResistance = null){ public function __construct(
$this->hardness = $hardness; private float $hardness,
$this->toolType = $toolType; private int $toolType = BlockToolType::NONE,
$this->toolHarvestLevel = $toolHarvestLevel; private int $toolHarvestLevel = 0,
?float $blastResistance = null
){
$this->blastResistance = $blastResistance ?? $hardness * 5; $this->blastResistance = $blastResistance ?? $hardness * 5;
} }

View File

@ -391,6 +391,7 @@ class BlockFactory{
$this->registerAllMeta(new Stair(new BID(Ids::STONE_BRICK_STAIRS, 0), "Stone Brick Stairs", $stoneBreakInfo)); $this->registerAllMeta(new Stair(new BID(Ids::STONE_BRICK_STAIRS, 0), "Stone Brick Stairs", $stoneBreakInfo));
$this->registerAllMeta(new Stair(new BID(Ids::MOSSY_STONE_BRICK_STAIRS, 0), "Mossy Stone Brick Stairs", $stoneBreakInfo)); $this->registerAllMeta(new Stair(new BID(Ids::MOSSY_STONE_BRICK_STAIRS, 0), "Mossy Stone Brick Stairs", $stoneBreakInfo));
$this->registerAllMeta(new StoneButton(new BID(Ids::STONE_BUTTON, 0), "Stone Button", new BlockBreakInfo(0.5, BlockToolType::PICKAXE))); $this->registerAllMeta(new StoneButton(new BID(Ids::STONE_BUTTON, 0), "Stone Button", new BlockBreakInfo(0.5, BlockToolType::PICKAXE)));
$this->registerAllMeta(new Stonecutter(new BID(Ids::STONECUTTER_BLOCK, 0, ItemIds::STONECUTTER_BLOCK), "Stonecutter", new BlockBreakInfo(3.5, BlockToolType::PICKAXE)));
$this->registerAllMeta(new StonePressurePlate(new BID(Ids::STONE_PRESSURE_PLATE, 0), "Stone Pressure Plate", new BlockBreakInfo(0.5, BlockToolType::PICKAXE, ToolTier::WOOD()->getHarvestLevel()))); $this->registerAllMeta(new StonePressurePlate(new BID(Ids::STONE_PRESSURE_PLATE, 0), "Stone Pressure Plate", new BlockBreakInfo(0.5, BlockToolType::PICKAXE, ToolTier::WOOD()->getHarvestLevel())));
//TODO: in the future this won't be the same for all the types //TODO: in the future this won't be the same for all the types
@ -431,7 +432,7 @@ class BlockFactory{
$this->registerSlabWithDoubleHighBitsRemapping($slabType); $this->registerSlabWithDoubleHighBitsRemapping($slabType);
} }
$this->registerAllMeta(new Opaque(new BID(Ids::STONECUTTER, 0), "Stonecutter", new BlockBreakInfo(3.5, BlockToolType::PICKAXE, ToolTier::WOOD()->getHarvestLevel()))); $this->registerAllMeta(new Opaque(new BID(Ids::STONECUTTER, 0), "Legacy Stonecutter", new BlockBreakInfo(3.5, BlockToolType::PICKAXE, ToolTier::WOOD()->getHarvestLevel())));
$this->registerAllMeta(new Sugarcane(new BID(Ids::REEDS_BLOCK, 0, ItemIds::REEDS), "Sugarcane", BlockBreakInfo::instant())); $this->registerAllMeta(new Sugarcane(new BID(Ids::REEDS_BLOCK, 0, ItemIds::REEDS), "Sugarcane", BlockBreakInfo::instant()));
$this->registerAllMeta(new SweetBerryBush(new BID(Ids::SWEET_BERRY_BUSH, 0, ItemIds::SWEET_BERRIES), "Sweet Berry Bush", BlockBreakInfo::instant())); $this->registerAllMeta(new SweetBerryBush(new BID(Ids::SWEET_BERRY_BUSH, 0, ItemIds::SWEET_BERRIES), "Sweet Berry Bush", BlockBreakInfo::instant()));
$this->registerAllMeta(new TNT(new BID(Ids::TNT, 0), "TNT", BlockBreakInfo::instant())); $this->registerAllMeta(new TNT(new BID(Ids::TNT, 0), "TNT", BlockBreakInfo::instant()));
@ -641,7 +642,6 @@ class BlockFactory{
//TODO: minecraft:seagrass //TODO: minecraft:seagrass
//TODO: minecraft:smithing_table //TODO: minecraft:smithing_table
//TODO: minecraft:sticky_piston //TODO: minecraft:sticky_piston
//TODO: minecraft:stonecutter_block
//TODO: minecraft:structure_block //TODO: minecraft:structure_block
//TODO: minecraft:turtle_egg //TODO: minecraft:turtle_egg
//endregion //endregion

View File

@ -27,31 +27,25 @@ use pocketmine\block\tile\Tile;
use pocketmine\utils\Utils; use pocketmine\utils\Utils;
class BlockIdentifier{ class BlockIdentifier{
private int $blockId;
private int $variant;
private ?int $itemId;
/** @phpstan-var class-string<Tile>|null */
private ?string $tileClass;
/** /**
* @phpstan-param class-string<Tile>|null $tileClass * @phpstan-param class-string<Tile>|null $tileClass
*/ */
public function __construct(int $blockId, int $variant, ?int $itemId = null, ?string $tileClass = null){ public function __construct(
private int $blockId,
private int $variant,
private ?int $itemId = null,
private ?string $tileClass = null
){
if($blockId < 0){ if($blockId < 0){
throw new \InvalidArgumentException("Block ID may not be negative"); throw new \InvalidArgumentException("Block ID may not be negative");
} }
if($variant < 0){ if($variant < 0){
throw new \InvalidArgumentException("Block variant may not be negative"); throw new \InvalidArgumentException("Block variant may not be negative");
} }
$this->blockId = $blockId;
$this->variant = $variant;
$this->itemId = $itemId;
if($tileClass !== null){ if($tileClass !== null){
Utils::testValidInstance($tileClass, Tile::class); Utils::testValidInstance($tileClass, Tile::class);
} }
$this->tileClass = $tileClass;
} }
public function getBlockId() : int{ public function getBlockId() : int{

View File

@ -24,16 +24,15 @@ declare(strict_types=1);
namespace pocketmine\block; namespace pocketmine\block;
class Element extends Opaque{ class Element extends Opaque{
public function __construct(
private int $atomicWeight; BlockIdentifier $idInfo,
private int $group; string $name,
private string $symbol; BlockBreakInfo $breakInfo,
private string $symbol,
public function __construct(BlockIdentifier $idInfo, string $name, BlockBreakInfo $breakInfo, string $symbol, int $atomicWeight, int $group){ private int $atomicWeight,
private int $group
){
parent::__construct($idInfo, $name, $breakInfo); parent::__construct($idInfo, $name, $breakInfo);
$this->atomicWeight = $atomicWeight;
$this->group = $group;
$this->symbol = $symbol;
} }
public function getAtomicWeight() : int{ public function getAtomicWeight() : int{

View File

@ -138,14 +138,16 @@ class FlowerPot extends Flowable{
$this->setPlant(null); $this->setPlant(null);
$this->position->getWorld()->setBlock($this->position, $this); $this->position->getWorld()->setBlock($this->position, $this);
return true;
}elseif($this->isValidPlant($plant)){
$this->setPlant($plant);
$item->pop();
$this->position->getWorld()->setBlock($this->position, $this);
return true; return true;
} }
$this->setPlant($plant); return false;
$item->pop();
$this->position->getWorld()->setBlock($this->position, $this);
return true;
} }
public function getDropsForCompatibleTool(Item $item) : array{ public function getDropsForCompatibleTool(Item $item) : array{

62
src/block/Stonecutter.php Normal file
View File

@ -0,0 +1,62 @@
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
declare(strict_types=1);
namespace pocketmine\block;
use pocketmine\block\inventory\StonecutterInventory;
use pocketmine\block\utils\BlockDataSerializer;
use pocketmine\block\utils\FacesOppositePlacingPlayerTrait;
use pocketmine\block\utils\HorizontalFacingTrait;
use pocketmine\item\Item;
use pocketmine\math\AxisAlignedBB;
use pocketmine\math\Facing;
use pocketmine\math\Vector3;
use pocketmine\player\Player;
class Stonecutter extends Transparent{
use FacesOppositePlacingPlayerTrait;
use HorizontalFacingTrait;
public function writeStateToMeta() : int{
return BlockDataSerializer::writeHorizontalFacing($this->facing);
}
public function readStateFromData(int $id, int $stateMeta) : void{
$this->facing = BlockDataSerializer::readHorizontalFacing($stateMeta);
}
public function getStateBitmask() : int{
return 0b111;
}
public function onInteract(Item $item, int $face, Vector3 $clickVector, ?Player $player = null) : bool{
if($player !== null){
$player->setCurrentWindow(new StonecutterInventory($this->position));
}
return true;
}
protected function recalculateCollisionBoxes() : array{
return [AxisAlignedBB::one()->trim(Facing::UP, 7 / 16)];
}
}

View File

@ -529,6 +529,7 @@ use pocketmine\utils\CloningRegistryTrait;
* @method static StainedHardenedGlass STAINED_HARDENED_GLASS() * @method static StainedHardenedGlass STAINED_HARDENED_GLASS()
* @method static StainedHardenedGlassPane STAINED_HARDENED_GLASS_PANE() * @method static StainedHardenedGlassPane STAINED_HARDENED_GLASS_PANE()
* @method static Opaque STONE() * @method static Opaque STONE()
* @method static Stonecutter STONECUTTER()
* @method static Opaque STONE_BRICKS() * @method static Opaque STONE_BRICKS()
* @method static Slab STONE_BRICK_SLAB() * @method static Slab STONE_BRICK_SLAB()
* @method static Stair STONE_BRICK_STAIRS() * @method static Stair STONE_BRICK_STAIRS()
@ -1099,6 +1100,7 @@ final class VanillaBlocks{
self::register("stone_pressure_plate", $factory->get(Ids::STONE_PRESSURE_PLATE, 0)); self::register("stone_pressure_plate", $factory->get(Ids::STONE_PRESSURE_PLATE, 0));
self::register("stone_slab", $factory->get(Ids::STONE_SLAB4, 2)); self::register("stone_slab", $factory->get(Ids::STONE_SLAB4, 2));
self::register("stone_stairs", $factory->get(Ids::NORMAL_STONE_STAIRS, 0)); self::register("stone_stairs", $factory->get(Ids::NORMAL_STONE_STAIRS, 0));
self::register("stonecutter", $factory->get(Ids::STONECUTTER_BLOCK, 2));
self::register("stripped_acacia_log", $factory->get(Ids::STRIPPED_ACACIA_LOG, 0)); self::register("stripped_acacia_log", $factory->get(Ids::STRIPPED_ACACIA_LOG, 0));
self::register("stripped_acacia_wood", $factory->get(Ids::WOOD, 12)); self::register("stripped_acacia_wood", $factory->get(Ids::WOOD, 12));
self::register("stripped_birch_log", $factory->get(Ids::STRIPPED_BIRCH_LOG, 0)); self::register("stripped_birch_log", $factory->get(Ids::STRIPPED_BIRCH_LOG, 0));

View File

@ -33,12 +33,10 @@ use pocketmine\world\sound\Sound;
class DoubleChestInventory extends BaseInventory implements BlockInventory, InventoryHolder{ class DoubleChestInventory extends BaseInventory implements BlockInventory, InventoryHolder{
use AnimatedBlockInventoryTrait; use AnimatedBlockInventoryTrait;
private ChestInventory $left; public function __construct(
private ChestInventory $right; private ChestInventory $left,
private ChestInventory $right
public function __construct(ChestInventory $left, ChestInventory $right){ ){
$this->left = $left;
$this->right = $right;
$this->holder = $this->left->getHolder(); $this->holder = $this->left->getHolder();
parent::__construct(); parent::__construct();
} }

View File

@ -43,12 +43,12 @@ class EnderChestInventory extends DelegateInventory implements BlockInventory{
onClose as animatedBlockInventoryTrait_onClose; onClose as animatedBlockInventoryTrait_onClose;
} }
private PlayerEnderInventory $inventory; public function __construct(
Position $holder,
public function __construct(Position $holder, PlayerEnderInventory $inventory){ private PlayerEnderInventory $inventory
){
parent::__construct($inventory); parent::__construct($inventory);
$this->holder = $holder; $this->holder = $holder;
$this->inventory = $inventory;
} }
public function getEnderInventory() : PlayerEnderInventory{ public function getEnderInventory() : PlayerEnderInventory{

View File

@ -35,11 +35,11 @@ class FurnaceInventory extends SimpleInventory implements BlockInventory{
public const SLOT_FUEL = 1; public const SLOT_FUEL = 1;
public const SLOT_RESULT = 2; public const SLOT_RESULT = 2;
private FurnaceType $furnaceType; public function __construct(
Position $holder,
public function __construct(Position $holder, FurnaceType $furnaceType){ private FurnaceType $furnaceType
){
$this->holder = $holder; $this->holder = $holder;
$this->furnaceType = $furnaceType;
parent::__construct(3); parent::__construct(3);
} }

View File

@ -0,0 +1,39 @@
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
declare(strict_types=1);
namespace pocketmine\block\inventory;
use pocketmine\inventory\SimpleInventory;
use pocketmine\inventory\TemporaryInventory;
use pocketmine\world\Position;
class StonecutterInventory extends SimpleInventory implements BlockInventory, TemporaryInventory{
use BlockInventoryTrait;
public const SLOT_INPUT = 0;
public function __construct(Position $holder){
$this->holder = $holder;
parent::__construct(1);
}
}

View File

@ -45,15 +45,14 @@ class FormattedCommandAlias extends Command{
*/ */
private const FORMAT_STRING_REGEX = '/\G\$(\$)?((?!0)+\d+)(-)?/'; private const FORMAT_STRING_REGEX = '/\G\$(\$)?((?!0)+\d+)(-)?/';
/** @var string[] */
private array $formatStrings = [];
/** /**
* @param string[] $formatStrings * @param string[] $formatStrings
*/ */
public function __construct(string $alias, array $formatStrings){ public function __construct(
string $alias,
private array $formatStrings
){
parent::__construct($alias); parent::__construct($alias);
$this->formatStrings = $formatStrings;
} }
public function execute(CommandSender $sender, string $commandLabel, array $args){ public function execute(CommandSender $sender, string $commandLabel, array $args){

View File

@ -26,23 +26,20 @@ namespace pocketmine\command;
use pocketmine\command\utils\InvalidCommandSyntaxException; use pocketmine\command\utils\InvalidCommandSyntaxException;
use pocketmine\plugin\Plugin; use pocketmine\plugin\Plugin;
use pocketmine\plugin\PluginOwned; use pocketmine\plugin\PluginOwned;
use pocketmine\plugin\PluginOwnedTrait;
final class PluginCommand extends Command implements PluginOwned{ final class PluginCommand extends Command implements PluginOwned{
use PluginOwnedTrait; public function __construct(
string $name,
private CommandExecutor $executor; private Plugin $owner,
private CommandExecutor $executor
public function __construct(string $name, Plugin $owner, CommandExecutor $executor){ ){
parent::__construct($name); parent::__construct($name);
$this->owningPlugin = $owner;
$this->executor = $executor;
$this->usageMessage = ""; $this->usageMessage = "";
} }
public function execute(CommandSender $sender, string $commandLabel, array $args){ public function execute(CommandSender $sender, string $commandLabel, array $args){
if(!$this->owningPlugin->isEnabled()){ if(!$this->owner->isEnabled()){
return false; return false;
} }
@ -59,6 +56,10 @@ final class PluginCommand extends Command implements PluginOwned{
return $success; return $success;
} }
public function getOwningPlugin() : Plugin{
return $this->owner;
}
public function getExecutor() : CommandExecutor{ public function getExecutor() : CommandExecutor{
return $this->executor; return $this->executor;
} }

View File

@ -37,20 +37,17 @@ use const PHP_INT_MAX;
class ConsoleCommandSender implements CommandSender{ class ConsoleCommandSender implements CommandSender{
use PermissibleDelegateTrait; use PermissibleDelegateTrait;
/** @var Server */
private $server;
/** /**
* @var int|null * @var int|null
* @phpstan-var positive-int|null * @phpstan-var positive-int|null
*/ */
protected $lineHeight = null; protected $lineHeight = null;
/** @var Language */
private $language;
public function __construct(Server $server, Language $language){ public function __construct(
$this->server = $server; private Server $server,
private Language $language
){
$this->perm = new PermissibleBase([DefaultPermissions::ROOT_CONSOLE => true]); $this->perm = new PermissibleBase([DefaultPermissions::ROOT_CONSOLE => true]);
$this->language = $language;
} }
public function getServer() : Server{ public function getServer() : Server{

View File

@ -46,13 +46,10 @@ use const PHP_BINARY;
use const STREAM_SHUT_RDWR; use const STREAM_SHUT_RDWR;
final class ConsoleReaderThread extends Thread{ final class ConsoleReaderThread extends Thread{
private \Threaded $buffer; public function __construct(
private ?SleeperNotifier $notifier; private \Threaded $buffer,
private ?SleeperNotifier $notifier = null
public function __construct(\Threaded $buffer, ?SleeperNotifier $notifier = null){ ){}
$this->buffer = $buffer;
$this->notifier = $notifier;
}
protected function onRun() : void{ protected function onRun() : void{
$buffer = $this->buffer; $buffer = $this->buffer;

View File

@ -33,15 +33,14 @@ abstract class CraftingGrid extends SimpleInventory{
public const SIZE_SMALL = 2; public const SIZE_SMALL = 2;
public const SIZE_BIG = 3; public const SIZE_BIG = 3;
private int $gridWidth;
private ?int $startX = null; private ?int $startX = null;
private ?int $xLen = null; private ?int $xLen = null;
private ?int $startY = null; private ?int $startY = null;
private ?int $yLen = null; private ?int $yLen = null;
public function __construct(int $gridWidth){ public function __construct(
$this->gridWidth = $gridWidth; private int $gridWidth
){
parent::__construct($this->getGridWidth() ** 2); parent::__construct($this->getGridWidth() ** 2);
} }

View File

@ -43,12 +43,19 @@ final class CraftingManagerFromDataHelper{
$itemDeserializerFunc = \Closure::fromCallable([Item::class, 'jsonDeserialize']); $itemDeserializerFunc = \Closure::fromCallable([Item::class, 'jsonDeserialize']);
foreach($recipes["shapeless"] as $recipe){ foreach($recipes["shapeless"] as $recipe){
if($recipe["block"] !== "crafting_table"){ //TODO: filter others out for now to avoid breaking economics $recipeType = match($recipe["block"]){
"crafting_table" => ShapelessRecipeType::CRAFTING(),
"stonecutter" => ShapelessRecipeType::STONECUTTER(),
//TODO: Cartography Table
default => null
};
if($recipeType === null){
continue; continue;
} }
$result->registerShapelessRecipe(new ShapelessRecipe( $result->registerShapelessRecipe(new ShapelessRecipe(
array_map($itemDeserializerFunc, $recipe["input"]), array_map($itemDeserializerFunc, $recipe["input"]),
array_map($itemDeserializerFunc, $recipe["output"]) array_map($itemDeserializerFunc, $recipe["output"]),
$recipeType
)); ));
} }
foreach($recipes["shaped"] as $recipe){ foreach($recipes["shaped"] as $recipe){

View File

@ -32,12 +32,15 @@ class ShapelessRecipe implements CraftingRecipe{
private array $ingredients = []; private array $ingredients = [];
/** @var Item[] */ /** @var Item[] */
private array $results; private array $results;
private ShapelessRecipeType $type;
/** /**
* @param Item[] $ingredients No more than 9 total. This applies to sum of item stack counts, not count of array. * @param Item[] $ingredients No more than 9 total. This applies to sum of item stack counts, not count of array.
* @param Item[] $results List of result items created by this recipe. * @param Item[] $results List of result items created by this recipe.
* TODO: we'll want to make the type parameter mandatory in PM5
*/ */
public function __construct(array $ingredients, array $results){ public function __construct(array $ingredients, array $results, ?ShapelessRecipeType $type = null){
$this->type = $type ?? ShapelessRecipeType::CRAFTING();
foreach($ingredients as $item){ foreach($ingredients as $item){
//Ensure they get split up properly //Ensure they get split up properly
if(count($this->ingredients) + $item->getCount() > 9){ if(count($this->ingredients) + $item->getCount() > 9){
@ -63,6 +66,10 @@ class ShapelessRecipe implements CraftingRecipe{
return $this->getResults(); return $this->getResults();
} }
public function getType() : ShapelessRecipeType{
return $this->type;
}
/** /**
* @return Item[] * @return Item[]
*/ */

View File

@ -0,0 +1,46 @@
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
declare(strict_types=1);
namespace pocketmine\crafting;
use pocketmine\utils\EnumTrait;
/**
* This doc-block is generated automatically, do not modify it manually.
* This must be regenerated whenever registry members are added, removed or changed.
* @see build/generate-registry-annotations.php
* @generate-registry-docblock
*
* @method static ShapelessRecipeType CRAFTING()
* @method static ShapelessRecipeType STONECUTTER()
*/
final class ShapelessRecipeType{
use EnumTrait;
protected static function setup() : void{
self::registerAll(
new self("crafting"),
new self("stonecutter")
);
}
}

View File

@ -80,18 +80,14 @@ class CrashDump{
public const PLUGIN_INVOLVEMENT_DIRECT = "direct"; public const PLUGIN_INVOLVEMENT_DIRECT = "direct";
public const PLUGIN_INVOLVEMENT_INDIRECT = "indirect"; public const PLUGIN_INVOLVEMENT_INDIRECT = "indirect";
/** @var Server */
private $server;
private CrashDumpData $data; private CrashDumpData $data;
/** @var string */ private string $encodedData;
private $encodedData;
private ?PluginManager $pluginManager; public function __construct(
private Server $server,
public function __construct(Server $server, ?PluginManager $pluginManager){ private ?PluginManager $pluginManager
){
$now = microtime(true); $now = microtime(true);
$this->server = $server;
$this->pluginManager = $pluginManager;
$this->data = new CrashDumpData(); $this->data = new CrashDumpData();
$this->data->format_version = self::FORMAT_VERSION; $this->data->format_version = self::FORMAT_VERSION;

View File

@ -35,12 +35,12 @@ final class CoralTypeIdMap{
* @var CoralType[] * @var CoralType[]
* @phpstan-var array<int, CoralType> * @phpstan-var array<int, CoralType>
*/ */
private $idToEnum = []; private array $idToEnum = [];
/** /**
* @var int[] * @var int[]
* @phpstan-var array<int, int> * @phpstan-var array<int, int>
*/ */
private $enumToId = []; private array $enumToId = [];
public function __construct(){ public function __construct(){
$this->register(BlockLegacyMetadata::CORAL_VARIANT_TUBE, CoralType::TUBE()); $this->register(BlockLegacyMetadata::CORAL_VARIANT_TUBE, CoralType::TUBE());

View File

@ -33,13 +33,13 @@ final class DyeColorIdMap{
* @var DyeColor[] * @var DyeColor[]
* @phpstan-var array<int, DyeColor> * @phpstan-var array<int, DyeColor>
*/ */
private $idToEnum = []; private array $idToEnum = [];
/** /**
* @var int[] * @var int[]
* @phpstan-var array<int, int> * @phpstan-var array<int, int>
*/ */
private $enumToId = []; private array $enumToId = [];
private function __construct(){ private function __construct(){
$this->register(0, DyeColor::WHITE()); $this->register(0, DyeColor::WHITE());

View File

@ -36,13 +36,13 @@ final class EffectIdMap{
* @var Effect[] * @var Effect[]
* @phpstan-var array<int, Effect> * @phpstan-var array<int, Effect>
*/ */
private $idToEffect = []; private array $idToEffect = [];
/** /**
* @var int[] * @var int[]
* @phpstan-var array<int, int> * @phpstan-var array<int, int>
*/ */
private $effectToId = []; private array $effectToId = [];
private function __construct(){ private function __construct(){
$this->register(EffectIds::SPEED, VanillaEffects::SPEED()); $this->register(EffectIds::SPEED, VanillaEffects::SPEED());

View File

@ -39,12 +39,12 @@ final class EnchantmentIdMap{
* @var Enchantment[] * @var Enchantment[]
* @phpstan-var array<int, Enchantment> * @phpstan-var array<int, Enchantment>
*/ */
private $idToEnch = []; private array $idToEnch = [];
/** /**
* @var int[] * @var int[]
* @phpstan-var array<int, int> * @phpstan-var array<int, int>
*/ */
private $enchToId = []; private array $enchToId = [];
private function __construct(){ private function __construct(){
$this->register(EnchantmentIds::PROTECTION, VanillaEnchantments::PROTECTION()); $this->register(EnchantmentIds::PROTECTION, VanillaEnchantments::PROTECTION());

View File

@ -37,12 +37,12 @@ abstract class LegacyToStringBidirectionalIdMap{
* @var string[] * @var string[]
* @phpstan-var array<int, string> * @phpstan-var array<int, string>
*/ */
private $legacyToString = []; private array $legacyToString = [];
/** /**
* @var int[] * @var int[]
* @phpstan-var array<string, int> * @phpstan-var array<string, int>
*/ */
private $stringToLegacy = []; private array $stringToLegacy = [];
public function __construct(string $file){ public function __construct(string $file){
$stringToLegacyId = json_decode(Utils::assumeNotFalse(file_get_contents($file), "Missing required resource file"), true); $stringToLegacyId = json_decode(Utils::assumeNotFalse(file_get_contents($file), "Missing required resource file"), true);

View File

@ -29,7 +29,7 @@ final class AttributeFactory{
use SingletonTrait; use SingletonTrait;
/** @var Attribute[] */ /** @var Attribute[] */
private $attributes = []; private array $attributes = [];
public function __construct(){ public function __construct(){
$this->register(Attribute::ABSORPTION, 0.00, 340282346638528859811704183484516925440.00, 0.00); $this->register(Attribute::ABSORPTION, 0.00, 340282346638528859811704183484516925440.00, 0.00);

View File

@ -27,7 +27,7 @@ use function array_filter;
class AttributeMap{ class AttributeMap{
/** @var Attribute[] */ /** @var Attribute[] */
private $attributes = []; private array $attributes = [];
public function add(Attribute $attribute) : void{ public function add(Attribute $attribute) : void{
$this->attributes[$attribute->getId()] = $attribute; $this->attributes[$attribute->getId()] = $attribute;

View File

@ -80,8 +80,7 @@ abstract class Entity{
public const MOTION_THRESHOLD = 0.00001; public const MOTION_THRESHOLD = 0.00001;
protected const STEP_CLIP_MULTIPLIER = 0.4; protected const STEP_CLIP_MULTIPLIER = 0.4;
/** @var int */ private static int $entityCount = 1;
private static $entityCount = 1;
/** /**
* Returns a new runtime entity ID for a new entity. * Returns a new runtime entity ID for a new entity.
@ -96,8 +95,7 @@ abstract class Entity{
/** @var int */ /** @var int */
protected $id; protected $id;
/** @var EntityMetadataCollection */ private EntityMetadataCollection $networkProperties;
private $networkProperties;
/** @var EntityDamageEvent|null */ /** @var EntityDamageEvent|null */
protected $lastDamageCause = null; protected $lastDamageCause = null;
@ -124,10 +122,8 @@ abstract class Entity{
/** @var EntitySizeInfo */ /** @var EntitySizeInfo */
public $size; public $size;
/** @var float */ private float $health = 20.0;
private $health = 20.0; private int $maxHealth = 20;
/** @var int */
private $maxHealth = 20;
/** @var float */ /** @var float */
protected $ySize = 0.0; protected $ySize = 0.0;
@ -150,8 +146,7 @@ abstract class Entity{
/** @var bool */ /** @var bool */
protected $isStatic = false; protected $isStatic = false;
/** @var bool */ private bool $savedWithChunk = true;
private $savedWithChunk = true;
/** @var bool */ /** @var bool */
public $isCollided = false; public $isCollided = false;
@ -181,8 +176,7 @@ abstract class Entity{
/** @var bool */ /** @var bool */
protected $closed = false; protected $closed = false;
private bool $closeInFlight = false; private bool $closeInFlight = false;
/** @var bool */ private bool $needsDespawn = false;
private $needsDespawn = false;
/** @var TimingsHandler */ /** @var TimingsHandler */
protected $timings; protected $timings;

View File

@ -70,12 +70,12 @@ final class EntityFactory{
* @var \Closure[] save ID => creator function * @var \Closure[] save ID => creator function
* @phpstan-var array<int|string, \Closure(World, CompoundTag) : Entity> * @phpstan-var array<int|string, \Closure(World, CompoundTag) : Entity>
*/ */
private $creationFuncs = []; private array $creationFuncs = [];
/** /**
* @var string[] * @var string[]
* @phpstan-var array<class-string<Entity>, string> * @phpstan-var array<class-string<Entity>, string>
*/ */
private $saveNames = []; private array $saveNames = [];
public function __construct(){ public function __construct(){
//define legacy save IDs first - use them for saving for maximum compatibility with Minecraft PC //define legacy save IDs first - use them for saving for maximum compatibility with Minecraft PC
@ -173,8 +173,6 @@ final class EntityFactory{
$this->register(Human::class, function(World $world, CompoundTag $nbt) : Human{ $this->register(Human::class, function(World $world, CompoundTag $nbt) : Human{
return new Human(Helper::parseLocation($nbt, $world), Human::parseSkinNBT($nbt), $nbt); return new Human(Helper::parseLocation($nbt, $world), Human::parseSkinNBT($nbt), $nbt);
}, ['Human']); }, ['Human']);
PaintingMotive::init();
} }
/** /**

View File

@ -26,16 +26,13 @@ namespace pocketmine\entity;
use function min; use function min;
final class EntitySizeInfo{ final class EntitySizeInfo{
/** @var float */ private float $eyeHeight;
private $height;
/** @var float */
private $width;
/** @var float */
private $eyeHeight;
public function __construct(float $height, float $width, ?float $eyeHeight = null){ public function __construct(
$this->height = $height; private float $height,
$this->width = $width; private float $width,
?float $eyeHeight = null
){
$this->eyeHeight = $eyeHeight ?? min($this->height / 2 + 0.1, $this->height); $this->eyeHeight = $eyeHeight ?? min($this->height / 2 + 0.1, $this->height);
} }

View File

@ -38,26 +38,18 @@ use function min;
class ExperienceManager{ class ExperienceManager{
/** @var Human */ private Attribute $levelAttr;
private $entity; private Attribute $progressAttr;
/** @var Attribute */ private int $totalXp = 0;
private $levelAttr;
/** @var Attribute */
private $progressAttr;
/** @var int */ private bool $canAttractXpOrbs = true;
private $totalXp = 0;
/** @var bool */ private int $xpCooldown = 0;
private $canAttractXpOrbs = true;
/** @var int */
private $xpCooldown = 0;
public function __construct(Human $entity){
$this->entity = $entity;
public function __construct(
private Human $entity
){
$this->levelAttr = self::fetchAttribute($entity, Attribute::EXPERIENCE_LEVEL); $this->levelAttr = self::fetchAttribute($entity, Attribute::EXPERIENCE_LEVEL);
$this->progressAttr = self::fetchAttribute($entity, Attribute::EXPERIENCE); $this->progressAttr = self::fetchAttribute($entity, Attribute::EXPERIENCE);
} }

View File

@ -156,9 +156,9 @@ class Human extends Living implements ProjectileSource, InventoryHolder{
public function jump() : void{ public function jump() : void{
parent::jump(); parent::jump();
if($this->isSprinting()){ if($this->isSprinting()){
$this->hungerManager->exhaust(0.8, PlayerExhaustEvent::CAUSE_SPRINT_JUMPING); $this->hungerManager->exhaust(0.2, PlayerExhaustEvent::CAUSE_SPRINT_JUMPING);
}else{ }else{
$this->hungerManager->exhaust(0.2, PlayerExhaustEvent::CAUSE_JUMPING); $this->hungerManager->exhaust(0.05, PlayerExhaustEvent::CAUSE_JUMPING);
} }
} }

View File

@ -32,25 +32,17 @@ use function min;
class HungerManager{ class HungerManager{
/** @var Human */ private Attribute $hungerAttr;
private $entity; private Attribute $saturationAttr;
private Attribute $exhaustionAttr;
/** @var Attribute */ private int $foodTickTimer = 0;
private $hungerAttr;
/** @var Attribute */
private $saturationAttr;
/** @var Attribute */
private $exhaustionAttr;
/** @var int */ private bool $enabled = true;
private $foodTickTimer = 0;
/** @var bool */
private $enabled = true;
public function __construct(Human $entity){
$this->entity = $entity;
public function __construct(
private Human $entity
){
$this->hungerAttr = self::fetchAttribute($entity, Attribute::HUNGER); $this->hungerAttr = self::fetchAttribute($entity, Attribute::HUNGER);
$this->saturationAttr = self::fetchAttribute($entity, Attribute::SATURATION); $this->saturationAttr = self::fetchAttribute($entity, Attribute::SATURATION);
$this->exhaustionAttr = self::fetchAttribute($entity, Attribute::EXHAUSTION); $this->exhaustionAttr = self::fetchAttribute($entity, Attribute::EXHAUSTION);
@ -208,7 +200,7 @@ class HungerManager{
if($food >= 18){ if($food >= 18){
if($health < $this->entity->getMaxHealth()){ if($health < $this->entity->getMaxHealth()){
$this->entity->heal(new EntityRegainHealthEvent($this->entity, 1, EntityRegainHealthEvent::CAUSE_SATURATION)); $this->entity->heal(new EntityRegainHealthEvent($this->entity, 1, EntityRegainHealthEvent::CAUSE_SATURATION));
$this->exhaust(3.0, PlayerExhaustEvent::CAUSE_HEALTH_REGEN); $this->exhaust(6.0, PlayerExhaustEvent::CAUSE_HEALTH_REGEN);
} }
}elseif($food <= 0){ }elseif($food <= 0){
if(($difficulty === World::DIFFICULTY_EASY && $health > 10) || ($difficulty === World::DIFFICULTY_NORMAL && $health > 1) || $difficulty === World::DIFFICULTY_HARD){ if(($difficulty === World::DIFFICULTY_EASY && $health > 10) || ($difficulty === World::DIFFICULTY_NORMAL && $health > 1) || $difficulty === World::DIFFICULTY_HARD){

View File

@ -39,16 +39,11 @@ final class Skin{
128 * 128 * 4 128 * 128 * 4
]; ];
/** @var string */ private string $skinId;
private $skinId; private string $skinData;
/** @var string */ private string $capeData;
private $skinData; private string $geometryName;
/** @var string */ private string $geometryData;
private $capeData;
/** @var string */
private $geometryName;
/** @var string */
private $geometryData;
private static function checkLength(string $string, string $name, int $maxLength) : void{ private static function checkLength(string $string, string $name, int $maxLength) : void{
if(strlen($string) > $maxLength){ if(strlen($string) > $maxLength){

View File

@ -44,8 +44,7 @@ class Squid extends WaterAnimal{
/** @var float */ /** @var float */
public $swimSpeed = 0.1; public $swimSpeed = 0.1;
/** @var int */ private int $switchDirectionTicker = 0;
private $switchDirectionTicker = 0;
protected function getInitialSizeInfo() : EntitySizeInfo{ return new EntitySizeInfo(0.95, 0.95); } protected function getInitialSizeInfo() : EntitySizeInfo{ return new EntitySizeInfo(0.95, 0.95); }

View File

@ -38,10 +38,8 @@ class Villager extends Living implements Ageable{
public static function getNetworkTypeId() : string{ return EntityIds::VILLAGER; } public static function getNetworkTypeId() : string{ return EntityIds::VILLAGER; }
/** @var bool */ private bool $baby = false;
private $baby = false; private int $profession = self::PROFESSION_FARMER;
/** @var int */
private $profession = self::PROFESSION_FARMER;
protected function getInitialSizeInfo() : EntitySizeInfo{ protected function getInitialSizeInfo() : EntitySizeInfo{
return new EntitySizeInfo(1.8, 0.6); //TODO: eye height?? return new EntitySizeInfo(1.8, 0.6); //TODO: eye height??

View File

@ -28,23 +28,12 @@ use pocketmine\utils\Limits;
use function max; use function max;
class EffectInstance{ class EffectInstance{
/** @var Effect */ private Effect $effectType;
private $effectType; private int $duration;
private int $amplifier;
/** @var int */ private bool $visible;
private $duration; private bool $ambient;
private Color $color;
/** @var int */
private $amplifier;
/** @var bool */
private $visible;
/** @var bool */
private $ambient;
/** @var Color */
private $color;
/** /**
* @param int|null $duration Passing null will use the effect type's default duration * @param int|null $duration Passing null will use the effect type's default duration

View File

@ -34,9 +34,6 @@ use function spl_object_id;
class EffectManager{ class EffectManager{
/** @var Living */
private $entity;
/** @var EffectInstance[] */ /** @var EffectInstance[] */
protected $effects = []; protected $effects = [];
@ -56,8 +53,9 @@ class EffectManager{
*/ */
protected $effectRemoveHooks; protected $effectRemoveHooks;
public function __construct(Living $entity){ public function __construct(
$this->entity = $entity; private Living $entity
){
$this->bubbleColor = new Color(0, 0, 0, 0); $this->bubbleColor = new Color(0, 0, 0, 0);
$this->effectAddHooks = new ObjectSet(); $this->effectAddHooks = new ObjectSet();
$this->effectRemoveHooks = new ObjectSet(); $this->effectRemoveHooks = new ObjectSet();

View File

@ -36,7 +36,7 @@ class HungerEffect extends Effect{
public function applyEffect(Living $entity, EffectInstance $instance, float $potency = 1.0, ?Entity $source = null) : void{ public function applyEffect(Living $entity, EffectInstance $instance, float $potency = 1.0, ?Entity $source = null) : void{
if($entity instanceof Human){ if($entity instanceof Human){
$entity->getHungerManager()->exhaust(0.025 * $instance->getEffectLevel(), PlayerExhaustEvent::CAUSE_POTION); $entity->getHungerManager()->exhaust(0.1 * $instance->getEffectLevel(), PlayerExhaustEvent::CAUSE_POTION);
} }
} }
} }

View File

@ -30,9 +30,7 @@ use pocketmine\event\entity\EntityDamageEvent;
use pocketmine\lang\Translatable; use pocketmine\lang\Translatable;
class PoisonEffect extends Effect{ class PoisonEffect extends Effect{
private bool $fatal;
/** @var bool */
private $fatal;
public function __construct(Translatable|string $name, Color $color, bool $isBad = false, int $defaultDuration = 600, bool $hasBubbles = true, bool $fatal = false){ public function __construct(Translatable|string $name, Color $color, bool $isBad = false, int $defaultDuration = 600, bool $hasBubbles = true, bool $fatal = false){
parent::__construct($name, $color, $isBad, $defaultDuration, $hasBubbles); parent::__construct($name, $color, $isBad, $defaultDuration, $hasBubbles);

View File

@ -24,6 +24,8 @@ declare(strict_types=1);
namespace pocketmine\entity\object; namespace pocketmine\entity\object;
class PaintingMotive{ class PaintingMotive{
private static bool $initialized = false;
/** @var PaintingMotive[] */ /** @var PaintingMotive[] */
protected static $motives = []; protected static $motives = [];
@ -76,6 +78,9 @@ class PaintingMotive{
* @return PaintingMotive[] * @return PaintingMotive[]
*/ */
public static function getAll() : array{ public static function getAll() : array{
if(!self::$initialized){
self::init();
}
return self::$motives; return self::$motives;
} }

View File

@ -30,8 +30,8 @@ use function get_class;
abstract class Event{ abstract class Event{
private const MAX_EVENT_CALL_DEPTH = 50; private const MAX_EVENT_CALL_DEPTH = 50;
/** @var int */
private static $eventCallDepth = 1; private static int $eventCallDepth = 1;
/** @var string|null */ /** @var string|null */
protected $eventName = null; protected $eventName = null;

View File

@ -28,18 +28,14 @@ use function array_fill_keys;
use function spl_object_id; use function spl_object_id;
class HandlerList{ class HandlerList{
/** @var string */
private $class;
/** @var RegisteredListener[][] */ /** @var RegisteredListener[][] */
private $handlerSlots = []; private array $handlerSlots = [];
/** @var HandlerList|null */
private $parentList;
public function __construct(string $class, ?HandlerList $parentList){ public function __construct(
$this->class = $class; private string $class,
private ?HandlerList $parentList
){
$this->handlerSlots = array_fill_keys(EventPriority::ALL, []); $this->handlerSlots = array_fill_keys(EventPriority::ALL, []);
$this->parentList = $parentList;
} }
/** /**

View File

@ -28,15 +28,14 @@ use pocketmine\utils\Utils;
class HandlerListManager{ class HandlerListManager{
/** @var HandlerListManager|null */ private static ?self $globalInstance = null;
private static $globalInstance = null;
public static function global() : self{ public static function global() : self{
return self::$globalInstance ?? (self::$globalInstance = new self); return self::$globalInstance ?? (self::$globalInstance = new self);
} }
/** @var HandlerList[] classname => HandlerList */ /** @var HandlerList[] classname => HandlerList */
private $allLists = []; private array $allLists = [];
/** /**
* Unregisters all the listeners * Unregisters all the listeners

View File

@ -28,31 +28,16 @@ use pocketmine\timings\TimingsHandler;
use function in_array; use function in_array;
class RegisteredListener{ class RegisteredListener{
public function __construct(
/** @var \Closure */ private \Closure $handler,
private $handler; private int $priority,
private Plugin $plugin,
/** @var int */ private bool $handleCancelled,
private $priority; private TimingsHandler $timings
){
/** @var Plugin */
private $plugin;
/** @var bool */
private $handleCancelled;
/** @var TimingsHandler */
private $timings;
public function __construct(\Closure $handler, int $priority, Plugin $plugin, bool $handleCancelled, TimingsHandler $timings){
if(!in_array($priority, EventPriority::ALL, true)){ if(!in_array($priority, EventPriority::ALL, true)){
throw new \InvalidArgumentException("Invalid priority number $priority"); throw new \InvalidArgumentException("Invalid priority number $priority");
} }
$this->handler = $handler;
$this->priority = $priority;
$this->plugin = $plugin;
$this->handleCancelled = $handleCancelled;
$this->timings = $timings;
} }
public function getHandler() : \Closure{ public function getHandler() : \Closure{

View File

@ -0,0 +1,44 @@
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
declare(strict_types=1);
namespace pocketmine\event\player;
use pocketmine\player\Player;
/**
* Called after a player is sent a chunk as part of their view radius.
*/
final class PlayerPostChunkSendEvent extends PlayerEvent{
public function __construct(
Player $player,
private int $chunkX,
private int $chunkZ
){
$this->player = $player;
}
public function getChunkX() : int{ return $this->chunkX; }
public function getChunkZ() : int{ return $this->chunkZ; }
}

View File

@ -29,13 +29,12 @@ use pocketmine\player\Player;
* Called when a player requests a different viewing distance than the current one. * Called when a player requests a different viewing distance than the current one.
*/ */
class PlayerViewDistanceChangeEvent extends PlayerEvent{ class PlayerViewDistanceChangeEvent extends PlayerEvent{
protected int $newDistance; public function __construct(
protected int $oldDistance; Player $player,
protected int $oldDistance,
public function __construct(Player $player, int $oldDistance, int $newDistance){ protected int $newDistance
){
$this->player = $player; $this->player = $player;
$this->oldDistance = $oldDistance;
$this->newDistance = $newDistance;
} }
/** /**

View File

@ -30,31 +30,20 @@ class CallbackInventoryListener implements InventoryListener{
//TODO: turn the closure signatures into type aliases when PHPStan supports them //TODO: turn the closure signatures into type aliases when PHPStan supports them
/**
* @var \Closure|null
* @phpstan-var (\Closure(Inventory, int, Item) : void)|null
*/
private $onSlotChangeCallback;
/**
* @var \Closure|null
* @phpstan-var (\Closure(Inventory, Item[]) : void)|null
*/
private $onContentChangeCallback;
/** /**
* @phpstan-param (\Closure(Inventory, int, Item) : void)|null $onSlotChange * @phpstan-param (\Closure(Inventory, int, Item) : void)|null $onSlotChange
* @phpstan-param (\Closure(Inventory, Item[]) : void)|null $onContentChange * @phpstan-param (\Closure(Inventory, Item[]) : void)|null $onContentChange
*/ */
public function __construct(?\Closure $onSlotChange, ?\Closure $onContentChange){ public function __construct(
private ?\Closure $onSlotChange,
private ?\Closure $onContentChange
){
if($onSlotChange !== null){ if($onSlotChange !== null){
Utils::validateCallableSignature(function(Inventory $inventory, int $slot, Item $oldItem) : void{}, $onSlotChange); Utils::validateCallableSignature(function(Inventory $inventory, int $slot, Item $oldItem) : void{}, $onSlotChange);
} }
if($onContentChange !== null){ if($onContentChange !== null){
Utils::validateCallableSignature(function(Inventory $inventory, array $oldContents) : void{}, $onContentChange); Utils::validateCallableSignature(function(Inventory $inventory, array $oldContents) : void{}, $onContentChange);
} }
$this->onSlotChangeCallback = $onSlotChange;
$this->onContentChangeCallback = $onContentChange;
} }
/** /**
@ -72,8 +61,8 @@ class CallbackInventoryListener implements InventoryListener{
} }
public function onSlotChange(Inventory $inventory, int $slot, Item $oldItem) : void{ public function onSlotChange(Inventory $inventory, int $slot, Item $oldItem) : void{
if($this->onSlotChangeCallback !== null){ if($this->onSlotChange !== null){
($this->onSlotChangeCallback)($inventory, $slot, $oldItem); ($this->onSlotChange)($inventory, $slot, $oldItem);
} }
} }
@ -81,8 +70,8 @@ class CallbackInventoryListener implements InventoryListener{
* @param Item[] $oldContents * @param Item[] $oldContents
*/ */
public function onContentChange(Inventory $inventory, array $oldContents) : void{ public function onContentChange(Inventory $inventory, array $oldContents) : void{
if($this->onContentChangeCallback !== null){ if($this->onContentChange !== null){
($this->onContentChangeCallback)($inventory, $oldContents); ($this->onContentChange)($inventory, $oldContents);
} }
} }
} }

View File

@ -34,7 +34,7 @@ final class CreativeInventory{
use SingletonTrait; use SingletonTrait;
/** @var Item[] */ /** @var Item[] */
private $creative = []; private array $creative = [];
private function __construct(){ private function __construct(){
$creativeItems = json_decode(file_get_contents(Path::join(\pocketmine\BEDROCK_DATA_PATH, "creativeitems.json")), true); $creativeItems = json_decode(file_get_contents(Path::join(\pocketmine\BEDROCK_DATA_PATH, "creativeitems.json")), true);

View File

@ -31,13 +31,12 @@ use function count;
* An inventory which is backed by another inventory, and acts as a proxy to that inventory. * An inventory which is backed by another inventory, and acts as a proxy to that inventory.
*/ */
class DelegateInventory extends BaseInventory{ class DelegateInventory extends BaseInventory{
private Inventory $backingInventory;
private InventoryListener $inventoryListener; private InventoryListener $inventoryListener;
public function __construct(Inventory $backingInventory){ public function __construct(
private Inventory $backingInventory
){
parent::__construct(); parent::__construct();
$this->backingInventory = $backingInventory;
$this->backingInventory->getListeners()->add($this->inventoryListener = new CallbackInventoryListener( $this->backingInventory->getListeners()->add($this->inventoryListener = new CallbackInventoryListener(
function(Inventory $unused, int $slot, Item $oldItem) : void{ function(Inventory $unused, int $slot, Item $oldItem) : void{
$this->onSlotChange($slot, $oldItem); $this->onSlotChange($slot, $oldItem);

View File

@ -26,11 +26,10 @@ namespace pocketmine\inventory;
use pocketmine\entity\Human; use pocketmine\entity\Human;
final class PlayerEnderInventory extends SimpleInventory{ final class PlayerEnderInventory extends SimpleInventory{
public function __construct(
private Human $holder; private Human $holder,
int $size = 27
public function __construct(Human $holder, int $size = 27){ ){
$this->holder = $holder;
parent::__construct($size); parent::__construct($size);
} }

View File

@ -26,8 +26,7 @@ namespace pocketmine\inventory;
use pocketmine\entity\Human; use pocketmine\entity\Human;
final class PlayerOffHandInventory extends SimpleInventory{ final class PlayerOffHandInventory extends SimpleInventory{
/** @var Human */ private Human $holder;
private $holder;
public function __construct(Human $player){ public function __construct(Human $player){
$this->holder = $player; $this->holder = $player;

View File

@ -57,8 +57,8 @@ class CraftingTransaction extends InventoryTransaction{
protected $inputs = []; protected $inputs = [];
/** @var Item[] */ /** @var Item[] */
protected $outputs = []; protected $outputs = [];
/** @var CraftingManager */
private $craftingManager; private CraftingManager $craftingManager;
public function __construct(Player $source, CraftingManager $craftingManager, array $actions = []){ public function __construct(Player $source, CraftingManager $craftingManager, array $actions = []){
parent::__construct($source, $actions); parent::__construct($source, $actions);

View File

@ -36,8 +36,7 @@ class SlotChangeAction extends InventoryAction{
/** @var Inventory */ /** @var Inventory */
protected $inventory; protected $inventory;
/** @var int */ private int $inventorySlot;
private $inventorySlot;
public function __construct(Inventory $inventory, int $inventorySlot, Item $sourceItem, Item $targetItem){ public function __construct(Inventory $inventory, int $inventorySlot, Item $sourceItem, Item $targetItem){
parent::__construct($sourceItem, $targetItem); parent::__construct($sourceItem, $targetItem);

View File

@ -40,8 +40,7 @@ class Armor extends Durable{
public const TAG_CUSTOM_COLOR = "customColor"; //TAG_Int public const TAG_CUSTOM_COLOR = "customColor"; //TAG_Int
/** @var ArmorTypeInfo */ private ArmorTypeInfo $armorInfo;
private $armorInfo;
/** @var Color|null */ /** @var Color|null */
protected $customColor = null; protected $customColor = null;

View File

@ -24,19 +24,11 @@ declare(strict_types=1);
namespace pocketmine\item; namespace pocketmine\item;
class ArmorTypeInfo{ class ArmorTypeInfo{
public function __construct(
/** @var int */ private int $defensePoints,
private $defensePoints; private int $maxDurability,
/** @var int */ private int $armorSlot
private $maxDurability; ){}
/** @var int */
private $armorSlot;
public function __construct(int $defensePoints, int $maxDurability, int $armorSlot){
$this->defensePoints = $defensePoints;
$this->maxDurability = $maxDurability;
$this->armorSlot = $armorSlot;
}
public function getDefensePoints() : int{ public function getDefensePoints() : int{
return $this->defensePoints; return $this->defensePoints;

View File

@ -39,14 +39,13 @@ class Banner extends ItemBlockWallOrFloor{
public const TAG_PATTERN_COLOR = TileBanner::TAG_PATTERN_COLOR; public const TAG_PATTERN_COLOR = TileBanner::TAG_PATTERN_COLOR;
public const TAG_PATTERN_NAME = TileBanner::TAG_PATTERN_NAME; public const TAG_PATTERN_NAME = TileBanner::TAG_PATTERN_NAME;
/** @var DyeColor */ private DyeColor $color;
private $color;
/** /**
* @var BannerPatternLayer[] * @var BannerPatternLayer[]
* @phpstan-var list<BannerPatternLayer> * @phpstan-var list<BannerPatternLayer>
*/ */
private $patterns = []; private array $patterns = [];
public function __construct(ItemIdentifier $identifier, Block $floorVariant, Block $wallVariant){ public function __construct(ItemIdentifier $identifier, Block $floorVariant, Block $wallVariant){
parent::__construct($identifier, $floorVariant, $wallVariant); parent::__construct($identifier, $floorVariant, $wallVariant);

View File

@ -28,9 +28,7 @@ use pocketmine\block\utils\DyeColor;
use pocketmine\block\VanillaBlocks; use pocketmine\block\VanillaBlocks;
class Bed extends Item{ class Bed extends Item{
private DyeColor $color;
/** @var DyeColor */
private $color;
public function __construct(ItemIdentifier $identifier, string $name, DyeColor $color){ public function __construct(ItemIdentifier $identifier, string $name, DyeColor $color){
parent::__construct($identifier, $name); parent::__construct($identifier, $name);

View File

@ -26,8 +26,7 @@ namespace pocketmine\item;
use pocketmine\block\utils\TreeType; use pocketmine\block\utils\TreeType;
class Boat extends Item{ class Boat extends Item{
/** @var TreeType */ private TreeType $woodType;
private $woodType;
public function __construct(ItemIdentifier $identifier, string $name, TreeType $woodType){ public function __construct(ItemIdentifier $identifier, string $name, TreeType $woodType){
parent::__construct($identifier, $name); parent::__construct($identifier, $name);

View File

@ -32,8 +32,7 @@ abstract class Durable extends Item{
/** @var int */ /** @var int */
protected $damage = 0; protected $damage = 0;
/** @var bool */ private bool $unbreakable = false;
private $unbreakable = false;
public function getMeta() : int{ public function getMeta() : int{
return $this->damage; return $this->damage;

View File

@ -26,9 +26,7 @@ namespace pocketmine\item;
use pocketmine\block\utils\DyeColor; use pocketmine\block\utils\DyeColor;
class Dye extends Item{ class Dye extends Item{
private DyeColor $color;
/** @var DyeColor */
private $color;
public function __construct(ItemIdentifier $identifier, string $name, DyeColor $color){ public function __construct(ItemIdentifier $identifier, string $name, DyeColor $color){
parent::__construct($identifier, $name); parent::__construct($identifier, $name);

View File

@ -65,10 +65,9 @@ class Item implements \JsonSerializable{
public const TAG_DISPLAY_NAME = "Name"; public const TAG_DISPLAY_NAME = "Name";
public const TAG_DISPLAY_LORE = "Lore"; public const TAG_DISPLAY_LORE = "Lore";
/** @var ItemIdentifier */ private ItemIdentifier $identifier;
private $identifier; private CompoundTag $nbt;
/** @var CompoundTag */
private $nbt;
/** @var int */ /** @var int */
protected $count = 1; protected $count = 1;
/** @var string */ /** @var string */

View File

@ -33,8 +33,7 @@ use pocketmine\block\BlockFactory;
* just place wheat crops when used on the ground). * just place wheat crops when used on the ground).
*/ */
final class ItemBlock extends Item{ final class ItemBlock extends Item{
/** @var int */ private int $blockFullId;
private $blockFullId;
public function __construct(ItemIdentifier $identifier, Block $block){ public function __construct(ItemIdentifier $identifier, Block $block){
parent::__construct($identifier, $block->getName()); parent::__construct($identifier, $block->getName());

View File

@ -29,11 +29,8 @@ use pocketmine\math\Axis;
use pocketmine\math\Facing; use pocketmine\math\Facing;
class ItemBlockWallOrFloor extends Item{ class ItemBlockWallOrFloor extends Item{
private int $floorVariant;
/** @var int */ private int $wallVariant;
private $floorVariant;
/** @var int */
private $wallVariant;
public function __construct(ItemIdentifier $identifier, Block $floorVariant, Block $wallVariant){ public function __construct(ItemIdentifier $identifier, Block $floorVariant, Block $wallVariant){
parent::__construct($identifier, $floorVariant->getName()); parent::__construct($identifier, $floorVariant->getName());

View File

@ -55,7 +55,7 @@ class ItemFactory{
use SingletonTrait; use SingletonTrait;
/** @var Item[] */ /** @var Item[] */
private $list = []; private array $list = [];
public function __construct(){ public function __construct(){
$this->registerArmorItems(); $this->registerArmorItems();

View File

@ -24,11 +24,8 @@ declare(strict_types=1);
namespace pocketmine\item; namespace pocketmine\item;
final class ItemIdentifier{ final class ItemIdentifier{
private int $id;
/** @var int */ private int $meta;
private $id;
/** @var int */
private $meta;
public function __construct(int $id, int $meta){ public function __construct(int $id, int $meta){
if($id < -0x8000 || $id > 0x7fff){ //signed short range if($id < -0x8000 || $id > 0x7fff){ //signed short range

View File

@ -50,9 +50,6 @@ use function trim;
final class LegacyStringToItemParser{ final class LegacyStringToItemParser{
use SingletonTrait; use SingletonTrait;
/** @var ItemFactory */
private $itemFactory;
private static function make() : self{ private static function make() : self{
$result = new self(ItemFactory::getInstance()); $result = new self(ItemFactory::getInstance());
@ -73,11 +70,9 @@ final class LegacyStringToItemParser{
* @var int[] * @var int[]
* @phpstan-var array<string, int> * @phpstan-var array<string, int>
*/ */
private $map = []; private array $map = [];
public function __construct(ItemFactory $itemFactory){ public function __construct(private ItemFactory $itemFactory){}
$this->itemFactory = $itemFactory;
}
public function addMapping(string $alias, int $id) : void{ public function addMapping(string $alias, int $id) : void{
$this->map[$alias] = $id; $this->map[$alias] = $id;

View File

@ -31,9 +31,7 @@ use pocketmine\math\Vector3;
use pocketmine\player\Player; use pocketmine\player\Player;
class LiquidBucket extends Item{ class LiquidBucket extends Item{
private Liquid $liquid;
/** @var Liquid */
private $liquid;
public function __construct(ItemIdentifier $identifier, string $name, Liquid $liquid){ public function __construct(ItemIdentifier $identifier, string $name, Liquid $liquid){
parent::__construct($identifier, $name); parent::__construct($identifier, $name);

View File

@ -81,8 +81,6 @@ final class PotionType{
__construct as Enum___construct; __construct as Enum___construct;
} }
private string $displayName;
protected static function setup() : void{ protected static function setup() : void{
self::registerAll( self::registerAll(
new self("water", "Water", fn() => []), new self("water", "Water", fn() => []),
@ -204,16 +202,15 @@ final class PotionType{
); );
} }
/** @phpstan-var \Closure() : list<EffectInstance> */
private \Closure $effectsGetter;
/** /**
* @phpstan-param \Closure() : list<EffectInstance> $effectsGetter * @phpstan-param \Closure() : list<EffectInstance> $effectsGetter
*/ */
private function __construct(string $enumName, string $displayName, \Closure $effectsGetter){ private function __construct(
string $enumName,
private string $displayName,
private \Closure $effectsGetter
){
$this->Enum___construct($enumName); $this->Enum___construct($enumName);
$this->displayName = $displayName;
$this->effectsGetter = $effectsGetter;
} }
public function getDisplayName() : string{ return $this->displayName; } public function getDisplayName() : string{ return $this->displayName; }

View File

@ -26,9 +26,9 @@ namespace pocketmine\item;
use pocketmine\block\utils\RecordType; use pocketmine\block\utils\RecordType;
class Record extends Item{ class Record extends Item{
/** @var RecordType */ private RecordType $recordType;
private $recordType;
//TODO: inconsistent parameter order
public function __construct(ItemIdentifier $identifier, RecordType $recordType, string $name){ public function __construct(ItemIdentifier $identifier, RecordType $recordType, string $name){
$this->recordType = $recordType; $this->recordType = $recordType;
parent::__construct($identifier, $name); parent::__construct($identifier, $name);

View File

@ -28,9 +28,7 @@ use pocketmine\block\utils\SkullType;
use pocketmine\block\VanillaBlocks; use pocketmine\block\VanillaBlocks;
class Skull extends Item{ class Skull extends Item{
private SkullType $skullType;
/** @var SkullType */
private $skullType;
public function __construct(ItemIdentifier $identifier, string $name, SkullType $skullType){ public function __construct(ItemIdentifier $identifier, string $name, SkullType $skullType){
parent::__construct($identifier, $name); parent::__construct($identifier, $name);

View File

@ -869,7 +869,8 @@ final class StringToItemParser extends StringToTParser{
$result->registerBlock("stone_stairs", fn() => VanillaBlocks::STONE_STAIRS()); $result->registerBlock("stone_stairs", fn() => VanillaBlocks::STONE_STAIRS());
$result->registerBlock("stone_wall", fn() => VanillaBlocks::COBBLESTONE_WALL()); $result->registerBlock("stone_wall", fn() => VanillaBlocks::COBBLESTONE_WALL());
$result->registerBlock("stonebrick", fn() => VanillaBlocks::STONE_BRICKS()); $result->registerBlock("stonebrick", fn() => VanillaBlocks::STONE_BRICKS());
$result->registerBlock("stonecutter", fn() => VanillaBlocks::LEGACY_STONECUTTER()); $result->registerBlock("stonecutter", fn() => VanillaBlocks::STONECUTTER());
$result->registerBlock("stonecutter_block", fn() => VanillaBlocks::STONECUTTER());
$result->registerBlock("stripped_acacia_log", fn() => VanillaBlocks::STRIPPED_ACACIA_LOG()); $result->registerBlock("stripped_acacia_log", fn() => VanillaBlocks::STRIPPED_ACACIA_LOG());
$result->registerBlock("stripped_acacia_wood", fn() => VanillaBlocks::STRIPPED_ACACIA_WOOD()); $result->registerBlock("stripped_acacia_wood", fn() => VanillaBlocks::STRIPPED_ACACIA_WOOD());
$result->registerBlock("stripped_birch_log", fn() => VanillaBlocks::STRIPPED_BIRCH_LOG()); $result->registerBlock("stripped_birch_log", fn() => VanillaBlocks::STRIPPED_BIRCH_LOG());

View File

@ -52,21 +52,14 @@ final class ToolTier{
); );
} }
/** @var int */ private function __construct(
private $harvestLevel; string $name,
/** @var int */ private int $harvestLevel,
private $maxDurability; private int $maxDurability,
/** @var int */ private int $baseAttackPoints,
private $baseAttackPoints; private int $baseEfficiency
/** @var int */ ){
private $baseEfficiency;
private function __construct(string $name, int $harvestLevel, int $maxDurability, int $baseAttackPoints, int $baseEfficiency){
$this->Enum___construct($name); $this->Enum___construct($name);
$this->harvestLevel = $harvestLevel;
$this->maxDurability = $maxDurability;
$this->baseAttackPoints = $baseAttackPoints;
$this->baseEfficiency = $baseEfficiency;
} }
public function getHarvestLevel() : int{ public function getHarvestLevel() : int{

View File

@ -42,7 +42,7 @@ abstract class WritableBookBase extends Item{
* @var WritableBookPage[] * @var WritableBookPage[]
* @phpstan-var list<WritableBookPage> * @phpstan-var list<WritableBookPage>
*/ */
private $pages = []; private array $pages = [];
public function __construct(ItemIdentifier $identifier, string $name){ public function __construct(ItemIdentifier $identifier, string $name){
parent::__construct($identifier, $name); parent::__construct($identifier, $name);

View File

@ -32,10 +32,8 @@ class WritableBookPage{
public const PAGE_LENGTH_HARD_LIMIT_BYTES = Limits::INT16_MAX; public const PAGE_LENGTH_HARD_LIMIT_BYTES = Limits::INT16_MAX;
public const PHOTO_NAME_LENGTH_HARD_LIMIT_BYTES = Limits::INT16_MAX; public const PHOTO_NAME_LENGTH_HARD_LIMIT_BYTES = Limits::INT16_MAX;
/** @var string */ private string $text;
private $text; private string $photoName;
/** @var string */
private $photoName;
/** /**
* @throws \InvalidArgumentException * @throws \InvalidArgumentException

View File

@ -40,12 +40,9 @@ class WrittenBook extends WritableBookBase{
public const TAG_AUTHOR = "author"; //TAG_String public const TAG_AUTHOR = "author"; //TAG_String
public const TAG_TITLE = "title"; //TAG_String public const TAG_TITLE = "title"; //TAG_String
/** @var int */ private int $generation = self::GENERATION_ORIGINAL;
private $generation = self::GENERATION_ORIGINAL; private string $author = "";
/** @var string */ private string $title = "";
private $author = "";
/** @var string */
private $title = "";
public function getMaxStackSize() : int{ public function getMaxStackSize() : int{
return 16; return 16;

View File

@ -29,21 +29,10 @@ namespace pocketmine\item\enchantment;
* Note: This class is assumed to be immutable. Consider this before making alterations. * Note: This class is assumed to be immutable. Consider this before making alterations.
*/ */
final class EnchantmentInstance{ final class EnchantmentInstance{
/** @var Enchantment */ public function __construct(
private $enchantment; private Enchantment $enchantment,
/** @var int */ private int $level = 1
private $level; ){}
/**
* EnchantmentInstance constructor.
*
* @param Enchantment $enchantment Enchantment type
* @param int $level Level of enchantment
*/
public function __construct(Enchantment $enchantment, int $level = 1){
$this->enchantment = $enchantment;
$this->level = $level;
}
/** /**
* Returns the type of this enchantment. * Returns the type of this enchantment.

View File

@ -29,15 +29,10 @@ use function count;
final class BandwidthStatsTracker{ final class BandwidthStatsTracker{
/** @var int[] */ /** @var int[] */
private $history; private array $history;
/** @var int */ private int $nextHistoryIndex = 0;
private $nextHistoryIndex = 0; private int $bytesSinceLastRotation = 0;
private int $totalBytes = 0;
/** @var int */
private $bytesSinceLastRotation = 0;
/** @var int */
private $totalBytes = 0;
/** @phpstan-param positive-int $historySize */ /** @phpstan-param positive-int $historySize */
public function __construct(int $historySize){ public function __construct(int $historySize){

View File

@ -24,12 +24,8 @@ declare(strict_types=1);
namespace pocketmine\network; namespace pocketmine\network;
final class BidirectionalBandwidthStatsTracker{ final class BidirectionalBandwidthStatsTracker{
private BandwidthStatsTracker $send;
/** @var BandwidthStatsTracker */ private BandwidthStatsTracker $receive;
private $send;
/** @var BandwidthStatsTracker */
private $receive;
/** @phpstan-param positive-int $historySize */ /** @phpstan-param positive-int $historySize */
public function __construct(int $historySize){ public function __construct(int $historySize){

View File

@ -28,6 +28,7 @@ namespace pocketmine\network;
use pocketmine\event\server\NetworkInterfaceRegisterEvent; use pocketmine\event\server\NetworkInterfaceRegisterEvent;
use pocketmine\event\server\NetworkInterfaceUnregisterEvent; use pocketmine\event\server\NetworkInterfaceUnregisterEvent;
use pocketmine\utils\Utils;
use function base64_encode; use function base64_encode;
use function get_class; use function get_class;
use function preg_match; use function preg_match;
@ -37,32 +38,28 @@ use const PHP_INT_MAX;
class Network{ class Network{
/** @var NetworkInterface[] */ /** @var NetworkInterface[] */
private $interfaces = []; private array $interfaces = [];
/** @var AdvancedNetworkInterface[] */ /** @var AdvancedNetworkInterface[] */
private $advancedInterfaces = []; private array $advancedInterfaces = [];
/** @var RawPacketHandler[] */ /** @var RawPacketHandler[] */
private $rawPacketHandlers = []; private array $rawPacketHandlers = [];
/** @var int[] */ /**
private $bannedIps = []; * @var int[]
* @phpstan-var array<string, int>
*/
private array $bannedIps = [];
/** @var BidirectionalBandwidthStatsTracker */ private BidirectionalBandwidthStatsTracker $bandwidthTracker;
private $bandwidthTracker; private string $name;
private NetworkSessionManager$sessionManager;
/** @var string */ public function __construct(
private $name; private \Logger $logger
){
/** @var NetworkSessionManager */
private $sessionManager;
/** @var \Logger */
private $logger;
public function __construct(\Logger $logger){
$this->sessionManager = new NetworkSessionManager(); $this->sessionManager = new NetworkSessionManager();
$this->logger = $logger;
$this->bandwidthTracker = new BidirectionalBandwidthStatsTracker(5); $this->bandwidthTracker = new BidirectionalBandwidthStatsTracker(5);
} }
@ -103,7 +100,7 @@ class Network{
if($interface instanceof AdvancedNetworkInterface){ if($interface instanceof AdvancedNetworkInterface){
$this->advancedInterfaces[$hash] = $interface; $this->advancedInterfaces[$hash] = $interface;
$interface->setNetwork($this); $interface->setNetwork($this);
foreach($this->bannedIps as $ip => $until){ foreach(Utils::stringifyKeys($this->bannedIps) as $ip => $until){
$interface->blockAddress($ip); $interface->blockAddress($ip);
} }
foreach($this->rawPacketHandlers as $handler){ foreach($this->rawPacketHandlers as $handler){

View File

@ -30,7 +30,7 @@ use function spl_object_id;
class NetworkSessionManager{ class NetworkSessionManager{
/** @var NetworkSession[] */ /** @var NetworkSession[] */
private $sessions = []; private array $sessions = [];
/** /**
* Adds a network session to the manager. This should only be called on session creation. * Adds a network session to the manager. This should only be called on session creation.

View File

@ -49,8 +49,7 @@ class ChunkRequestTask extends AsyncTask{
/** @var Compressor */ /** @var Compressor */
protected $compressor; protected $compressor;
/** @var string */ private string $tiles;
private $tiles = "";
/** /**
* @phpstan-param (\Closure() : void)|null $onError * @phpstan-param (\Closure() : void)|null $onError

View File

@ -31,6 +31,7 @@ use pocketmine\block\inventory\EnchantInventory;
use pocketmine\block\inventory\FurnaceInventory; use pocketmine\block\inventory\FurnaceInventory;
use pocketmine\block\inventory\HopperInventory; use pocketmine\block\inventory\HopperInventory;
use pocketmine\block\inventory\LoomInventory; use pocketmine\block\inventory\LoomInventory;
use pocketmine\block\inventory\StonecutterInventory;
use pocketmine\crafting\FurnaceType; use pocketmine\crafting\FurnaceType;
use pocketmine\inventory\CreativeInventory; use pocketmine\inventory\CreativeInventory;
use pocketmine\inventory\Inventory; use pocketmine\inventory\Inventory;
@ -74,15 +75,9 @@ class InventoryManager{
private const RESERVED_WINDOW_ID_RANGE_START = ContainerIds::LAST - 10; private const RESERVED_WINDOW_ID_RANGE_START = ContainerIds::LAST - 10;
private const HARDCODED_INVENTORY_WINDOW_ID = self::RESERVED_WINDOW_ID_RANGE_START + 2; private const HARDCODED_INVENTORY_WINDOW_ID = self::RESERVED_WINDOW_ID_RANGE_START + 2;
/** @var Player */
private $player;
/** @var NetworkSession */
private $session;
/** @var Inventory[] */ /** @var Inventory[] */
private $windowMap = []; private array $windowMap = [];
/** @var int */ private int $lastInventoryNetworkId = ContainerIds::FIRST;
private $lastInventoryNetworkId = ContainerIds::FIRST;
/** /**
* TODO: HACK! This tracks GUIs for inventories that the server considers "always open" so that the client can't * TODO: HACK! This tracks GUIs for inventories that the server considers "always open" so that the client can't
@ -97,17 +92,16 @@ class InventoryManager{
* @var Item[][] * @var Item[][]
* @phpstan-var array<int, array<int, Item>> * @phpstan-var array<int, array<int, Item>>
*/ */
private $initiatedSlotChanges = []; private array $initiatedSlotChanges = [];
/** @var int */ private int $clientSelectedHotbarSlot = -1;
private $clientSelectedHotbarSlot = -1;
/** @phpstan-var ObjectSet<ContainerOpenClosure> */ /** @phpstan-var ObjectSet<ContainerOpenClosure> */
private ObjectSet $containerOpenCallbacks; private ObjectSet $containerOpenCallbacks;
public function __construct(Player $player, NetworkSession $session){ public function __construct(
$this->player = $player; private Player $player,
$this->session = $session; private NetworkSession $session
){
$this->containerOpenCallbacks = new ObjectSet(); $this->containerOpenCallbacks = new ObjectSet();
$this->containerOpenCallbacks->add(\Closure::fromCallable([self::class, 'createContainerOpen'])); $this->containerOpenCallbacks->add(\Closure::fromCallable([self::class, 'createContainerOpen']));
@ -210,6 +204,7 @@ class InventoryManager{
$inv instanceof AnvilInventory => WindowTypes::ANVIL, $inv instanceof AnvilInventory => WindowTypes::ANVIL,
$inv instanceof HopperInventory => WindowTypes::HOPPER, $inv instanceof HopperInventory => WindowTypes::HOPPER,
$inv instanceof CraftingTableInventory => WindowTypes::WORKBENCH, $inv instanceof CraftingTableInventory => WindowTypes::WORKBENCH,
$inv instanceof StonecutterInventory => WindowTypes::STONECUTTER,
default => WindowTypes::CONTAINER default => WindowTypes::CONTAINER
}; };
return [ContainerOpenPacket::blockInv($id, $windowType, $blockPosition)]; return [ContainerOpenPacket::blockInv($id, $windowType, $blockPosition)];

View File

@ -136,11 +136,7 @@ use const SORT_NUMERIC;
class NetworkSession{ class NetworkSession{
private \PrefixedLogger $logger; private \PrefixedLogger $logger;
private Server $server;
private ?Player $player = null; private ?Player $player = null;
private NetworkSessionManager $manager;
private string $ip;
private int $port;
private ?PlayerInfo $info = null; private ?PlayerInfo $info = null;
private ?int $ping = null; private ?int $ping = null;
@ -163,37 +159,31 @@ class NetworkSession{
* @phpstan-var \SplQueue<CompressBatchPromise> * @phpstan-var \SplQueue<CompressBatchPromise>
*/ */
private \SplQueue $compressedQueue; private \SplQueue $compressedQueue;
private Compressor $compressor;
private bool $forceAsyncCompression = true; private bool $forceAsyncCompression = true;
private PacketPool $packetPool;
private PacketSerializerContext $packetSerializerContext; private PacketSerializerContext $packetSerializerContext;
private ?InventoryManager $invManager = null; private ?InventoryManager $invManager = null;
private PacketSender $sender;
private PacketBroadcaster $broadcaster;
/** /**
* @var \Closure[]|ObjectSet * @var \Closure[]|ObjectSet
* @phpstan-var ObjectSet<\Closure() : void> * @phpstan-var ObjectSet<\Closure() : void>
*/ */
private ObjectSet $disposeHooks; private ObjectSet $disposeHooks;
public function __construct(Server $server, NetworkSessionManager $manager, PacketPool $packetPool, PacketSender $sender, PacketBroadcaster $broadcaster, Compressor $compressor, string $ip, int $port){ public function __construct(
$this->server = $server; private Server $server,
$this->manager = $manager; private NetworkSessionManager $manager,
$this->sender = $sender; private PacketPool $packetPool,
$this->broadcaster = $broadcaster; private PacketSender $sender,
$this->ip = $ip; private PacketBroadcaster $broadcaster,
$this->port = $port; private Compressor $compressor,
private string $ip,
private int $port
){
$this->logger = new \PrefixedLogger($this->server->getLogger(), $this->getLogPrefix()); $this->logger = new \PrefixedLogger($this->server->getLogger(), $this->getLogPrefix());
$this->compressedQueue = new \SplQueue(); $this->compressedQueue = new \SplQueue();
$this->compressor = $compressor;
$this->packetPool = $packetPool;
//TODO: allow this to be injected //TODO: allow this to be injected
$this->packetSerializerContext = new PacketSerializerContext(GlobalItemTypeDictionary::getInstance()->getDictionary()); $this->packetSerializerContext = new PacketSerializerContext(GlobalItemTypeDictionary::getInstance()->getDictionary());

View File

@ -28,13 +28,7 @@ use pocketmine\Server;
use function spl_object_id; use function spl_object_id;
final class StandardPacketBroadcaster implements PacketBroadcaster{ final class StandardPacketBroadcaster implements PacketBroadcaster{
public function __construct(private Server $server){}
/** @var Server */
private $server;
public function __construct(Server $server){
$this->server = $server;
}
public function broadcastPackets(array $recipients, array $packets) : void{ public function broadcastPackets(array $recipients, array $packets) : void{
$buffers = []; $buffers = [];

View File

@ -42,39 +42,33 @@ class ProcessLoginTask extends AsyncTask{
private const CLOCK_DRIFT_MAX = 60; private const CLOCK_DRIFT_MAX = 60;
/** @var string */ private string $chain;
private $chain;
/** @var string */
private $clientDataJwt;
/** /**
* @var string|null
* Whether the keychain signatures were validated correctly. This will be set to an error message if any link in the * Whether the keychain signatures were validated correctly. This will be set to an error message if any link in the
* keychain is invalid for whatever reason (bad signature, not in nbf-exp window, etc). If this is non-null, the * keychain is invalid for whatever reason (bad signature, not in nbf-exp window, etc). If this is non-null, the
* keychain might have been tampered with. The player will always be disconnected if this is non-null. * keychain might have been tampered with. The player will always be disconnected if this is non-null.
*/ */
private $error = "Unknown"; private ?string $error = "Unknown";
/** /**
* @var bool
* Whether the player is logged into Xbox Live. This is true if any link in the keychain is signed with the Mojang * Whether the player is logged into Xbox Live. This is true if any link in the keychain is signed with the Mojang
* root public key. * root public key.
*/ */
private $authenticated = false; private bool $authenticated = false;
/** @var bool */ private ?string $clientPublicKey = null;
private $authRequired;
/** @var string|null */
private $clientPublicKey = null;
/** /**
* @param string[] $chainJwts * @param string[] $chainJwts
* @phpstan-param \Closure(bool $isAuthenticated, bool $authRequired, ?string $error, ?string $clientPublicKey) : void $onCompletion * @phpstan-param \Closure(bool $isAuthenticated, bool $authRequired, ?string $error, ?string $clientPublicKey) : void $onCompletion
*/ */
public function __construct(array $chainJwts, string $clientDataJwt, bool $authRequired, \Closure $onCompletion){ public function __construct(
array $chainJwts,
private string $clientDataJwt,
private bool $authRequired,
\Closure $onCompletion
){
$this->storeLocal(self::TLS_KEY_ON_COMPLETION, $onCompletion); $this->storeLocal(self::TLS_KEY_ON_COMPLETION, $onCompletion);
$this->chain = igbinary_serialize($chainJwts); $this->chain = igbinary_serialize($chainJwts);
$this->clientDataJwt = $clientDataJwt;
$this->authRequired = $authRequired;
} }
public function onRun() : void{ public function onRun() : void{

View File

@ -39,7 +39,7 @@ use function strlen;
*/ */
class ChunkCache implements ChunkListener{ class ChunkCache implements ChunkListener{
/** @var self[][] */ /** @var self[][] */
private static $instances = []; private static array $instances = [];
/** /**
* Fetches the ChunkCache instance for the given world. This lazily creates cache systems as needed. * Fetches the ChunkCache instance for the given world. This lazily creates cache systems as needed.
@ -79,23 +79,16 @@ class ChunkCache implements ChunkListener{
} }
} }
/** @var World */
private $world;
/** @var Compressor */
private $compressor;
/** @var CompressBatchPromise[] */ /** @var CompressBatchPromise[] */
private $caches = []; private array $caches = [];
/** @var int */ private int $hits = 0;
private $hits = 0; private int $misses = 0;
/** @var int */
private $misses = 0;
private function __construct(World $world, Compressor $compressor){ private function __construct(
$this->world = $world; private World $world,
$this->compressor = $compressor; private Compressor $compressor
} ){}
/** /**
* Requests asynchronous preparation of the chunk at the given coordinates. * Requests asynchronous preparation of the chunk at the given coordinates.

View File

@ -25,6 +25,7 @@ namespace pocketmine\network\mcpe\cache;
use pocketmine\crafting\CraftingManager; use pocketmine\crafting\CraftingManager;
use pocketmine\crafting\FurnaceType; use pocketmine\crafting\FurnaceType;
use pocketmine\crafting\ShapelessRecipeType;
use pocketmine\item\Item; use pocketmine\item\Item;
use pocketmine\network\mcpe\convert\ItemTranslator; use pocketmine\network\mcpe\convert\ItemTranslator;
use pocketmine\network\mcpe\convert\TypeConverter; use pocketmine\network\mcpe\convert\TypeConverter;
@ -53,7 +54,7 @@ final class CraftingDataCache{
* @var CraftingDataPacket[] * @var CraftingDataPacket[]
* @phpstan-var array<int, CraftingDataPacket> * @phpstan-var array<int, CraftingDataPacket>
*/ */
private $caches = []; private array $caches = [];
public function getCache(CraftingManager $manager) : CraftingDataPacket{ public function getCache(CraftingManager $manager) : CraftingDataPacket{
$id = spl_object_id($manager); $id = spl_object_id($manager);
@ -81,6 +82,11 @@ final class CraftingDataCache{
$recipesWithTypeIds = []; $recipesWithTypeIds = [];
foreach($manager->getShapelessRecipes() as $list){ foreach($manager->getShapelessRecipes() as $list){
foreach($list as $recipe){ foreach($list as $recipe){
$typeTag = match($recipe->getType()->id()){
ShapelessRecipeType::CRAFTING()->id() => CraftingRecipeBlockName::CRAFTING_TABLE,
ShapelessRecipeType::STONECUTTER()->id() => CraftingRecipeBlockName::STONECUTTER,
default => throw new AssumptionFailedError("Unreachable"),
};
$recipesWithTypeIds[] = new ProtocolShapelessRecipe( $recipesWithTypeIds[] = new ProtocolShapelessRecipe(
CraftingDataPacket::ENTRY_SHAPELESS, CraftingDataPacket::ENTRY_SHAPELESS,
Binary::writeInt(++$counter), Binary::writeInt(++$counter),
@ -91,7 +97,7 @@ final class CraftingDataCache{
return $converter->coreItemStackToNet($item); return $converter->coreItemStackToNet($item);
}, $recipe->getResults()), }, $recipe->getResults()),
$nullUUID, $nullUUID,
CraftingRecipeBlockName::CRAFTING_TABLE, $typeTag,
50, 50,
$counter $counter
); );

View File

@ -34,11 +34,6 @@ use function file_get_contents;
class StaticPacketCache{ class StaticPacketCache{
use SingletonTrait; use SingletonTrait;
/** @var BiomeDefinitionListPacket */
private $biomeDefs;
/** @var AvailableActorIdentifiersPacket */
private $availableActorIdentifiers;
/** /**
* @phpstan-return CacheableNbt<\pocketmine\nbt\tag\CompoundTag> * @phpstan-return CacheableNbt<\pocketmine\nbt\tag\CompoundTag>
*/ */
@ -55,10 +50,10 @@ class StaticPacketCache{
); );
} }
public function __construct(BiomeDefinitionListPacket $biomeDefs, AvailableActorIdentifiersPacket $availableActorIdentifiers){ public function __construct(
$this->biomeDefs = $biomeDefs; private BiomeDefinitionListPacket $biomeDefs,
$this->availableActorIdentifiers = $availableActorIdentifiers; private AvailableActorIdentifiersPacket $availableActorIdentifiers
} ){}
public function getBiomeDefs() : BiomeDefinitionListPacket{ public function getBiomeDefs() : BiomeDefinitionListPacket{
return $this->biomeDefs; return $this->biomeDefs;

View File

@ -31,13 +31,11 @@ class CompressBatchPromise{
* @var \Closure[] * @var \Closure[]
* @phpstan-var (\Closure(self) : void)[] * @phpstan-var (\Closure(self) : void)[]
*/ */
private $callbacks = []; private array $callbacks = [];
/** @var string|null */ private ?string $result = null;
private $result = null;
/** @var bool */ private bool $cancelled = false;
private $cancelled = false;
/** /**
* @phpstan-param \Closure(self) : void ...$callbacks * @phpstan-param \Closure(self) : void ...$callbacks

View File

@ -29,14 +29,11 @@ class CompressBatchTask extends AsyncTask{
private const TLS_KEY_PROMISE = "promise"; private const TLS_KEY_PROMISE = "promise";
/** @var string */ public function __construct(
private $data; private string $data,
/** @var Compressor */ CompressBatchPromise $promise,
private $compressor; private Compressor $compressor
){
public function __construct(string $data, CompressBatchPromise $promise, Compressor $compressor){
$this->data = $data;
$this->compressor = $compressor;
$this->storeLocal(self::TLS_KEY_PROMISE, $promise); $this->storeLocal(self::TLS_KEY_PROMISE, $promise);
} }

View File

@ -46,21 +46,14 @@ final class ZlibCompressor implements Compressor{
return new self(self::DEFAULT_LEVEL, self::DEFAULT_THRESHOLD, self::DEFAULT_MAX_DECOMPRESSION_SIZE); return new self(self::DEFAULT_LEVEL, self::DEFAULT_THRESHOLD, self::DEFAULT_MAX_DECOMPRESSION_SIZE);
} }
/** @var int */ public function __construct(
private $level; private int $level,
/** @var int */ private int $minCompressionSize,
private $threshold; private int $maxDecompressionSize
/** @var int */ ){}
private $maxDecompressionSize;
public function __construct(int $level, int $minCompressionSize, int $maxDecompressionSize){
$this->level = $level;
$this->threshold = $minCompressionSize;
$this->maxDecompressionSize = $maxDecompressionSize;
}
public function willCompress(string $data) : bool{ public function willCompress(string $data) : bool{
return $this->threshold > -1 && strlen($data) >= $this->threshold; return $this->minCompressionSize > -1 && strlen($data) >= $this->minCompressionSize;
} }
/** /**

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