Passed
Push — master ( b6e803...52a2f7 )
by Evgenii
03:17
created

DalliApiBody::__construct()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
eloc 9
c 1
b 0
f 1
nc 3
nop 2
dl 0
loc 13
ccs 10
cts 10
cp 1
crap 3
rs 9.9666
1
<?php
2
3
4
namespace floor12\DalliApi\Models;
5
6
7
use floor12\DalliApi\Exceptions\EmptyApiMethodException;
8
use floor12\DalliApi\Exceptions\EmptyTokenException;
9
use ReflectionClass;
10
use ReflectionException;
11
use SimpleXMLElement;
12
13
class DalliApiBody extends BaseXmlObject
14
{
15
    /** @var string */
16
    protected $authToken;
17
    /** @var string */
18
    protected $apiMethodName = 'testMehod';
19
    /** @var SimpleXMLElement */
20
    protected $mainElement;
21
22
    /**
23
     * DalliApiBody constructor.
24
     * @param string|null $apiMethodName
25
     * @param string|null $authToken
26
     * @throws EmptyApiMethodException
27
     * @throws EmptyTokenException
28
     */
29 3
    public function __construct(?string $apiMethodName, ?string $authToken)
30
    {
31 3
        if (empty($apiMethodName))
32 1
            throw new EmptyApiMethodException();
33
34 2
        if (empty($authToken))
35 1
            throw new EmptyTokenException();
36
37 1
        $this->apiMethodName = $apiMethodName;
38 1
        $this->authToken = $authToken;
39 1
        $this->mainElement = new SimpleXMLElement("<$this->apiMethodName></$this->apiMethodName>");
40 1
        $auth = $this->mainElement->addChild('auth');
41 1
        $auth->addAttribute('token', $this->authToken);
42 1
    }
43
44
    /**
45
     * @param BaseXmlObject $object
46
     * @return $this
47
     * @throws ReflectionException
48
     */
49 1
    public function add(BaseXmlObject $object): self
50
    {
51 1
        $className = mb_strtolower((new ReflectionClass($object))->getShortName());
52 1
        $mainElement = $this->mainElement->addChild($className);
53 1
        foreach ($object as $attributeName => $attributeValue) {
54 1
            $this->processAttributeNameAndValue($mainElement, $attributeName, $attributeValue);
55
        }
56 1
        return $this;
57
    }
58
59
    /**
60
     * @param BaseXmlObject|null $object
61
     * @return string
62
     */
63 1
    public function getAsXmlString(BaseXmlObject $object = null): string
64
    {
65 1
        return $this->mainElement->asXML();
66
    }
67
}
68