aboutsummaryrefslogtreecommitdiff
path: root/formats/SfeedFormat.php
blob: 063e4543f44e42302654b1475f1d55afa6dc435f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?PHP

class SfeedFormat extends FormatAbstract
{
    const MIME_TYPE = 'text/plain';

    public function render(): string
    {
        $text = '';
        foreach ($this->getItems() as $item) {
            $text .= sprintf(
                "%s\t%s\t%s\t%s\thtml\t\t%s\t%s\t%s\n",
                $item->toArray()['timestamp'],
                preg_replace('/\s/', ' ', $item->toArray()['title']),
                $item->toArray()['uri'],
                $this->escape($item->toArray()['content']),
                $item->toArray()['author'],
                $this->getFirstEnclosure(
                    $item->toArray()['enclosures']
                ),
                $this->escape(
                    $this->getCategories(
                        $item->toArray()['categories']
                    )
                )
            );
        }

        return $text;
    }

    private function escape(string $str)
    {
        $str = str_replace('\\', '\\\\', $str);
        $str = str_replace("\n", '\\n', $str);
        return str_replace("\t", '\\t', $str);
    }

    private function getFirstEnclosure(array $enclosures)
    {
        if (count($enclosures) >= 1) {
            return $enclosures[0];
        }
        return '';
    }

    private function getCategories(array $cats)
    {
        $toReturn = '';
        $i = 1;
        foreach ($cats as $cat) {
            $toReturn .= trim($cat);
            if (count($cats) > $i++) {
                $toReturn .= '|';
            }
        }
        return $toReturn;
    }
}