Completed
Push — master ( 5f3a6c...fcd09b )
by Kacper
05:50
created

XmlElementFactory::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 4
dl 0
loc 6
ccs 3
cts 3
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Nucleus - XMPP Library for PHP
4
 *
5
 * Copyright (C) 2016, Some rights reserved.
6
 *
7
 * @author Kacper "Kadet" Donat <[email protected]>
8
 *
9
 * Contact with author:
10
 * Xmpp: [email protected]
11
 * E-mail: [email protected]
12
 *
13
 * From Kadet with love.
14
 */
15
16
namespace Kadet\Xmpp\Xml;
17
18
class XmlElementFactory
19
{
20
    /**
21
     * @var string[string]
22
     */
23
    private $_lookup = [];
24
    
25 3
    public function lookup($namespace, $tag, $additional = [])
26
    {
27 3
        $lookup = array_merge($this->_lookup, $this->_lookupize($additional));
28
29 3
        if (isset($lookup["$tag@$namespace"])) {
30 1
            return $lookup["$tag@$namespace"];
31 3
        } elseif (isset($lookup[$namespace])) {
32 1
            return $lookup[$namespace];
33
        } else {
34 3
            return XmlElement::class;
35
        }
36
    }
37
38 1
    public function register($class, $namespace, $tag = null)
39
    {
40 1
        $this->_lookup = array_merge($this->_lookup, $this->_lookupize([[$class, 'uri' => $namespace, 'name' => $tag]]));
41 1
    }
42
43
    public function load(array $dictionary)
44
    {
45
        foreach ($dictionary as $element) {
46
            $this->register($element[0], $element['uri'] ?? null, $element['name'] ?? null);
47
        }
48
    }
49
50 3
    public function create($namespace, $tag, $arguments = [], $additional = [])
51
    {
52 3
        $class = $this->lookup($namespace, $tag, $additional);
53
        /** @noinspection PhpUndefinedMethodInspection */
54 3
        return $class::plain(...$arguments);
55
    }
56
57 3
    private function _lookupize(array $dictionary)
58
    {
59 3
        $result = [];
60 3
        foreach ($dictionary as $element) {
61 1
            $result[$this->_name($element['name'] ?? null, $element['uri'] ?? null)] = $element[0];
62
        }
63
64 3
        return $result;
65
    }
66
67 1
    private function _name(string $name = null, string $uri = null)
68
    {
69 1
        return $name ? "$name@$uri" : $uri;
70
    }
71
}
72