Completed
Push — master ( 9b8515...2320df )
by Adrien
02:36
created

Decoder   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Test Coverage

Coverage 96.3%

Importance

Changes 0
Metric Value
eloc 26
dl 0
loc 76
ccs 26
cts 27
cp 0.963
rs 10
c 0
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A validate() 0 15 3
A decode() 0 18 3
1
<?php
2
3
namespace Genkgo\Camt;
4
5
use DOMDocument;
6
use Genkgo\Camt\Exception\InvalidMessageException;
7
use SimpleXMLElement;
8
9
/**
10
 * Class Decoder
11
 *
12
 * @package Genkgo\Camt
13
 */
14
class Decoder implements DecoderInterface
15
{
16
    /**
17
     * @var SimpleXMLElement
18
     */
19
    private $document;
20
21
    /**
22
     * @var Decoder\Message
23
     */
24
    private $messageDecoder;
25
26
    /**
27
     * Path to the schema definition
28
     *
29
     * @var string
30
     */
31
    protected $schemeDefinitionPath;
32
33
    /**
34
     * @param Decoder\Message $messageDecoder
35
     * @param string          $schemeDefinitionPath
36
     */
37 23
    public function __construct(Decoder\Message $messageDecoder, $schemeDefinitionPath)
38
    {
39 23
        $this->messageDecoder       = $messageDecoder;
40 23
        $this->schemeDefinitionPath = $schemeDefinitionPath;
41 23
    }
42
43
    /**
44
     * @param DOMDocument $document
45
     *
46
     * @throws InvalidMessageException
47
     */
48 22
    private function validate(DOMDocument $document)
49
    {
50 22
        libxml_use_internal_errors(true);
51 22
        $valid  = $document->schemaValidate(dirname(__DIR__) . $this->schemeDefinitionPath);
52 22
        $errors = libxml_get_errors();
53 22
        libxml_clear_errors();
54
55 22
        if (!$valid) {
56 1
            $messages = [];
57 1
            foreach ($errors as $error) {
58 1
                $messages[] = $error->message;
59
            }
60
61 1
            $errorMessage = implode("\n", $messages);
62 1
            throw new InvalidMessageException("Provided XML is not valid according to the XSD:\n{$errorMessage}");
63
        }
64 21
    }
65
66
    /**
67
     * @param DOMDocument $document
68
     * @param bool        $xsdValidation
69
     *
70
     * @return DTO\Message
71
     */
72 23
    public function decode(DOMDocument $document, $xsdValidation = true)
73
    {
74 23
        if ($xsdValidation === true) {
75 22
            $this->validate($document);
76
        }
77
78 22
        $document = simplexml_import_dom($document);
79 22
        if ($document === false) {
80
            throw new InvalidMessageException("Provided XML could not be parsed");
81
        }
82
83 22
        $this->document = $document;
84
85 22
        $message = new DTO\Message();
86 22
        $this->messageDecoder->addGroupHeader($message, $this->document);
87 22
        $this->messageDecoder->addRecords($message, $this->document);
88
89 22
        return $message;
90
    }
91
}
92