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