PocketMine-MP 5.15.1 git-be6754494fdbbb9dd57c058ba0e33a4a78c4581f
TransactionBuilderInventory.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
31
39
44 private \SplFixedArray $changedSlots;
45
46 public function __construct(
47 private Inventory $actualInventory
48 ){
49 parent::__construct();
50 $this->changedSlots = new \SplFixedArray($this->actualInventory->getSize());
51 }
52
53 public function getActualInventory() : Inventory{
54 return $this->actualInventory;
55 }
56
57 protected function internalSetContents(array $items) : void{
58 for($i = 0, $size = $this->getSize(); $i < $size; ++$i){
59 if(!isset($items[$i])){
60 $this->clear($i);
61 }else{
62 $this->setItem($i, $items[$i]);
63 }
64 }
65 }
66
67 protected function internalSetItem(int $index, Item $item) : void{
68 if(!$item->equalsExact($this->actualInventory->getItem($index))){
69 $this->changedSlots[$index] = $item->isNull() ? VanillaItems::AIR() : clone $item;
70 }
71 }
72
73 public function getSize() : int{
74 return $this->actualInventory->getSize();
75 }
76
77 public function getItem(int $index) : Item{
78 return $this->changedSlots[$index] !== null ? clone $this->changedSlots[$index] : $this->actualInventory->getItem($index);
79 }
80
81 public function getContents(bool $includeEmpty = false) : array{
82 $contents = $this->actualInventory->getContents($includeEmpty);
83 foreach($this->changedSlots as $index => $item){
84 if($item !== null){
85 if($includeEmpty || !$item->isNull()){
86 $contents[$index] = clone $item;
87 }else{
88 unset($contents[$index]);
89 }
90 }
91 }
92 return $contents;
93 }
94
98 public function generateActions() : array{
99 $result = [];
100 foreach($this->changedSlots as $index => $newItem){
101 if($newItem !== null){
102 $oldItem = $this->actualInventory->getItem($index);
103 if(!$newItem->equalsExact($oldItem)){
104 $result[] = new SlotChangeAction($this->actualInventory, $index, $oldItem, $newItem);
105 }
106 }
107 }
108 return $result;
109 }
110}
setItem(int $index, Item $item)