PocketMine-MP 5.35.1 git-e32e836dad793a3a3c8ddd8927c00e112b1e576a
Loading...
Searching...
No Matches
ContainerTileTrait.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 try{
47 $inventoryTag = $tag->getListTag(ContainerTile::TAG_ITEMS, CompoundTag::class);
49 //preserve the old behaviour of not throwing on wrong types
50 $inventoryTag = null;
51 }
52 if($inventoryTag !== null){
53 $inventory = $this->getRealInventory();
54 $listeners = $inventory->getListeners()->toArray();
55 $inventory->getListeners()->remove(...$listeners); //prevent any events being fired by initialization
56
57 $newContents = [];
58 $errorLogContext = "Container (" . $this->getPosition() . ")";
59 foreach($inventoryTag as $itemNBT){
60 $slotId = $itemNBT->getByte(SavedItemStackData::TAG_SLOT);
61 $newContents[$slotId] = Item::safeNbtDeserialize($itemNBT, "$errorLogContext slot $slotId");
62 }
63 $inventory->setContents($newContents);
64
65 $inventory->getListeners()->add(...$listeners);
66 }
67
68 if(($lockTag = $tag->getTag(ContainerTile::TAG_LOCK)) instanceof StringTag){
69 $this->lock = $lockTag->getValue();
70 }
71 }
72
73 protected function saveItems(CompoundTag $tag) : void{
74 $items = [];
75 foreach($this->getRealInventory()->getContents() as $slot => $item){
76 $items[] = $item->nbtSerialize($slot);
77 }
78
79 $tag->setTag(ContainerTile::TAG_ITEMS, new ListTag($items, NBT::TAG_Compound));
80
81 if($this->lock !== null){
82 $tag->setString(ContainerTile::TAG_LOCK, $this->lock);
83 }
84 }
85
89 public function canOpenWith(string $key) : bool{
90 return $this->lock === null || $this->lock === $key;
91 }
92
96 abstract protected function getPosition() : Position;
97
101 protected function onBlockDestroyedHook() : void{
102 $inv = $this->getRealInventory();
103 $pos = $this->getPosition();
104
105 $world = $pos->getWorld();
106 $dropPos = $pos->add(0.5, 0.5, 0.5);
107 foreach($inv->getContents() as $k => $item){
108 $world->dropItem($dropPos, $item);
109 }
110 $inv->clearAll();
111 }
112}
setString(string $name, string $value)
setTag(string $name, Tag $tag)
getListTag(string $name, string $tagClass=Tag::class)