Skip to content

Instantly share code, notes, and snippets.

@Frago9876543210
Last active July 31, 2018 12:12
Show Gist options
  • Save Frago9876543210/3669de3d494531070c8df43c85773352 to your computer and use it in GitHub Desktop.
Save Frago9876543210/3669de3d494531070c8df43c85773352 to your computer and use it in GitHub Desktop.
NBT object to code
<?php
declare(strict_types=1);
namespace NS;
use pocketmine\nbt\NBTStream;
use pocketmine\nbt\NetworkLittleEndianNBTStream;
use pocketmine\nbt\tag\NamedTag;
class NBTDumper{
public static function substituteClass(NamedTag $tag){
$class = self::getClassName($tag);
return new class($class, $tag->getName(), $tag->getValue()) extends NamedTag{
/** @var string */
private $class;
/** @var mixed */
private $value;
/** @var bool */
private $asHex;
/**
* constructor.
* @param string $class
* @param string $name
* @param mixed $value
* @param bool $asHex
*/
public function __construct(string $class, string $name, $value, bool $asHex = false){
parent::__construct($name);
$this->class = $class;
$this->value = $value;
$this->asHex = $asHex;
}
public function getValue(){
return $this->value;
}
public function getType() : int{
return -1;
}
public function write(NBTStream $nbt) : void{
}
public function read(NBTStream $nbt) : void{
}
public function __toString() : string{
if(is_array($this->value)){
$str = 'new ' . $this->class . "(\"" . $this->getName() . "\", [" . "\n";
foreach($this->value as $tag){
if($tag instanceof NamedTag){
$str .= (string) NBTDumper::substituteClass($tag);
}
}
return $str . "])," . "\n";
}else{
if(is_string($this->value)){
return 'new ' . $this->class . '("' . $this->getName() . '", "' . ($this->asHex ? NBTDumper::str2hex($this->value) : $this->value) . '"),' . "\n";
}else{
return 'new ' . $this->class . '("' . $this->getName() . '", ' . var_export($this->value, true) . '),' . "\n";
}
}
}
};
}
public static function getClassName($class) : string{
/** @noinspection PhpUnhandledExceptionInspection */
return (new \ReflectionClass($class))->getShortName();
}
public static function dump(string $namedtag) : string{
return (string) self::substituteClass((new NetworkLittleEndianNBTStream)->read($namedtag)) . PHP_EOL;
}
public static function str2hex(string $string) : string{
return empty($string) ? $string : implode(array_map(function(string $value) : string{
return str_pad($value, 4, "\x", STR_PAD_LEFT);
}, str_split(bin2hex($string), 2)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment