142 protected function matchItems(array &$needItems, array &$haveItems) : void{
145 foreach($this->actions as $key => $action){
146 if(!$action->getTargetItem()->isNull()){
147 $needItems[] = $action->getTargetItem();
151 $action->validate($this->source);
156 if(!$action->getSourceItem()->isNull()){
157 $haveItems[] = $action->getSourceItem();
161 foreach($needItems as $i => $needItem){
162 foreach($haveItems as $j => $haveItem){
163 if($needItem->canStackWith($haveItem)){
164 $amount = min($needItem->getCount(), $haveItem->getCount());
165 $needItem->setCount($needItem->getCount() - $amount);
166 $haveItem->setCount($haveItem->getCount() - $amount);
167 if($haveItem->getCount() === 0){
168 unset($haveItems[$j]);
170 if($needItem->getCount() === 0){
171 unset($needItems[$i]);
177 $needItems = array_values($needItems);
178 $haveItems = array_values($haveItems);
196 foreach($this->actions as $key => $action){
198 $slotChanges[$h = (spl_object_hash($action->getInventory()) .
"@" . $action->getSlot())][] = $action;
199 $inventories[$h] = $action->getInventory();
200 $slots[$h] = $action->getSlot();
204 foreach(Utils::stringifyKeys($slotChanges) as $hash => $list){
205 if(count($list) === 1){
209 $inventory = $inventories[$hash];
210 $slot = $slots[$hash];
211 if(!$inventory->slotExists($slot)){
214 $sourceItem = $inventory->getItem($slot);
216 $targetItem = $this->findResultItem($sourceItem, $list);
217 if($targetItem ===
null){
218 throw new TransactionValidationException(
"Failed to compact " . count($list) .
" duplicate actions");
221 foreach($list as $action){
222 unset($this->actions[spl_object_id($action)]);
225 if(!$targetItem->equalsExact($sourceItem)){
227 $this->addAction(
new SlotChangeAction($inventory, $slot, $sourceItem, $targetItem));
237 assert(count($possibleActions) > 0);
240 $newList = $possibleActions;
241 foreach($possibleActions as $i => $action){
242 if($action->getSourceItem()->equalsExact($needOrigin)){
243 if($candidate !==
null){
254 $candidate = $action;
258 if($candidate ===
null){
263 if(count($newList) === 0){
264 return $candidate->getTargetItem();
266 return $this->findResultItem($candidate->getTargetItem(), $newList);
304 if($this->hasExecuted()){
308 $this->shuffleActions();
312 if(!$this->callExecuteEvent()){
316 foreach($this->actions as $action){
317 if(!$action->onPreExecute($this->source)){
318 throw new TransactionCancelledException(
"One of the actions in this transaction was cancelled");
322 foreach($this->actions as $action){
323 $action->execute($this->source);
326 $this->hasExecuted =
true;