Completed
Push — master ( 6aef24...286712 )
by Márk
06:17
created

NativeSerializer::serialize()   D

Complexity

Conditions 9
Paths 7

Size

Total Lines 34
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 34
ccs 0
cts 30
cp 0
rs 4.9091
cc 9
eloc 23
nc 7
nop 2
crap 90
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
        $toBeVisited = [&$params];
22
23
        while (isset($toBeVisited[0]) && $value = &$toBeVisited[0]) {
24
            $type = gettype($value);
25
26
            if ($type === 'array') {
27
                foreach ($value as &$child) {
28
                    $toBeVisited[] = &$child;
29
                }
30
            } elseif ($type === 'object') {
31
                if ($value instanceof \DateTime) {
32
                    $value = $value->format('Ymd\TH:i:s');
33
                    xmlrpc_set_type($value, 'datetime');
34
                } elseif ($value instanceof Base64) {
35
                    $value = $value->getDecoded();
36
                    xmlrpc_set_type($value, 'base64');
37
                } else {
38
                    $value = get_object_vars($value);
39
                }
40
            } elseif ($type === 'resource') {
41
                throw new InvalidTypeException($value);
42
            }
43
44
            array_shift($toBeVisited);
45
        }
46
47
        return xmlrpc_encode_request(
48
            $method,
49
            $params,
50
            ['encoding' => 'UTF-8', 'escaping' => 'markup', 'verbosity' => 'no_white_space']
51
        );
52
    }
53
}
54