Improve item enchantment API and fix some bugs (#512)

This commit is contained in:
PMMPFTW 2017-05-03 11:13:00 +01:00 committed by Dylan K. Taylor
parent 2b4e303f52
commit fb59b57bdf

View File

@ -504,10 +504,26 @@ class Item implements ItemIds, \JsonSerializable{
}
$tag = $this->getNamedTag();
if(isset($tag->ench)){
$tag = $tag->ench;
if($tag instanceof ListTag){
return true;
return isset($tag->ench) and $tag->ench instanceof ListTag;
}
/**
* @param int $id
* @param int $level
*
* @return bool
*/
public function hasEnchantment(int $id, int $level = -1) : bool{
if(!$this->hasEnchantments()){
return false;
}
foreach($this->getNamedTag()->ench as $entry){
if($entry["id"] === $id){
if($level === -1 or $entry["lvl"] === $level){
return true;
}
}
}
@ -535,6 +551,35 @@ class Item implements ItemIds, \JsonSerializable{
return null;
}
/**
* @param int $id
* @param int $level
*/
public function removeEnchantment(int $id, int $level = -1){
if(!$this->hasEnchantments()){
return;
}
$tag = $this->getNamedTag();
foreach($tag->ench as $k => $entry){
if($entry["id"] === $id){
if($level === -1 or $entry["lvl"] === $level){
unset($tag->ench[$k]);
break;
}
}
}
$this->setNamedTag($tag);
}
public function removeEnchantments(){
if($this->hasEnchantments()){
$tag = $this->getNamedTag();
unset($tag->ench);
$this->setNamedTag($tag);
}
}
/**
* @param Enchantment $ench
*/
@ -545,26 +590,26 @@ class Item implements ItemIds, \JsonSerializable{
$tag = $this->getNamedTag();
}
$found = false;
if(!isset($tag->ench)){
$tag->ench = new ListTag("ench", []);
$tag->ench->setTagType(NBT::TAG_Compound);
}
$found = false;
foreach($tag->ench as $k => $entry){
if($entry["id"] === $ench->getId()){
$tag->ench->{$k} = new CompoundTag("", [
new ShortTag("id", $ench->getId()),
new ShortTag("lvl", $ench->getLevel())
]);
$found = true;
break;
}else{
foreach($tag->ench as $k => $entry){
if($entry["id"] === $ench->getId()){
$tag->ench->{$k} = new CompoundTag("", [
new ShortTag("id", $ench->getId()),
new ShortTag("lvl", $ench->getLevel())
]);
$found = true;
break;
}
}
}
if(!$found){
$tag->ench->{count($tag->ench) + 1} = new CompoundTag("", [
$tag->ench->{count($tag->ench)} = new CompoundTag("", [
new ShortTag("id", $ench->getId()),
new ShortTag("lvl", $ench->getLevel())
]);
@ -577,16 +622,14 @@ class Item implements ItemIds, \JsonSerializable{
* @return Enchantment[]
*/
public function getEnchantments() : array{
if(!$this->hasEnchantments()){
return [];
}
$enchantments = [];
foreach($this->getNamedTag()->ench as $entry){
$e = Enchantment::getEnchantment($entry["id"]);
$e->setLevel($entry["lvl"]);
$enchantments[] = $e;
if($this->hasEnchantments()){
foreach($this->getNamedTag()->ench as $entry){
$e = Enchantment::getEnchantment($entry["id"]);
$e->setLevel($entry["lvl"]);
$enchantments[] = $e;
}
}
return $enchantments;