PocketMine-MP 5.35.1 git-d241807752ab518f2ffc7e3b71f6a72f9cdf0c30
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
36
42 private $lock = null;
43
44 abstract public function getRealInventory() : Inventory;
45
46 protected function loadItems(CompoundTag $tag) : void{
47 try{
48 $inventoryTag = $tag->getListTag(Container::TAG_ITEMS, CompoundTag::class);
50 //preserve the old behaviour of not throwing on wrong types
51 $inventoryTag = null;
52 }
53 if($inventoryTag !== null){
54 $inventory = $this->getRealInventory();
55 $listeners = $inventory->getListeners()->toArray();
56 $inventory->getListeners()->remove(...$listeners); //prevent any events being fired by initialization
57
58 $newContents = [];
59 foreach($inventoryTag as $itemNBT){
60 try{
61 $newContents[$itemNBT->getByte(SavedItemStackData::TAG_SLOT)] = Item::nbtDeserialize($itemNBT);
63 //TODO: not the best solution
64 \GlobalLogger::get()->logException($e);
65 continue;
66 }
67 }
68 $inventory->setContents($newContents);
69
70 $inventory->getListeners()->add(...$listeners);
71 }
72
73 if(($lockTag = $tag->getTag(Container::TAG_LOCK)) instanceof StringTag){
74 $this->lock = $lockTag->getValue();
75 }
76 }
77
78 protected function saveItems(CompoundTag $tag) : void{
79 $items = [];
80 foreach($this->getRealInventory()->getContents() as $slot => $item){
81 $items[] = $item->nbtSerialize($slot);
82 }
83
84 $tag->setTag(Container::TAG_ITEMS, new ListTag($items, NBT::TAG_Compound));
85
86 if($this->lock !== null){
87 $tag->setString(Container::TAG_LOCK, $this->lock);
88 }
89 }
90
94 public function canOpenWith(string $key) : bool{
95 return $this->lock === null || $this->lock === $key;
96 }
97
101 abstract protected function getPosition() : Position;
102
106 protected function onBlockDestroyedHook() : void{
107 $inv = $this->getRealInventory();
108 $pos = $this->getPosition();
109
110 $world = $pos->getWorld();
111 $dropPos = $pos->add(0.5, 0.5, 0.5);
112 foreach($inv->getContents() as $k => $item){
113 $world->dropItem($dropPos, $item);
114 }
115 $inv->clearAll();
116 }
117}
setString(string $name, string $value)
setTag(string $name, Tag $tag)
getListTag(string $name, string $tagClass=Tag::class)