<?php

class Document extends DOMDocument {

    public static function serializeNode(DOMNode $node) {
        $c = [];
        foreach ($node->attributes as $a) {
            $n = $a->name;
            $c[$n] = $node->getAttribute($n);
        }
        return $c;
    }

    public static function serializeList(DOMNodeList $list) {
        $columns = [];
        foreach ($list as $node) {
            $columns[] = self::serializeNode($node);
        }
        return $columns;
    }

    public function __construct($ver = '1.0', $enc = 'utf-8') {
        parent::__construct($ver, $enc);
    }

    public function schema($name = '') {
        $path = "/root/schema/col";
        if (!empty($name)) {
            $path .= "[@name='$name']";
            return self::serializeNode($this->query($path)->item(0));
        }

        $list = $this->query($path);

        return self::serializeList($list);
    }

    public function name($v = '') {
        $node = $this->query("/root/name")->item(0);
        if (empty($v)) {
            return $node->textContent;
        }
        $node->textContent = $v;
        return $this->save($this->documentURI);
    }

    public function query($s) {
        return (new DOMXPath($this))->query($s);
    }

    public function findByid($s) {
        return $this->query("//*[@id='$s']")->item(0);
    }

}
