<?php

namespace Helpers\Outil;

use DOMDocument;

class XPathHelper extends \DOMXPath
{

    private ?\DOMNode $ctx = null;

    /**
     * @param array<string,string> $mapNamespace namespace indexed by prefix
     */
    public function __construct(DOMDocument $document, ?\DOMNode $context = null, array $mapNamespace = [])
    {
        parent::__construct($document, true);
        foreach ($mapNamespace as $alias => $namesp) {
            $this->registerNamespace($alias, $namesp);
        }
        $this->setContext($context);
    }

    public function setContext(?\DOMNode $context = null) :self
    {
        $this->ctx = $context;
        return $this;
    }
    
    /**
     * @return \DOMNodeList<\DOMNode>
     */
    public function mustQuery(string $path) :\DOMNodeList
    {
        /** @var \DOMNodeList<\DOMNode>|false */
        $res = $this->query($path, $this->ctx);
        if ($res === false) {
            throw new \Exception('xpath failed "'.$path.'"');
        }
        return $res;
    }

    public function queryFirstValue(string $path) :?string
    {
        $res = $this->mustQuery($path)->item(0) ?? null;
        return $res != null ? $res->textContent : null;
    }
}
