Promote some constructors

This commit is contained in:
Dylan K. Taylor 2022-05-17 22:34:58 +01:00
parent 8e767da29e
commit d4b7f66e15
No known key found for this signature in database
GPG Key ID: 8927471A91CAFD3D
30 changed files with 144 additions and 218 deletions

View File

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

View File

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

View File

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

View File

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

View File

@ -27,25 +27,18 @@ use pocketmine\block\tile\Tile;
use pocketmine\utils\Utils;
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
*/
public function __construct(int $blockId, int $variant, ?int $itemId = null, ?string $tileClass = null){
$this->blockId = $blockId;
$this->variant = $variant;
$this->itemId = $itemId;
public function __construct(
private int $blockId,
private int $variant,
private ?int $itemId = null,
private ?string $tileClass = null
){
if($tileClass !== null){
Utils::testValidInstance($tileClass, Tile::class);
}
$this->tileClass = $tileClass;
}
public function getBlockId() : int{

View File

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

View File

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

View File

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

View File

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

View File

@ -45,15 +45,14 @@ class FormattedCommandAlias extends Command{
*/
private const FORMAT_STRING_REGEX = '/\G\$(\$)?((?!0)+\d+)(-)?/';
/** @var string[] */
private array $formatStrings = [];
/**
* @param string[] $formatStrings
*/
public function __construct(string $alias, array $formatStrings){
public function __construct(
string $alias,
private array $formatStrings
){
parent::__construct($alias);
$this->formatStrings = $formatStrings;
}
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\plugin\Plugin;
use pocketmine\plugin\PluginOwned;
use pocketmine\plugin\PluginOwnedTrait;
final class PluginCommand extends Command implements PluginOwned{
use PluginOwnedTrait;
private CommandExecutor $executor;
public function __construct(string $name, Plugin $owner, CommandExecutor $executor){
public function __construct(
string $name,
private Plugin $owner,
private CommandExecutor $executor
){
parent::__construct($name);
$this->owningPlugin = $owner;
$this->executor = $executor;
$this->usageMessage = "";
}
public function execute(CommandSender $sender, string $commandLabel, array $args){
if(!$this->owningPlugin->isEnabled()){
if(!$this->owner->isEnabled()){
return false;
}
@ -59,6 +56,10 @@ final class PluginCommand extends Command implements PluginOwned{
return $success;
}
public function getOwningPlugin() : Plugin{
return $this->owner;
}
public function getExecutor() : CommandExecutor{
return $this->executor;
}

View File

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

View File

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

View File

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

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.
*/
class DelegateInventory extends BaseInventory{
private Inventory $backingInventory;
private InventoryListener $inventoryListener;
public function __construct(Inventory $backingInventory){
public function __construct(
private Inventory $backingInventory
){
parent::__construct();
$this->backingInventory = $backingInventory;
$this->backingInventory->getListeners()->add($this->inventoryListener = new CallbackInventoryListener(
function(Inventory $unused, int $slot, Item $oldItem) : void{
$this->onSlotChange($slot, $oldItem);

View File

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

View File

@ -81,8 +81,6 @@ final class PotionType{
__construct as Enum___construct;
}
private string $displayName;
protected static function setup() : void{
self::registerAll(
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
*/
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->displayName = $displayName;
$this->effectsGetter = $effectsGetter;
}
public function getDisplayName() : string{ return $this->displayName; }

View File

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

View File

@ -56,11 +56,9 @@ final class GlobalItemTypeDictionary{
return new self(new ItemTypeDictionary($params));
}
private ItemTypeDictionary $dictionary;
public function __construct(ItemTypeDictionary $dictionary){
$this->dictionary = $dictionary;
}
public function __construct(
private ItemTypeDictionary $dictionary
){}
public function getDictionary() : ItemTypeDictionary{ return $this->dictionary; }
}

View File

@ -27,13 +27,10 @@ use pocketmine\snooze\SleeperNotifier;
use raklib\server\ipc\InterThreadChannelWriter;
final class SnoozeAwarePthreadsChannelWriter implements InterThreadChannelWriter{
private \Threaded $buffer;
private SleeperNotifier $notifier;
public function __construct(\Threaded $buffer, SleeperNotifier $notifier){
$this->buffer = $buffer;
$this->notifier = $notifier;
}
public function __construct(
private \Threaded $buffer,
private SleeperNotifier $notifier
){}
public function write(string $str) : void{
$this->buffer[] = $str;

View File

@ -66,19 +66,15 @@ final class PluginEnableOrder{
return self::$aliasMap[mb_strtolower($name)] ?? null;
}
/**
* @var string[]
* @phpstan-var list<string>
*/
private array $aliases;
/**
* @param string[] $aliases
* @phpstan-param list<string> $aliases
*/
private function __construct(string $enumName, array $aliases){
private function __construct(
string $enumName,
private array $aliases
){
$this->Enum___construct($enumName);
$this->aliases = $aliases;
}
/**

View File

@ -30,18 +30,11 @@ use Webmozart\PathUtil\Path;
* Task used to dump memory from AsyncWorkers
*/
class DumpWorkerMemoryTask extends AsyncTask{
/** @var string */
private $outputFolder;
/** @var int */
private $maxNesting;
/** @var int */
private $maxStringSize;
public function __construct(string $outputFolder, int $maxNesting, int $maxStringSize){
$this->outputFolder = $outputFolder;
$this->maxNesting = $maxNesting;
$this->maxStringSize = $maxStringSize;
}
public function __construct(
private string $outputFolder,
private int $maxNesting,
private int $maxStringSize
){}
public function onRun() : void{
MemoryManager::dumpMemory(

View File

@ -32,17 +32,14 @@ use function json_decode;
class UpdateCheckTask extends AsyncTask{
private const TLS_KEY_UPDATER = "updater";
/** @var string */
private $endpoint;
/** @var string */
private $channel;
/** @var string */
private $error = "Unknown error";
private string $error = "Unknown error";
public function __construct(UpdateChecker $updater, string $endpoint, string $channel){
public function __construct(
UpdateChecker $updater,
private string $endpoint,
private string $channel
){
$this->storeLocal(self::TLS_KEY_UPDATER, $updater);
$this->endpoint = $endpoint;
$this->channel = $channel;
}
public function onRun() : void{

View File

@ -35,19 +35,11 @@ class MainLogger extends \AttachableThreadedLogger implements \BufferedLogger{
/** @var bool */
protected $logDebug;
/** @var string */
private $format = TextFormat::AQUA . "[%s] " . TextFormat::RESET . "%s[%s/%s]: %s" . TextFormat::RESET;
/** @var bool */
private $useFormattingCodes = false;
private string $format = TextFormat::AQUA . "[%s] " . TextFormat::RESET . "%s[%s/%s]: %s" . TextFormat::RESET;
private bool $useFormattingCodes = false;
private string $mainThreadName;
/** @var string */
private $timezone;
/** @var MainLoggerThread */
private $logWriterThread;
private string $timezone;
private MainLoggerThread $logWriterThread;
/**
* @throws \RuntimeException

View File

@ -30,16 +30,15 @@ use function is_resource;
use function touch;
final class MainLoggerThread extends \Thread{
private string $logFile;
private \Threaded $buffer;
private bool $syncFlush = false;
private bool $shutdown = false;
public function __construct(string $logFile){
public function __construct(
private string $logFile
){
$this->buffer = new \Threaded();
touch($logFile);
$this->logFile = $logFile;
touch($this->logFile);
}
public function write(string $line) : void{

View File

@ -28,13 +28,12 @@ namespace pocketmine\world\format\io;
*/
class ReadOnlyWorldProviderManagerEntry extends WorldProviderManagerEntry{
/** @phpstan-var FromPath */
private \Closure $fromPath;
/** @phpstan-param FromPath $fromPath */
public function __construct(\Closure $isValid, \Closure $fromPath){
public function __construct(
\Closure $isValid,
private \Closure $fromPath
){
parent::__construct($isValid);
$this->fromPath = $fromPath;
}
public function fromPath(string $path) : WorldProvider{ return ($this->fromPath)($path); }

View File

@ -31,13 +31,10 @@ use pocketmine\world\format\io\exception\UnsupportedWorldFormatException;
*/
abstract class WorldProviderManagerEntry{
/** @phpstan-var IsValid */
protected \Closure $isValid;
/** @phpstan-param IsValid $isValid */
protected function __construct(\Closure $isValid){
$this->isValid = $isValid;
}
protected function __construct(
protected \Closure $isValid
){}
/**
* Tells if the path is a valid world.

View File

@ -30,19 +30,17 @@ use pocketmine\world\WorldCreationOptions;
* @phpstan-type Generate \Closure(string $path, string $name, WorldCreationOptions $options) : void
*/
final class WritableWorldProviderManagerEntry extends WorldProviderManagerEntry{
/** @phpstan-var FromPath */
private \Closure $fromPath;
/** @phpstan-var Generate */
private \Closure $generate;
/**
* @phpstan-param FromPath $fromPath
* @phpstan-param Generate $generate
*/
public function __construct(\Closure $isValid, \Closure $fromPath, \Closure $generate){
public function __construct(
\Closure $isValid,
private \Closure $fromPath,
private \Closure $generate
){
parent::__construct($isValid);
$this->fromPath = $fromPath;
$this->generate = $generate;
}
public function fromPath(string $path) : WritableWorldProvider{

View File

@ -26,13 +26,10 @@ namespace pocketmine\world\generator;
use function exp;
final class Gaussian{
public int $smoothSize;
/** @var float[][] */
public array $kernel = [];
public function __construct(int $smoothSize){
$this->smoothSize = $smoothSize;
public function __construct(public int $smoothSize){
$bellSize = 1 / $this->smoothSize;
$bellHeight = 2 * $this->smoothSize;

View File

@ -41,10 +41,6 @@ use function igbinary_unserialize;
class PopulationTask extends AsyncTask{
private const TLS_KEY_ON_COMPLETION = "onCompletion";
private int $worldId;
private int $chunkX;
private int $chunkZ;
private ?string $chunk;
private string $adjacentChunks;
@ -54,10 +50,14 @@ class PopulationTask extends AsyncTask{
* @phpstan-param array<int, Chunk|null> $adjacentChunks
* @phpstan-param OnCompletion $onCompletion
*/
public function __construct(int $worldId, int $chunkX, int $chunkZ, ?Chunk $chunk, array $adjacentChunks, \Closure $onCompletion){
$this->worldId = $worldId;
$this->chunkX = $chunkX;
$this->chunkZ = $chunkZ;
public function __construct(
private int $worldId,
private int $chunkX,
private int $chunkZ,
?Chunk $chunk,
array $adjacentChunks,
\Closure $onCompletion
){
$this->chunk = $chunk !== null ? FastChunkSerializer::serializeTerrain($chunk) : null;
$this->adjacentChunks = igbinary_serialize(array_map(