NativeSerializer::serialize()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 8
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 2
crap 2
1
<?php
2
3
namespace Fxmlrpc\Serialization\Serializer;
4
5
use Fxmlrpc\Serialization\Exception\InvalidTypeException;
6
use Fxmlrpc\Serialization\Serializer;
7
use Fxmlrpc\Serialization\Value\Base64;
8
9
/**
10
 * Serializer creates XML from native PHP types using XML RPC extension.
11
 *
12
 * @author Lars Strojny <[email protected]>
13
 */
14
final class NativeSerializer implements Serializer
15
{
16
    /**
17
     * {@inheritdoc}
18
     */
19
    public function serialize($method, array $params = [])
20
    {
21
        return xmlrpc_encode_request(
22
            $method,
23
            $this->convert($params),
24
            ['encoding' => 'UTF-8', 'escaping' => 'markup', 'verbosity' => 'no_white_space']
25
        );
26
    }
27
28
    /**
29
     * @param array $params
30
     *
31
     * @return array
32
     */
33
    private function convert(array $params)
34
    {
35
        foreach ($params as $key => $value) {
36
            $type = gettype($value);
37
            if ($type === 'array') {
38
                $params[$key] = $this->convert($value);
39
            } elseif ($type === 'object') {
40
                if ($value instanceof \DateTime) {
41
                    $params[$key] = (object) [
42
                        'xmlrpc_type' => 'datetime',
43
                        'scalar' => $value->format('Ymd\TH:i:s'),
44
                        'timestamp' => $value->format('u'),
45
                    ];
46
                } elseif ($value instanceof Base64) {
47
                    $params[$key] = (object) [
48
                        'xmlrpc_type' => 'base64',
49
                        'scalar' => $value->getDecoded(),
50
                    ];
51
                } else {
52
                    $params[$key] = get_object_vars($value);
53
                }
54
            } elseif ($type === 'resource') {
55
                throw new InvalidTypeException($value);
56
            }
57
        }
58
59
        return $params;
60
    }
61
}
62