Passed
Branch new-version (3d9930)
by Jeroen
02:32
created

VcfFormatter::getContent()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 1
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace JeroenDesloovere\VCard\Formatter;
4
5
use JeroenDesloovere\VCard\Property\NodeInterface;
6
use JeroenDesloovere\VCard\VCard;
7
8
final class VcfFormatter implements FormatterInterface
9
{
10
    public function getContent(array $vCards): string
11
    {
12
        $string = '';
13
14
        /**
15
         * @var VCard $vCard
16
         */
17
        foreach ($vCards as $vCard) {
18
            $string .= "BEGIN:VCARD\r\n";
19
            $this->setNodesToString($vCard->getParameters(), $string);
20
            $this->setNodesToString($vCard->getProperties(), $string);
21
            $string .= "END:VCARD\r\n";
22
        }
23
24
        return $string;
25
    }
26
27
    public function getContentType(): string
28
    {
29
        return 'text/x-vcard';
30
    }
31
32
    public function getFileExtension(): string
33
    {
34
        return 'vcf';
35
    }
36
37
    /**
38
     * Fold a line according to RFC2425 section 5.8.1.
39
     *
40
     * @link   http://tools.ietf.org/html/rfc2425#section-5.8.1
41
     * @param  string $value
42
     * @return string
43
     */
44
    private function fold(string $value): string
45
    {
46
        if (strlen($value) <= 75) {
47
            return $value;
48
        }
49
50
        // split, wrap and trim trailing separator
51
        return substr(chunk_split($value, 73, "\r\n "), 0, -3);
52
    }
53
54
    /**
55
     * @param NodeInterface[] $nodes
56
     * @param string $string
57
     */
58
    private function setNodesToString(array $nodes, string &$string): void
59
    {
60
        /**
61
         * @var NodeInterface $parameter
62
         */
63
        foreach ($nodes as $parameter) {
64
            $string .= $this->fold($parameter->getFormatter()->getVcfString() . "\r\n");
65
        }
66
    }
67
}
68