1 | <?php declare(strict_types=1); |
||
18 | class JsonParser extends ParserAbstract |
||
19 | { |
||
20 | |||
21 | /** |
||
22 | * @param Document $document |
||
23 | * @param FeedInterface $feed |
||
24 | * @return FeedInterface |
||
25 | */ |
||
26 | 1 | public function parseContent(Document $document, FeedInterface $feed) : FeedInterface |
|
27 | { |
||
28 | 1 | $data = $document->getJsonAsArray(); |
|
29 | 1 | $feed->setTitle($this->readOffset($data, 'title')); |
|
30 | 1 | $feed->setDescription($this->readOffset($data, 'description')); |
|
31 | 1 | $feed->setLink($this->readOffset($data, 'feed_url')); |
|
32 | 1 | $feed->setUrl($this->readOffset($data, 'home_page_url')); |
|
33 | |||
34 | 1 | if (array_key_exists('items', $data)) { |
|
35 | 1 | $this->parseItems($data['items'], $feed); |
|
36 | } |
||
37 | |||
38 | 1 | return $feed; |
|
39 | } |
||
40 | |||
41 | /** |
||
42 | * @param Document $document |
||
43 | * @param iterable $mandatoryFields |
||
44 | * @throws MissingFieldsException |
||
45 | * @return bool |
||
46 | */ |
||
47 | 1 | public function checkBodyStructure(Document $document, iterable $mandatoryFields) : bool |
|
48 | { |
||
49 | 1 | $data = $document->getJsonAsArray(); |
|
50 | |||
51 | 1 | foreach ($mandatoryFields as $mandatoryField) { |
|
52 | 1 | if (! array_key_exists($mandatoryField, $data)) { |
|
53 | 1 | throw new MissingFieldsException("Missing {$mandatoryField} in the JSON Feed"); |
|
54 | } |
||
55 | } |
||
56 | |||
57 | 1 | return true; |
|
58 | } |
||
59 | |||
60 | /** |
||
61 | * @param iterable $items |
||
62 | * @param FeedInterface $feed |
||
63 | * @return JsonParser |
||
64 | */ |
||
65 | 1 | public function parseItems(iterable $items, FeedInterface $feed) : JsonParser |
|
66 | { |
||
67 | 1 | foreach ($items as $dataItem) { |
|
68 | 1 | $item = new Item(); |
|
69 | 1 | $item->setPublicId($this->readOffset($dataItem, 'id')); |
|
70 | 1 | $item->setTitle($this->readOffset($dataItem, 'title')); |
|
71 | 1 | $item->setLastModified(new \DateTime($this->readOffset($dataItem, 'date_published'))); |
|
72 | 1 | $contentHtml = $this->readOffset($dataItem, 'content_html'); |
|
73 | 1 | $item->setDescription($this->readOffset($dataItem, 'content_text', $contentHtml)); |
|
74 | 1 | $feed->add($item); |
|
75 | } |
||
76 | |||
77 | 1 | return $this; |
|
78 | } |
||
79 | |||
80 | /** |
||
81 | * @param array $data |
||
82 | * @param string $offsetName |
||
83 | * @param string|null $default |
||
84 | * @return null|string |
||
85 | */ |
||
86 | 1 | public function readOffset(array $data, string $offsetName, string $default = null) : ? string |
|
94 | } |
||
95 |