PocketMine-MP 5.21.2 git-b2aa6396c3cc2cafdd815eacc360e1ad89599899
Loading...
Searching...
No Matches
ContainerTrait.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\block\tile;
25
35
41 private $lock = null;
42
43 abstract public function getRealInventory() : Inventory;
44
45 protected function loadItems(CompoundTag $tag) : void{
46 if(($inventoryTag = $tag->getTag(Container::TAG_ITEMS)) instanceof ListTag && $inventoryTag->getTagType() === NBT::TAG_Compound){
47 $inventory = $this->getRealInventory();
48 $listeners = $inventory->getListeners()->toArray();
49 $inventory->getListeners()->remove(...$listeners); //prevent any events being fired by initialization
50
51 $newContents = [];
53 foreach($inventoryTag as $itemNBT){
54 try{
55 $newContents[$itemNBT->getByte(SavedItemStackData::TAG_SLOT)] = Item::nbtDeserialize($itemNBT);
57 //TODO: not the best solution
58 \GlobalLogger::get()->logException($e);
59 continue;
60 }
61 }
62 $inventory->setContents($newContents);
63
64 $inventory->getListeners()->add(...$listeners);
65 }
66
67 if(($lockTag = $tag->getTag(Container::TAG_LOCK)) instanceof StringTag){
68 $this->lock = $lockTag->getValue();
69 }
70 }
71
72 protected function saveItems(CompoundTag $tag) : void{
73 $items = [];
74 foreach($this->getRealInventory()->getContents() as $slot => $item){
75 $items[] = $item->nbtSerialize($slot);
76 }
77
78 $tag->setTag(Container::TAG_ITEMS, new ListTag($items, NBT::TAG_Compound));
79
80 if($this->lock !== null){
81 $tag->setString(Container::TAG_LOCK, $this->lock);
82 }
83 }
84
88 public function canOpenWith(string $key) : bool{
89 return $this->lock === null || $this->lock === $key;
90 }
91
95 abstract protected function getPosition() : Position;
96
100 protected function onBlockDestroyedHook() : void{
101 $inv = $this->getRealInventory();
102 $pos = $this->getPosition();
103
104 $world = $pos->getWorld();
105 $dropPos = $pos->add(0.5, 0.5, 0.5);
106 foreach($inv->getContents() as $k => $item){
107 $world->dropItem($dropPos, $item);
108 }
109 $inv->clearAll();
110 }
111}
setString(string $name, string $value)
setTag(string $name, Tag $tag)