PocketMine-MP 5.35.1 git-05a71d8cc5185aa9e46ef5f9754bb862464c13e0
Loading...
Searching...
No Matches
InventoryTransaction.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
24namespace pocketmine\inventory\transaction;
25
33use function array_values;
34use function assert;
35use function count;
36use function get_class;
37use function min;
38use function spl_object_hash;
39use function spl_object_id;
40
57 protected bool $hasExecuted = false;
58
63 protected array $inventories = [];
64
69 protected array $actions = [];
70
74 public function __construct(
75 protected Player $source,
76 array $actions = []
77 ){
78 foreach($actions as $action){
79 $this->addAction($action);
80 }
81 }
82
83 public function getSource() : Player{
84 return $this->source;
85 }
86
91 public function getInventories() : array{
92 return $this->inventories;
93 }
94
107 public function getActions() : array{
108 return $this->actions;
109 }
110
111 public function addAction(InventoryAction $action) : void{
112 if(!isset($this->actions[$hash = spl_object_id($action)])){
113 $this->actions[$hash] = $action;
114 $action->onAddToTransaction($this);
115 if($action instanceof SlotChangeAction && !isset($this->inventories[$inventoryId = spl_object_id($action->getInventory())])){
116 $this->inventories[$inventoryId] = $action->getInventory();
117 }
118 }else{
119 throw new \InvalidArgumentException("Tried to add the same action to a transaction twice");
120 }
121 }
122
131 protected function matchItems(array &$needItems, array &$haveItems) : void{
132 $needItems = [];
133 $haveItems = [];
134 foreach($this->actions as $key => $action){
135 $targetItem = $action->getTargetItem();
136 if(!$targetItem->isNull()){
137 $needItems[] = $targetItem;
138 }
139
140 try{
141 $action->validate($this->source);
143 throw new TransactionValidationException(get_class($action) . "#" . spl_object_id($action) . ": " . $e->getMessage(), 0, $e);
144 }
145
146 $sourceItem = $action->getSourceItem();
147 if(!$sourceItem->isNull()){
148 $haveItems[] = $sourceItem;
149 }
150 }
151
152 foreach($needItems as $i => $needItem){
153 foreach($haveItems as $j => $haveItem){
154 if($needItem->canStackWith($haveItem)){
155 $amount = min($needItem->getCount(), $haveItem->getCount());
156 $needItem->setCount($needItem->getCount() - $amount);
157 $haveItem->setCount($haveItem->getCount() - $amount);
158 if($haveItem->getCount() === 0){
159 unset($haveItems[$j]);
160 }
161 if($needItem->getCount() === 0){
162 unset($needItems[$i]);
163 break;
164 }
165 }
166 }
167 }
168 $needItems = array_values($needItems);
169 $haveItems = array_values($haveItems);
170 }
171
182 protected function squashDuplicateSlotChanges() : void{
183 $slotChanges = [];
184 $inventories = [];
185 $slots = [];
186
187 foreach($this->actions as $key => $action){
188 if($action instanceof SlotChangeAction){
189 $slotChanges[$h = (spl_object_hash($action->getInventory()) . "@" . $action->getSlot())][] = $action;
190 $inventories[$h] = $action->getInventory();
191 $slots[$h] = $action->getSlot();
192 }
193 }
194
195 foreach(Utils::stringifyKeys($slotChanges) as $hash => $list){
196 if(count($list) === 1){ //No need to compact slot changes if there is only one on this slot
197 continue;
198 }
199
200 $inventory = $inventories[$hash];
201 $slot = $slots[$hash];
202 if(!$inventory->slotExists($slot)){ //this can get hit for crafting tables because the validation happens after this compaction
203 throw new TransactionValidationException("Slot $slot does not exist in inventory " . get_class($inventory));
204 }
205 $sourceItem = $inventory->getItem($slot);
206
207 $targetItem = $this->findResultItem($sourceItem, $list);
208 if($targetItem === null){
209 throw new TransactionValidationException("Failed to compact " . count($list) . " duplicate actions");
210 }
211
212 foreach($list as $action){
213 unset($this->actions[spl_object_id($action)]);
214 }
215
216 if(!$targetItem->equalsExact($sourceItem)){
217 //sometimes we get actions on the crafting grid whose source and target items are the same, so dump them
218 $this->addAction(new SlotChangeAction($inventory, $slot, $sourceItem, $targetItem));
219 }
220 }
221 }
222
227 protected function findResultItem(Item $needOrigin, array $possibleActions) : ?Item{
228 assert(count($possibleActions) > 0);
229
230 $candidate = null;
231 $newList = $possibleActions;
232 foreach($possibleActions as $i => $action){
233 if($action->getSourceItem()->equalsExact($needOrigin)){
234 if($candidate !== null){
235 /*
236 * we found multiple possible actions that match the origin action
237 * this means that there are multiple ways that this chain could play out
238 * if we cared so much about this, we could build all the possible chains in parallel and see which
239 * variation managed to complete the chain, but this has an extremely high complexity which is not
240 * worth the trouble for this scenario (we don't usually expect to see chains longer than a couple
241 * of actions in here anyway), and might still result in multiple possible results.
242 */
243 return null;
244 }
245 $candidate = $action;
246 unset($newList[$i]);
247 }
248 }
249 if($candidate === null){
250 //chaining is not possible with this origin, none of the actions are valid
251 return null;
252 }
253
254 if(count($newList) === 0){
255 return $candidate->getTargetItem();
256 }
257 return $this->findResultItem($candidate->getTargetItem(), $newList);
258 }
259
265 public function validate() : void{
266 $this->squashDuplicateSlotChanges();
267
268 $haveItems = [];
269 $needItems = [];
270 $this->matchItems($needItems, $haveItems);
271 if(count($this->actions) === 0){
272 throw new TransactionValidationException("Inventory transaction must have at least one action to be executable");
273 }
274
275 if(count($haveItems) > 0){
276 throw new TransactionValidationException("Transaction does not balance (tried to destroy some items)");
277 }
278 if(count($needItems) > 0){
279 throw new TransactionValidationException("Transaction does not balance (tried to create some items)");
280 }
281 }
282
283 protected function callExecuteEvent() : bool{
284 $ev = new InventoryTransactionEvent($this);
285 $ev->call();
286 return !$ev->isCancelled();
287 }
288
294 public function execute() : void{
295 if($this->hasExecuted()){
296 throw new TransactionValidationException("Transaction has already been executed");
297 }
298
299 $this->validate();
300
301 if(!$this->callExecuteEvent()){
302 throw new TransactionCancelledException("Transaction event cancelled");
303 }
304
305 foreach($this->actions as $action){
306 if(!$action->onPreExecute($this->source)){
307 throw new TransactionCancelledException("One of the actions in this transaction was cancelled");
308 }
309 }
310
311 foreach($this->actions as $action){
312 $action->execute($this->source);
313 }
314
315 $this->hasExecuted = true;
316 }
317
318 public function hasExecuted() : bool{
319 return $this->hasExecuted;
320 }
321}
findResultItem(Item $needOrigin, array $possibleActions)
__construct(protected Player $source, array $actions=[])
onAddToTransaction(InventoryTransaction $transaction)