Created
June 25, 2011 14:56
-
-
Save rande/1046563 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Sonata\PageBundle\Block; | |
use Symfony\Component\HttpFoundation\Response; | |
use Symfony\Component\Form\Form; | |
use Sonata\AdminBundle\Form\FormMapper; | |
use Sonata\PageBundle\Model\BlockInterface; | |
use Sonata\PageBundle\Model\PageInterface; | |
use Sonata\AdminBundle\Validator\ErrorElement; | |
class RssBlockService extends BaseBlockService | |
{ | |
public function getName() | |
{ | |
return 'Rss Reader'; | |
} | |
function getDefaultSettings() | |
{ | |
return array( | |
'url' => false, | |
'title' => 'Insert the rss title' | |
); | |
} | |
public function buildEditForm(FormMapper $formMapper, BlockInterface $block) | |
{ | |
$formMapper->addType('settings', 'sonata_type_immutable_array', array( | |
'keys' => array( | |
array('url', 'url', array('required' => false)), | |
array('title', 'text', array('required' => false)), | |
) | |
)); | |
} | |
function validateBlock(ErrorElement $errorElement, BlockInterface $block) | |
{ | |
$errorElement | |
->with('settings.url') | |
->assertNotNull(array()) | |
->assertNotBlank() | |
->end() | |
->with('settings.title') | |
->assertNotNull(array()) | |
->assertNotBlank() | |
->assertMaxLength(array('limit' => 50)) | |
->end(); | |
} | |
public function execute(BlockInterface $block, PageInterface $page, Response $response = null) | |
{ | |
// merge settings | |
$settings = array_merge($this->getDefaultSettings(), $block->getSettings()); | |
$feeds = false; | |
if ($settings['url']) { | |
$options = array( | |
'http' => array( | |
'user_agent' => 'Sonata/RSS Reader', | |
'timeout' => 2, | |
) | |
); | |
// retrieve contents with a specific stream context to avoid php errors | |
$content = @file_get_contents($settings['url'], false, stream_context_create($options)); | |
if ($content) { | |
// generate a simple xml element | |
try { | |
$feeds = new \SimpleXMLElement($content); | |
$feeds = $feeds->channel->item; | |
} catch(\Exception $e) { | |
// silently fail error | |
} | |
} | |
} | |
return $this->renderResponse('SonataPageBundle:Block:block_core_rss.html.twig', array( | |
'feeds' => $feeds, | |
'block' => $block, | |
'settings' => $settings | |
), $response); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment