PocketMine-MP 5.23.3 git-976fc63567edab7a6fb6aeae739f43cf9fe57de4
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 if(!$action->getTargetItem()->isNull()){
147 $needItems[] = $action->getTargetItem();
148 }
149
150 try{
151 $action->validate($this->source);
153 throw new TransactionValidationException(get_class($action) . "#" . spl_object_id($action) . ": " . $e->getMessage(), 0, $e);
154 }
155
156 if(!$action->getSourceItem()->isNull()){
157 $haveItems[] = $action->getSourceItem();
158 }
159 }
160
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]);
169 }
170 if($needItem->getCount() === 0){
171 unset($needItems[$i]);
172 break;
173 }
174 }
175 }
176 }
177 $needItems = array_values($needItems);
178 $haveItems = array_values($haveItems);
179 }
180
191 protected function squashDuplicateSlotChanges() : void{
192 $slotChanges = [];
193 $inventories = [];
194 $slots = [];
195
196 foreach($this->actions as $key => $action){
197 if($action instanceof SlotChangeAction){
198 $slotChanges[$h = (spl_object_hash($action->getInventory()) . "@" . $action->getSlot())][] = $action;
199 $inventories[$h] = $action->getInventory();
200 $slots[$h] = $action->getSlot();
201 }
202 }
203
204 foreach(Utils::stringifyKeys($slotChanges) as $hash => $list){
205 if(count($list) === 1){ //No need to compact slot changes if there is only one on this slot
206 continue;
207 }
208
209 $inventory = $inventories[$hash];
210 $slot = $slots[$hash];
211 if(!$inventory->slotExists($slot)){ //this can get hit for crafting tables because the validation happens after this compaction
212 throw new TransactionValidationException("Slot $slot does not exist in inventory " . get_class($inventory));
213 }
214 $sourceItem = $inventory->getItem($slot);
215
216 $targetItem = $this->findResultItem($sourceItem, $list);
217 if($targetItem === null){
218 throw new TransactionValidationException("Failed to compact " . count($list) . " duplicate actions");
219 }
220
221 foreach($list as $action){
222 unset($this->actions[spl_object_id($action)]);
223 }
224
225 if(!$targetItem->equalsExact($sourceItem)){
226 //sometimes we get actions on the crafting grid whose source and target items are the same, so dump them
227 $this->addAction(new SlotChangeAction($inventory, $slot, $sourceItem, $targetItem));
228 }
229 }
230 }
231
236 protected function findResultItem(Item $needOrigin, array $possibleActions) : ?Item{
237 assert(count($possibleActions) > 0);
238
239 $candidate = null;
240 $newList = $possibleActions;
241 foreach($possibleActions as $i => $action){
242 if($action->getSourceItem()->equalsExact($needOrigin)){
243 if($candidate !== null){
244 /*
245 * we found multiple possible actions that match the origin action
246 * this means that there are multiple ways that this chain could play out
247 * if we cared so much about this, we could build all the possible chains in parallel and see which
248 * variation managed to complete the chain, but this has an extremely high complexity which is not
249 * worth the trouble for this scenario (we don't usually expect to see chains longer than a couple
250 * of actions in here anyway), and might still result in multiple possible results.
251 */
252 return null;
253 }
254 $candidate = $action;
255 unset($newList[$i]);
256 }
257 }
258 if($candidate === null){
259 //chaining is not possible with this origin, none of the actions are valid
260 return null;
261 }
262
263 if(count($newList) === 0){
264 return $candidate->getTargetItem();
265 }
266 return $this->findResultItem($candidate->getTargetItem(), $newList);
267 }
268
274 public function validate() : void{
275 $this->squashDuplicateSlotChanges();
276
277 $haveItems = [];
278 $needItems = [];
279 $this->matchItems($needItems, $haveItems);
280 if(count($this->actions) === 0){
281 throw new TransactionValidationException("Inventory transaction must have at least one action to be executable");
282 }
283
284 if(count($haveItems) > 0){
285 throw new TransactionValidationException("Transaction does not balance (tried to destroy some items)");
286 }
287 if(count($needItems) > 0){
288 throw new TransactionValidationException("Transaction does not balance (tried to create some items)");
289 }
290 }
291
292 protected function callExecuteEvent() : bool{
293 $ev = new InventoryTransactionEvent($this);
294 $ev->call();
295 return !$ev->isCancelled();
296 }
297
303 public function execute() : void{
304 if($this->hasExecuted()){
305 throw new TransactionValidationException("Transaction has already been executed");
306 }
307
308 $this->shuffleActions();
309
310 $this->validate();
311
312 if(!$this->callExecuteEvent()){
313 throw new TransactionCancelledException("Transaction event cancelled");
314 }
315
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");
319 }
320 }
321
322 foreach($this->actions as $action){
323 $action->execute($this->source);
324 }
325
326 $this->hasExecuted = true;
327 }
328
329 public function hasExecuted() : bool{
330 return $this->hasExecuted;
331 }
332}
findResultItem(Item $needOrigin, array $possibleActions)
__construct(protected Player $source, array $actions=[])