Archives pour la catégorie Dev

Symfony2 how to add a response header for each request

JsonResponseListener.php

<?php
namespace MyCorp\MyBundle\Listener;
 
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
 
class JsonResponseListener
{
    public function onKernelResponse(FilterResponseEvent $event)
    {   
        $request = $event->getRequest();
 
        if(strpos($request->getHost(), 'api.') === false) {
            return;
        }                                                                                                                                                                                                                         
        $event->getResponse()->headers->set('Access-Control-Allow-Headers', 'origin, content-type, accept');
        $event->getResponse()->headers->set('Access-Control-Allow-Origin', '*');
        $event->getResponse()->headers->set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE OPTIONS');
    }   
}

services.xml

<?xml version="1.0" ?>
 
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
 
    <services>
        <service id="mycorp.filter_response_listener" class="MyCorp\MyBundle\Listener\JsonResponseListener">
            <tag name="kernel.event_listener" event="kernel.response" method="onKernelResponse" />
        </service>
    </services>
</container>

mongodb/mongoose simulate rand() on mysql

with nodejs mongoose odm

        var d = 1
        var rand = Math.random();
        var question_count = models.question.count({ difficulty: d}, function(err, count) {
            if(err) {
                console.log(err);
                return;
            }
            models.question.findOne({ difficulty: d }).limit(-1).skip( rand * count).exec(function(err, doc) {
                if(err) {
                    console.log(err);
                    return;
                }
                if(doc) {
                    res.respond(doc);
                } else {
                    res.respond(404);
                }
            });
        });

php cron lock method

<?php
class CronJob {
  private $_lock;
 
  public function __construct() {
        $this->_lock = fopen(__FILE__, 'r');
 
        if (!flock($this->_lock, LOCK_EX|LOCK_NB)) {
            die('already running !'.PHP_EOL);
        }
  }
 
  public function doTheJob() {
        // DO THE JOB HERE
  }
 
  public function __destruct(){
       flock($this->_lock, LOCK_UN);
       fclose($this->_lock);
  }
}

php.net:flock

Twig filter example

$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path' => __DIR__.'/../src/Views',
    'twig.options'          => array(
        'charset'           => 'utf-8',
        'strict_variables'  => true,
        'cache'             => __DIR__.'/cache'
    )
));
 
$app->before(function() use($app) {
    $app['twig']->addExtension(new \Twig\MyExtension($app));
});
<?php
namespace Twig;
 
class MyExtension extends \Twig_Extension {
 
    public function getName() {
        return 'my';
    }
 
    public function getFilters() {
        return array(
            'link' => new \Twig_Filter_Method($this, 'link_filter', array('is_safe' => array('html'))),
        );
    }
 
    public function link_filter($ressource, $type = null) {
        $img_regex = '#(gif|jpe?g|png)$#i';
        $url_regex = '#^(https?:\/\/)#i';
        if(!$type) {
            if(preg_match($img_regex, $ressource)) {
                $type = 'img';
            } else if(preg_match($url_regex, $ressource)) {
                $type = 'a';
            }
        }
        switch($type) {
        case 'img':
            return '<img src="'.$ressource.'"/>';
            break;
        case 'a':
            return '<a href="'.$ressource.'">'.$ressource.'</a>';
            break;
        default:
            return $ressource;
        }
    }
}
<p>
{{ ressource|link }}
</p>

php array recursive find function

<?php
 
$array1 = array(
    0 => array(
        'id' => 1,
        'name' => 'HiO'
    ),
    1 => array(
        'id' => 2,
        'name' => 'Hyun'
    ),
    'key0' => array(
        'id' => 3,
        'name' => 'test'
    )
);
 
 
$array2 = array(
    0 => array(
        'id' => 15, 
        'name' => 'Plop'
    ),
    1 => array(
        'id' => 4,
        'name' => 'Hyun'
    ),
    2 => array(
        'id' => 56,
        'name' => 'Hehe'
    ),
    3 => array(
        0 => array(
            'id' => 10,
            'name' => 'Hi0',
            'key' => array(
                'id' => 1,
                'name' => 'HiO'
            )
        )
    )
);
 
function find($index, $search, $array) {
    foreach($array as $key => $value) {
        if(is_array($value)) {
            if(find($index, $search, $value)) {
                return true;
            }
        }
        if($key == $index && $value == $search)
            return true;
    }
    return false;
}
 
$not_found_array = array();
$found_array = array();
foreach($array1 as $key => $value) {
    if($find = find('name', $value['name'], $array2)) {
        echo $value['name'].' found !<br />';
        $found_array[] = $value;
    } else {
        echo $value['name'].' not found !<br />';
        $not_found_array[] = $value;
    }
}
 
var_dump($not_found_array, $found_array);

Design pattern decorator

<?php
 
interface IDecorator {
    public function decorate();
}
 
abstract class Decorator implements IDecorator {
    protected $_toDecorate;
 
    public function __construct(IDecorator $toDecorate) {
        $this->_toDecorate = $toDecorate;
    }
}
 
class Html implements IDecorator {
    protected $_str;
 
    public function __construct($str) {
        $this->_str = $str;
    }
 
    public function decorate() {
        return $this->_str;
    }
}
 
class Strong extends Decorator {
    public function decorate() {
        return '<strong>'.$this->_toDecorate->decorate().'</strong>';
    }
}
 
class Em extends Decorator {
    public function decorate() {
        return '<em>'.$this->_toDecorate->decorate().'</em>';
    }
}
 
 
$html = new Html('text to decorate');
 
$decorate = new Strong($html);
$decorated = $decorate->decorate();
echo $decorated.PHP_EOL;
 
$decorate = new Em($html);
$decorated = $decorate->decorate();
echo $decorated.PHP_EOL;
 
$decorate = new Strong(new Em($html));
$decorated = $decorate->decorate();
echo $decorated.PHP_EOL;

Symfony2 preExecute Controller

Listener/PublisherListener.php

<?php
namespace Main\PublisherBundle\Listener;
 
use Symfony\Component\EventDispatcher\Event; 
use Symfony\Component\HttpKernel\HttpKernelInterface; 
use Symfony\Component\HttpKernel\Event\FilterControllerEvent; 
 
class PublisherListener {
 
    public function onCoreController(FilterControllerEvent $event) {
        if(HttpKernelInterface::MASTER_REQUEST == $event->getRequestType()) {
            $_controller = $event->getController();
            if(isset($_controller[0])) {
                $controller = $_controller[0];
                if(method_exists($controller, 'preExecute')) {
                    $controller->preExecute();
                }
            }
        }
    }
}

Resources/config/services.xml

<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
 
    <parameters>
        <parameter key="main_publisher.listener.class">Main\PublisherBundle\Listener\PublisherListener</parameter>
    </parameters>
 
    <services>
        <service id="main_publisher_listener" class="%main_publisher.listener.class%">
            <tag name="kernel.event_listener" event="kernel.controller" method="onCoreController"/>
        </service>
    </services>
</container>

Controller/PublisherController.php

<?php
namespace Main\PublisherBundle\Controller;
 
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
 
class GamesController extends Controller {
   public function preExecute() {
        $this->gameManager = $this->container->get('main_publisher.game.manager');
        $this->userManager = $this->container->get('main_user_manager');
    }
}

symfony2 twig i18n date

sudo aptitude install php5-intl

app/config/config.yml

services:
    twig.extension.intl:
       class: Twig_Extensions_Extension_Intl
       tags:
           - { name: twig.extension }

In twig template

{{ game.created_at| localizeddate('full', 'none') }}

twig macro link title translation

{% macro link(route, title, name, attr) %}
{% spaceless %}
<a href="{{ path(route) }}" title="{{ title|trans({}, 'link') }}"{% for attrname,attrvalue in attr %} {{attrname}}="{{attrvalue}}"{% endfor %}>{{ name|trans({}, 'link') }}</a>
{% endspaceless %}
{% endmacro %}
 
<!-- Usage 
{{ macro.link('route_name', 'link title', 'link name', {'class':'css_class'}) }}
-->
 
<!-- HTML
<a href="/dashboard" title="Manage" class="pouet">Manage</a>
-->

Symfony2 service + manager

Resources/config/services.xml

<?xml version="1.0" ?>
 
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
 
    <parameters>
        <parameter key="main_publisher.game.manager.class">Main\PublisherBundle\Manager\GameManager</parameter>
    </parameters>
 
    <services>
        <service id="main_publisher.game.manager" class="%main_publisher.game.manager.class%">
            <argument type="service" id="doctrine.orm.entity_manager" />
        </service>
    </services>
</container>

Manager/BaseManager.php

<?php
namespace Main\PublisherBundle\Manager;
 
class BaseManager {
 
    protected function persistAndFlush($entity) {
        $this->_em->persist($entity);
        $this->_em->flush();
    }
 
}

Manager/GameManager.php

<?php
namespace Main\PublisherBundle\Manager;
 
use Doctrine\ORM\EntityManager;
use Main\PublisherBundle\Manager\BaseManager;
use Main\PublisherBundle\Entity\Game;
 
class GameManager extends BaseManager {
    protected $_em;
 
    public function __construct(EntityManager $em) {
        $this->_em = $em;
    } 
 
    public function save(Game $game) {
        return $this->persistAndFlush($game);
    }
 
    public function getRepository() {
        return $this->_em->getRepository('MainPublisherBundle:Game');
    }
}

Controller/GamesController.php

<?php
 
namespace Main\PublisherBundle\Controller;
 
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
 
use Main\PublisherBundle\Entity\Game;
use Main\PublisherBundle\Form\GameType;
 
class GamesController extends Controller
{
    public function newAction(Request $request) {
        $form = $this->createForm(new GameType(), new Game());
        if($request->getMethod() == 'POST') {
            $form->bindRequest($request);
            if($form->isValid()) {
                $game = $form->getData();
                $manager = $this->container->get('main_publisher.game.manager');
                $manager->save($game);
                return $this->redirect($this->get('router')->generate('homepage'));
            }
 
        }
        return $this->render('MainPublisherBundle:Games:new.html.twig',
            array('form' => $form->createView()));
    }
}