creationTime = microtime(true); $this->source = $source; } /** * @return Player */ public function getSource(){ return $this->source; } public function getCreationTime(){ return $this->creationTime; } public function getInventories(){ return $this->inventories; } public function getTransactions(){ return $this->transactions; } public function addTransaction(Transaction $transaction){ if(isset($this->transactions[spl_object_hash($transaction)])){ return; } foreach($this->transactions as $hash => $tx){ if($tx->getInventory() === $transaction->getInventory() and $tx->getSlot() === $transaction->getSlot()){ if($transaction->getCreationTime() >= $tx->getCreationTime()){ unset($this->transactions[$hash]); }else{ return; } } } $this->transactions[spl_object_hash($transaction)] = $transaction; $this->inventories[spl_object_hash($transaction->getInventory())] = $transaction->getInventory(); } /** * @param Item[] $needItems * @param Item[] $haveItems */ protected function matchItems(array &$needItems, array &$haveItems){ foreach($this->transactions as $key => $ts){ if($ts->getTargetItem()->getID() !== Item::AIR){ $needItems[] = $ts->getTargetItem(); } $checkSourceItem = $ts->getInventory()->getItem($ts->getSlot()); $sourceItem = $ts->getSourceItem(); if(!$checkSourceItem->equals($sourceItem, true) or $sourceItem->getCount() !== $checkSourceItem->getCount()){ return false; } if($sourceItem->getID() !== Item::AIR){ $haveItems[] = $sourceItem; } } foreach($needItems as $i => $needItem){ foreach($haveItems as $j => $haveItem){ if($needItem->equals($haveItem, true)){ $amount = min($needItem->getCount(), $haveItem->getCount()); $needItem->setCount($needItem->getCount() - $amount); $haveItem->setCount($haveItem->getCount() - $amount); if($haveItem->getCount() === 0){ unset($haveItems[$j]); } if($needItem->getCount() === 0){ unset($needItems[$i]); break; } } } } } public function canExecute(){ $haveItems = []; $needItems = []; $this->matchItems($haveItems, $needItems); return count($haveItems) === 0 and count($needItems) === 0 and count($this->transactions) > 0; } public function execute(){ if($this->hasExecuted() or !$this->canExecute()){ return false; } Server::getInstance()->getPluginManager()->callEvent($ev = new InventoryTransactionEvent($this)); if($ev->isCancelled()){ foreach($this->inventories as $inventory){ $inventory->sendContents($inventory->getViewers()); } return false; } foreach($this->transactions as $transaction){ $transaction->getInventory()->setItem($transaction->getSlot(), $transaction->getTargetItem(), $this->getSource()); } $this->hasExecuted = true; return true; } public function hasExecuted(){ return $this->hasExecuted; } }