Skip to content

Commit

Permalink
RssController
Browse files Browse the repository at this point in the history
  • Loading branch information
mparaiso committed Mar 23, 2013
1 parent 65b959b commit dcb762f
Show file tree
Hide file tree
Showing 10 changed files with 265 additions and 7 deletions.
14 changes: 11 additions & 3 deletions app/ConfigProvider.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
<?php

use Silex\Provider\ServiceControllerServiceProvider;
use Helper\SnippetAdapter;
use Mparaiso\Rss\SimpleRss;
use Service\RssService;
use Service\AccountService;
use Silex\Provider\DoctrineServiceProvider;
use Mparaiso\Provider\CrudGeneratorServiceProvider;
Expand Down Expand Up @@ -38,11 +41,11 @@ class ConfigProvider implements ServiceProviderInterface
{
function register(Application $app)
{
$app["debug"]=getenv("SNIPPETMANAGER_ENV")=="development"?true:false;
$app["debug"]=getenv("SNIPPETMANAGER_ENV")=="development"?TRUE:FALSE;
//$app['secure_protocol'] = $app["debug"]==true?"http":"https";
//FR: choisit entre http et https selon le debug mode
//EN: switch between http (dev) and https (production)
define("TEMP_DIR", __DIR__ . "/../temp/");
!defined("TEMP_DIR") AND define("TEMP_DIR", __DIR__ . "/../temp/");
$app->register(new TwigServiceProvider, array(
"twig.options" => array("cache" => TEMP_DIR."/twig/",),
"twig.path" => array(__DIR__ . "/Resources/templates/",)
Expand Down Expand Up @@ -96,7 +99,7 @@ function register(Application $app)
}),
"logout"=>array("logout_path"=>"/account/logout"),
"pattern" => "^/",
"anonymous" => true, /* FR : autorise les utilisateurs anonymes ,EN : allow anonymous users */
"anonymous" => TRUE, /* FR : autorise les utilisateurs anonymes ,EN : allow anonymous users */
"form"=>array(
"login_path"=>$app["url_generator"]->generate("account_login"),
"check_path"=>$app["url_generator"]->generate("account_check"),
Expand Down Expand Up @@ -144,6 +147,11 @@ function register(Application $app)
$app["user_provider"] = $app->share(function ($app) {
return new EntityUserProvider($app["em.registry"], '\Entity\User', "username");
});
$app["rss_service"]=$app->share(function($app){
$rss= new SimpleRss(array());
$rss->setItemAdapter(new SnippetAdapter($app["url_generator"]));
return new RssService($app["snippet_service"],$app["category_service"],$rss);
});
}

function boot(Application $app)
Expand Down
49 changes: 49 additions & 0 deletions app/Controller/RssController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

namespace Controller;

use Silex\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Silex\Application;

class RssController implements ControllerProviderInterface
{
/**
* FR : génère un flux rss à partir de la BDD
* @param \Symfony\Component\HttpFoundation\Request $req
* @param $title
* @param \Silex\Application $app
* @return mixed
*/
function index(Request $req, $title,Application $app)
{
$content = $app["rss_service"]->generate($title);
return $content;
}

/**
* Returns routes to connect to the given application.
*
* @param Application $app An Application instance
*
* @return ControllerCollection A ControllerCollection instance
*/
public function connect(Application $app)
{
/* @var $controllers \Silex\ControllerCollection */
$controllers = $app["controllers_factory"];
$controllers->match("/rss/{title}", array($this, "index"))
->value("title", "")
->bind("rss")
->after(function(Request $req,Response $res,Application $app){
$res->headers->add(
array("Content-type"=>"application/rss+xml"));
return $res;
});



return $controllers;
}
}
88 changes: 88 additions & 0 deletions app/Helper/SnippetAdapter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php

namespace Helper;

use Mparaiso\Rss\Adapter\IItemAdapter;
use Symfony\Component\Routing\Generator\UrlGenerator;
use Exception;

class SnippetAdapter implements IItemAdapter
{

protected $generator;

function __construct(UrlGenerator $generator)
{
$this->generator = $generator;
}

/**
* convert a model to an associative array
* @param $data
* @return mixed
*/
function toChannel($data)
{
if ($data instanceof \Entity\Category) {
$channel["title"] = $data->getTitle();
$channel["description"] = $data->getDescription();
$channel["language"] = "en-en";
$channel["link"] = $this->generator->generate("home", array("category" => urlencode($data->getTitle())), TRUE);
$channel["guid"] = $channel["link"];
$channel["language"] = "en-en";
foreach ($data->getSnippets() as $snippet) {
/* @var $snippet \Entity\Snippet */
$channel["items"][] = array(
"title" => $snippet->getTitle(),
"description" => $snippet->getDescription(),
"pubDate" => $snippet->getCreatedAt(),
"guid" => $this->generator->generate("snippet", array('title' => urlencode($snippet->getTitle())), TRUE),
);
}
/* trie les snippet dans l'ordre de date décroissant */
uasort($channel['items'], function ($a, $b) {
if ($a['pubDate'] == $b['pubDate']) return 0;
return $a['pubDate'] < $b['pubDate'] ? 1 : -1;
});
} elseif (is_array($data)) {
$channel["title"] = "Snippet Manager";
$channel["description"] = "Manage your snippets online";
$channel["language"] = "en-en";
$channel['link'] = $this->generator->generate("home", array(), TRUE);
$channel['guid'] = $channel['link'];
foreach ($data as $snippet) {
/* @var $snippet \Entity\Snippet */
$channel["items"][] = array(
"title" => $snippet->getTitle(),
"description" => $snippet->getDescription(),
"pubDate" => $snippet->getCreatedAt(),
"guid" => $this->generator->generate("snippet", array('title' => urlencode($snippet->getTitle())), TRUE),

);
}
} else {
throw new Exception('Cant parse data, must be a \Entity\Category or an array of snippets');
}
return $channel;
}

/**
* convert channel back to a model
* @param $channel
* @return mixed
*/
function toModel($channel)
{
// TODO: Implement toModel() method.
}

public function getGenerator()
{
return $this->generator;
}

public function setGenerator($generator)
{
$this->generator = $generator;
}
}
3 changes: 3 additions & 0 deletions app/Resources/templates/index.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
{% if snippets|length <= 0 %}
<h3>No snippets yet , please create a new snippet </h3>
{% endif %}
<div class="row">
<span class="pull-right"><a href="{{ path("rss",{"title":app.request.get('category')|default("")}) }}">RSS</a></span>
</div>
{% include 'crud/includes/pagination.html.twig' %}
{% for snippet in snippets %}
<div class="span4 border"><h4><a title="{{ snippet.description }}"
Expand Down
43 changes: 43 additions & 0 deletions app/Service/RssService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php


namespace Service;

use Mparaiso\Rss\SimpleRss;
use Helper\SnippetAdapter;

class RssService
{

protected $rssGenerator;

protected $categoryService;

protected $snippetService;

function __construct(SnippetService $snippetService, CategoryService $categoryService, SimpleRss $rssGenerator)
{
$this->rssGenerator = $rssGenerator;
$this->categoryService = $categoryService;
$this->snippetService = $snippetService;
}

/**
* FR : génère un flux RSS à partir d'une categories
* EN : generate a rss feed according to a category
* @param string $channel
*/
function generate($channel = NULL)
{
if ($channel != NULL) {
$data = $this->categoryService
->findOneBy(array("title" => $channel));
} else {
$data = $this->snippetService
->findAll(array(),array("created_at"=>"DESC"));
}
$this->rssGenerator->setChannel($data);
return $this->rssGenerator->generate();
}

}
10 changes: 6 additions & 4 deletions app/SnippetManager.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

use Controller\RoleController;
use Controller\RssController;
use Silex\Application;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
Expand All @@ -16,16 +17,17 @@ function __construct(array $values = array())
{
parent::__construct($values);
$this->register(new ConfigProvider);
$this->mount("/", new RssController);
$this->mount("/", new DefaultController);
$this->mount("/account", new AccountController);
$this->mount("/account", new SnippetController);
$this->mount("/admin",new AdminController);
$this->mount("/admin", new AdminController);
$this->mount("/admin", new RoleController);
$this->mount("/admin", new CategoryController);
if($this["debug"]==FALSE){
if ($this["debug"] == FALSE) {
// force HTTPS on heroku
$this->after(function(Request $req,Response $resp){
$resp->headers->add(array("Strict-Transport-Security"=>"max-age=31536000; includeSubDomains"));
$this->after(function (Request $req, Response $resp) {
$resp->headers->add(array("Strict-Transport-Security" => "max-age=31536000; includeSubDomains"));
return $resp;
});
}
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"doctrine/orm":"2.3.*",
"symfony/symfony":"2.2.*",
"silex/silex":"*@dev",
"mparaiso/simple-rss":"*@dev",
"doctrine/migrations":"*@dev",
"silex/web-profiler":"*@dev"
}
Expand Down
10 changes: 10 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?xml version='1.0' encoding='utf-8' ?>
<phpunit
bootstrap="./tests/bootstrap.php"
>
<testsuites>
<testsuite name="Snippet Manager Test Suit">
<directory>./tests/</directory>
</testsuite>
</testsuites>
</phpunit>
37 changes: 37 additions & 0 deletions tests/Service/RssServiceTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

namespace Service;

use PHPUnit_Framework_TestCase;

/**
* integration test
*/
class RssServiceTest extends PHPUnit_Framework_TestCase
{
protected $app;
/**
* @var \Service\RssService
*/
protected $rssService;
public function setUp()
{
$this->app = getApp();
$this->app->boot();
$this->rssService = $this->app["rss_service"];
}

public function testConstruct()
{
$this->assertNotNull($this->app["rss_service"]);
$this->assertInstanceOf('\Service\RssService', $this->app["rss_service"]);
}

public function testGenerate()
{
$category = "PHP";
$feed = $this->rssService->generate($category);
$this->assertInternalType("string",$feed);
print($feed);
}
}
17 changes: 17 additions & 0 deletions tests/bootstrap.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php
use Silex\Application;

/**
* Bootstrap file for phpunit
*/
$autoload = require __DIR__ . "/../vendor/autoload.php";
$autoload->add("",__DIR__."/../app");
/**
* @return Silex\Application
*/
function getApp()
{
return new SnippetManager();
}


0 comments on commit dcb762f

Please sign in to comment.