Completed
Push — master ( 9038ff...55d9a6 )
by Sebastian
03:06 queued 11s
created

Feed::getFeedContent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 0
1
<?php
2
3
namespace Spatie\Feed;
4
5
use Illuminate\Http\Response;
6
use Illuminate\Support\Collection;
7
use Spatie\Feed\Exceptions\InvalidFeedItem;
8
use Illuminate\Contracts\Support\Responsable;
9
10
class Feed implements Responsable
11
{
12
    /** @var string */
13
    protected $title;
14
15
    /** @var string */
16
    protected $url;
17
18
    /** @var \Illuminate\Support\Collection */
19
    protected $items;
20
21
    public function __construct($title, $url, $resolver)
22
    {
23
        $this->title = $title;
24
        $this->url = $url;
25
26
        $this->items = $this->resolveItems($resolver);
27
    }
28
29
    public function toResponse($request): Response
30
    {
31
        $meta = [
32
            'id' => url($this->url),
33
            'link' => url($this->url),
34
            'title' => $this->title,
35
            'updated' => $this->lastUpdated(),
36
        ];
37
38
        $contents = view('feed::feed', [
39
            'meta' => $meta,
40
            'items' => $this->items,
41
        ]);
42
43
        return new Response($contents, 200, [
44
            'Content-Type' => 'application/xml;charset=UTF-8',
45
        ]);
46
    }
47
48
    protected function resolveItems($resolver): Collection
49
    {
50
        $resolver = array_wrap($resolver);
51
52
        $items = app()->call(
53
            array_shift($resolver), $resolver
54
        );
55
56
        return collect($items)->map(function ($feedable) {
57
            return $this->castToFeedItem($feedable);
58
        });
59
    }
60
61
    protected function castToFeedItem($feedable): FeedItem
62
    {
63
        if (is_array($feedable)) {
64
            $feedable = new FeedItem($feedable);
65
        }
66
67
        if ($feedable instanceof FeedItem) {
68
            $feedable->validate();
69
70
            return $feedable;
71
        }
72
73
        if (! $feedable instanceof Feedable) {
74
            throw InvalidFeedItem::notFeedable($feedable);
75
        }
76
77
        $feedItem = $feedable->toFeedItem();
78
79
        if (! $feedItem instanceof FeedItem) {
80
            throw InvalidFeedItem::notAFeedItem($feedItem);
81
        }
82
83
        $feedItem->validate();
84
85
        return $feedItem;
86
    }
87
88
    protected function lastUpdated(): string
89
    {
90
        if ($this->items->isEmpty()) {
91
            return '';
92
        }
93
94
        return $this->items->sortBy('updated')->last()->updated->toAtomString();
95
    }
96
}
97