From 5d4f14b3888f461799bec236148c209b029c0137 Mon Sep 17 00:00:00 2001 From: "Dylan K. Taylor" Date: Thu, 9 Sep 2021 17:10:04 +0100 Subject: [PATCH] Added TransactionBuilderInventory for server-side inventory transaction generation --- .../TransactionBuilderInventory.php | 106 ++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 src/inventory/transaction/TransactionBuilderInventory.php diff --git a/src/inventory/transaction/TransactionBuilderInventory.php b/src/inventory/transaction/TransactionBuilderInventory.php new file mode 100644 index 000000000..8888b4a45 --- /dev/null +++ b/src/inventory/transaction/TransactionBuilderInventory.php @@ -0,0 +1,106 @@ + + */ + private \SplFixedArray $changedSlots; + + public function __construct( + private Inventory $actualInventory + ){ + parent::__construct(); + $this->changedSlots = new \SplFixedArray($this->actualInventory->getSize()); + } + + protected function internalSetContents(array $items) : void{ + for($i = 0, $size = $this->getSize(); $i < $size; ++$i){ + if(!isset($items[$i])){ + $this->clear($i); + }else{ + $this->setItem($i, $items[$i]); + } + } + } + + protected function internalSetItem(int $index, Item $item) : void{ + if(!$item->equalsExact($this->actualInventory->getItem($index))){ + $this->changedSlots[$index] = $item->isNull() ? ItemFactory::air() : clone $item; + } + } + + public function getSize() : int{ + return $this->actualInventory->getSize(); + } + + public function getItem(int $index) : Item{ + return $this->changedSlots[$index] !== null ? clone $this->changedSlots[$index] : $this->actualInventory->getItem($index); + } + + public function getContents(bool $includeEmpty = false) : array{ + $contents = $this->actualInventory->getContents($includeEmpty); + foreach($this->changedSlots as $index => $item){ + if($item !== null){ + if($includeEmpty || !$item->isNull()){ + $contents[$index] = clone $item; + }else{ + unset($contents[$index]); + } + } + } + return $contents; + } + + /** + * @return SlotChangeAction[] + */ + public function generateActions() : array{ + $result = []; + foreach($this->changedSlots as $index => $newItem){ + if($newItem !== null){ + $oldItem = $this->actualInventory->getItem($index); + if(!$newItem->equalsExact($oldItem)){ + $result[] = new SlotChangeAction($this->actualInventory, $index, $oldItem, $newItem); + } + } + } + return $result; + } +}