Passed
Push — develop ( 726e4d...2a8883 )
by Luís
37s
created

SerializerTrait   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
c 1
b 0
f 0
lcom 1
cbo 4
dl 0
loc 54
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getSerializer() 0 10 2
A xmlSerialize() 0 16 2
A formatAmount() 0 8 2
1
<?php
2
3
namespace PHPSC\PagSeguro;
4
5
use JMS\Serializer\Annotation as Serializer;
6
use JMS\Serializer\Naming\IdenticalPropertyNamingStrategy;
7
use JMS\Serializer\Naming\SerializedNameAnnotationStrategy;
8
use JMS\Serializer\SerializerBuilder;
9
use SimpleXMLElement;
10
11
/**
12
 * @author Vinícius Fagundes <[email protected]>
13
 */
14
trait SerializerTrait
15
{
16
    /**
17
     * @Serializer\Exclude
18
     *
19
     * @var \JMS\Serializer\Serializer
20
     */
21
    private $serializer;
22
23
    /**
24
     * @return \JMS\Serializer\Serializer
25
     */
26
    public function getSerializer()
27
    {
28
        if ($this->serializer === null) {
29
            $this->serializer = SerializerBuilder::create()
30
                ->setPropertyNamingStrategy(new SerializedNameAnnotationStrategy(new IdenticalPropertyNamingStrategy()))
31
                ->build();
32
        }
33
34
        return $this->serializer;
35
    }
36
37
    /**
38
     * @param SimpleXMLElement|null $xmlRoot
39
     *
40
     * @return SimpleXMLElement
41
     */
42
    public function xmlSerialize(SimpleXMLElement $xmlRoot = null)
43
    {
44
        $xmlString = $this->getSerializer()->serialize($this, 'xml');
45
        $xmlObject = new SimpleXMLElement($xmlString);
46
47
        if ($xmlRoot === null) {
48
            return $xmlObject;
49
        }
50
51
        $domRoot = dom_import_simplexml($xmlRoot);
52
        $domObject = dom_import_simplexml($xmlObject);
53
54
        $domRoot->appendChild($domRoot->ownerDocument->importNode($domObject, true));
55
56
        return $xmlRoot;
57
    }
58
59
    protected final function formatAmount($amount)
60
    {
61
        if ($amount === null) {
62
            return null;
63
        }
64
65
        return number_format($amount, 2, '.', '');
66
    }
67
}
68