PocketMine-MP 5.23.3 git-f7687af337d001ddbcc47b8e773f014a33faa662
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_keys;
34use function array_values;
35use function assert;
36use function count;
37use function get_class;
38use function min;
39use function shuffle;
40use function spl_object_hash;
41use function spl_object_id;
42
59 protected bool $hasExecuted = false;
60
65 protected array $inventories = [];
66
71 protected array $actions = [];
72
76 public function __construct(
77 protected Player $source,
78 array $actions = []
79 ){
80 foreach($actions as $action){
81 $this->addAction($action);
82 }
83 }
84
85 public function getSource() : Player{
86 return $this->source;
87 }
88
93 public function getInventories() : array{
94 return $this->inventories;
95 }
96
106 public function getActions() : array{
107 return $this->actions;
108 }
109
110 public function addAction(InventoryAction $action) : void{
111 if(!isset($this->actions[$hash = spl_object_id($action)])){
112 $this->actions[$hash] = $action;
113 $action->onAddToTransaction($this);
114 if($action instanceof SlotChangeAction && !isset($this->inventories[$inventoryId = spl_object_id($action->getInventory())])){
115 $this->inventories[$inventoryId] = $action->getInventory();
116 }
117 }else{
118 throw new \InvalidArgumentException("Tried to add the same action to a transaction twice");
119 }
120 }
121
125 private function shuffleActions() : void{
126 $keys = array_keys($this->actions);
127 shuffle($keys);
128 $actions = [];
129 foreach($keys as $key){
130 $actions[$key] = $this->actions[$key];
131 }
132 $this->actions = $actions;
133 }
134
143 protected function matchItems(array &$needItems, array &$haveItems) : void{
144 $needItems = [];
145 $haveItems = [];
146 foreach($this->actions as $key => $action){
147 if(!$action->getTargetItem()->isNull()){
148 $needItems[] = $action->getTargetItem();
149 }
150
151 try{
152 $action->validate($this->source);
154 throw new TransactionValidationException(get_class($action) . "#" . spl_object_id($action) . ": " . $e->getMessage(), 0, $e);
155 }
156
157 if(!$action->getSourceItem()->isNull()){
158 $haveItems[] = $action->getSourceItem();
159 }
160 }
161
162 foreach($needItems as $i => $needItem){
163 foreach($haveItems as $j => $haveItem){
164 if($needItem->canStackWith($haveItem)){
165 $amount = min($needItem->getCount(), $haveItem->getCount());
166 $needItem->setCount($needItem->getCount() - $amount);
167 $haveItem->setCount($haveItem->getCount() - $amount);
168 if($haveItem->getCount() === 0){
169 unset($haveItems[$j]);
170 }
171 if($needItem->getCount() === 0){
172 unset($needItems[$i]);
173 break;
174 }
175 }
176 }
177 }
178 $needItems = array_values($needItems);
179 $haveItems = array_values($haveItems);
180 }
181
192 protected function squashDuplicateSlotChanges() : void{
193 $slotChanges = [];
194 $inventories = [];
195 $slots = [];
196
197 foreach($this->actions as $key => $action){
198 if($action instanceof SlotChangeAction){
199 $slotChanges[$h = (spl_object_hash($action->getInventory()) . "@" . $action->getSlot())][] = $action;
200 $inventories[$h] = $action->getInventory();
201 $slots[$h] = $action->getSlot();
202 }
203 }
204
205 foreach(Utils::stringifyKeys($slotChanges) as $hash => $list){
206 if(count($list) === 1){ //No need to compact slot changes if there is only one on this slot
207 continue;
208 }
209
210 $inventory = $inventories[$hash];
211 $slot = $slots[$hash];
212 if(!$inventory->slotExists($slot)){ //this can get hit for crafting tables because the validation happens after this compaction
213 throw new TransactionValidationException("Slot $slot does not exist in inventory " . get_class($inventory));
214 }
215 $sourceItem = $inventory->getItem($slot);
216
217 $targetItem = $this->findResultItem($sourceItem, $list);
218 if($targetItem === null){
219 throw new TransactionValidationException("Failed to compact " . count($list) . " duplicate actions");
220 }
221
222 foreach($list as $action){
223 unset($this->actions[spl_object_id($action)]);
224 }
225
226 if(!$targetItem->equalsExact($sourceItem)){
227 //sometimes we get actions on the crafting grid whose source and target items are the same, so dump them
228 $this->addAction(new SlotChangeAction($inventory, $slot, $sourceItem, $targetItem));
229 }
230 }
231 }
232
237 protected function findResultItem(Item $needOrigin, array $possibleActions) : ?Item{
238 assert(count($possibleActions) > 0);
239
240 $candidate = null;
241 $newList = $possibleActions;
242 foreach($possibleActions as $i => $action){
243 if($action->getSourceItem()->equalsExact($needOrigin)){
244 if($candidate !== null){
245 /*
246 * we found multiple possible actions that match the origin action
247 * this means that there are multiple ways that this chain could play out
248 * if we cared so much about this, we could build all the possible chains in parallel and see which
249 * variation managed to complete the chain, but this has an extremely high complexity which is not
250 * worth the trouble for this scenario (we don't usually expect to see chains longer than a couple
251 * of actions in here anyway), and might still result in multiple possible results.
252 */
253 return null;
254 }
255 $candidate = $action;
256 unset($newList[$i]);
257 }
258 }
259 if($candidate === null){
260 //chaining is not possible with this origin, none of the actions are valid
261 return null;
262 }
263
264 if(count($newList) === 0){
265 return $candidate->getTargetItem();
266 }
267 return $this->findResultItem($candidate->getTargetItem(), $newList);
268 }
269
275 public function validate() : void{
276 $this->squashDuplicateSlotChanges();
277
278 $haveItems = [];
279 $needItems = [];
280 $this->matchItems($needItems, $haveItems);
281 if(count($this->actions) === 0){
282 throw new TransactionValidationException("Inventory transaction must have at least one action to be executable");
283 }
284
285 if(count($haveItems) > 0){
286 throw new TransactionValidationException("Transaction does not balance (tried to destroy some items)");
287 }
288 if(count($needItems) > 0){
289 throw new TransactionValidationException("Transaction does not balance (tried to create some items)");
290 }
291 }
292
293 protected function callExecuteEvent() : bool{
294 $ev = new InventoryTransactionEvent($this);
295 $ev->call();
296 return !$ev->isCancelled();
297 }
298
304 public function execute() : void{
305 if($this->hasExecuted()){
306 throw new TransactionValidationException("Transaction has already been executed");
307 }
308
309 $this->shuffleActions();
310
311 $this->validate();
312
313 if(!$this->callExecuteEvent()){
314 throw new TransactionCancelledException("Transaction event cancelled");
315 }
316
317 foreach($this->actions as $action){
318 if(!$action->onPreExecute($this->source)){
319 throw new TransactionCancelledException("One of the actions in this transaction was cancelled");
320 }
321 }
322
323 foreach($this->actions as $action){
324 $action->execute($this->source);
325 }
326
327 $this->hasExecuted = true;
328 }
329
330 public function hasExecuted() : bool{
331 return $this->hasExecuted;
332 }
333}
findResultItem(Item $needOrigin, array $possibleActions)
__construct(protected Player $source, array $actions=[])
onAddToTransaction(InventoryTransaction $transaction)