Completed
Push — master ( b526e9...87ea4e )
by Giancarlos
03:25
created

XmlUtils::extractSign()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: Administrador
5
 * Date: 04/10/2017
6
 * Time: 04:41 PM.
7
 */
8
9
namespace Greenter\Report;
10
11
/**
12
 * Class XmlUtils.
13
 */
14
final class XmlUtils
15
{
16
    const EXT_NAMESPACE = 'urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2';
17
    const DS_NAMESPACE = 'http://www.w3.org/2000/09/xmldsig#';
18
19
    /**
20
     * @param string $xml
21
     *
22
     * @return string
23
     */
24 6
    public function getHashSign($xml)
25
    {
26 6
        $doc = new \DOMDocument();
27 6
        $doc->loadXML($xml);
28
29 6
        return $this->getHashSignFromDoc($doc);
30
    }
31
32
    /**
33
     * @param string $filename
34
     *
35
     * @return string
36
     */
37 6
    public function getHashSignFromFile($filename)
38
    {
39 6
        $doc = new \DOMDocument();
40 6
        $doc->load($filename);
41
42 6
        return $this->getHashSignFromDoc($doc);
43
    }
44
45
    /**
46
     * @param \DOMDocument $document
47
     *
48
     * @return string
49
     */
50 16
    public function getHashSignFromDoc(\DOMDocument $document)
51
    {
52 16
        $xpt = $this->getXpath($document);
53
54 16
        $exts = $xpt->query('ext:UBLExtensions/ext:UBLExtension', $document->documentElement);
55 16
        if ($exts->length == 0) {
56 2
            return '';
57
        }
58 14
        $nodeSign = $exts->item($exts->length - 1);
59
60 14
        $hash = $xpt->query('ext:ExtensionContent/ds:Signature/ds:SignedInfo/ds:Reference/ds:DigestValue', $nodeSign);
61
62 14
        if ($hash->length == 0) {
63 2
            return '';
64
        }
65
66 12
        return $hash->item(0)->nodeValue;
67
    }
68
69
    /**
70
     * @param \DOMDocument $document
71
     *
72
     * @return \DOMXPath
73
     */
74 16
    public function getXpath(\DOMDocument $document)
75
    {
76 16
        $xpt = new \DOMXPath($document);
77 16
        $xpt->registerNamespace('ext', self::EXT_NAMESPACE);
78 16
        $xpt->registerNamespace('ds', self::DS_NAMESPACE);
79
80 16
        return $xpt;
81
    }
82
}
83