<?php

namespace iDServer\Internal;

use DOMNode;
use DOMXPath;
use Exception;
use RobRichards\XMLSecLibs\XMLSecurityDSig as XMLSecurityDSigBase;

class XMLSecurityDSig extends XMLSecurityDSigBase
{
    /**
     * @param $node
     * @return XMLSecurityKey|null
     */
    public function locateKey($node = null)
    {
        if (empty($node)) {
            $node = $this->sigNode;
        }
        if (! $node instanceof DOMNode) {
            return null;
        }
        if ($doc = $node->ownerDocument) {
            $xpath = new DOMXPath($doc);
            $xpath->registerNamespace('secdsig', self::XMLDSIGNS);
            $query = "string(./secdsig:SignedInfo/secdsig:SignatureMethod/@Algorithm)";
            $algorithm = $xpath->evaluate($query, $node);
            if ($algorithm) {
                try {
                    $objKey = new XMLSecurityKey($algorithm, array('type' => 'public'));
                } catch (Exception $e) {
                    return null;
                }
                return $objKey;
            }
        }
        return null;
    }
}
