Created
March 20, 2015 21:48
-
-
Save jadb/5b779959f50c22d2f2ff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace FluxCtrl\Model\Hose; | |
use Cake\Collection\Collection; | |
use Cake\ORM\TableRegistry; | |
use FluxCtrl\Datasource\HoseInterface; | |
use FluxCtrl\Model\Entity\Feed; | |
use PicoFeed\Parser\Item; | |
use PicoFeed\PicoFeedException; | |
use PicoFeed\Reader\Reader; | |
class PicoHose implements HoseInterface | |
{ | |
protected $_Feed; | |
public function __construct(Feed $feed) | |
{ | |
$this->_Feed = $feed; | |
} | |
public function aggregate() | |
{ | |
$feed = $this->_Feed; | |
$raw = $this->getFeedParser()->execute(); | |
$items = (new Collection($raw->getItems())) | |
->map(function ($item) { | |
return $this->toFluxCtrlItem($item) | |
->hiddenProperties([]) | |
->toArray(); | |
}) | |
->toArray(); | |
$data = compact('items'); | |
$options = ['associated' => ['Items' => ['accessibleFields' => ['*' => true]]]]; | |
if ($feed->isNew()) { | |
$data += [ | |
'title' => $feed->title, | |
'description' => $feed->description, | |
'url' => $feed->feed_url, | |
'website' => $feed->site_url, | |
'checked' => $feed->date, | |
'lang' => $feed->language, | |
]; | |
$options += ['fieldList' => array_keys($data)]; | |
} | |
return TableRegistry::get('Feeds')->patchEntity($feed, $data, $options); | |
} | |
public function getFeedParser() | |
{ | |
try { | |
$reader = new Reader(); | |
$resource = $reader->download( | |
$this->_Feed->url, | |
$this->_Feed->checked, | |
$this->_Feed->etag | |
); | |
$parser = $reader->getParser( | |
$resource->getUrl(), | |
$resource->getContent(), | |
$resource->getEncoding() | |
); | |
} catch (PicoFeedException $e) { | |
throw $e; | |
} | |
return $parser; | |
} | |
public function toFluxCtrlItem(Item $item) | |
{ | |
return TableRegistry::get('Items')->newEntity( | |
[ | |
'title' => $item->title, | |
'author' => $item->author, | |
'url' => $item->url, | |
'content' => $item->content, | |
'enclosure_url' => $item->enclosure_url, | |
'enclosure_type' => $item->enclosure_type, | |
'lang' => $item->language, | |
'published' => $item->date, | |
], | |
[ | |
'validate' => false, | |
'accessibleFields' => ['*' => true] | |
] | |
)->accessible('*', false); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment