Archives du mot-clef symfony

Symfony filter SSL

apps/frontend/config/app.yml

  ssl_filter:
    enabled: true
    secure:
      profile:
       actions: ~
      feed:
       actions: ~
      bookmark:
       actions: ~
      alert:
       actions: ~
      sfGuardAuth:
        actions: [signin]
      sfGuardRegister:
        actions: ~
      sfGuardForgotPassword:
        action: ~

lib/filter/sfSslFilter.class.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php
class sfSslFilter extends sfFilter {
  public function execute($filterChain) {
    if(sfConfig::get('app_ssl_filter_enabled', true) && $this->isFirstCall()) {
      $request = $this->getContext()->getRequest();
      if($request->isMethod('get') || $request->isMethod('head')) {
        $context = $this->getContext();
        $controller = $context->getController();
        $stackEntry = $controller->getActionStack()->getLastEntry();
        $module = $stackEntry->getModuleName();
        $action = $stackEntry->getActionName();
        $moduleSettings = sfConfig::get('app_ssl_filter_secure', false);
        if(isset($moduleSettings[$module])) {
          if(isset($moduleSettings[$module]['actions'])){
            if(!$request->isSecure() && is_array($moduleSettings[$module]['actions']) && in_array($action, $moduleSettings[$module]['actions'])) {
              return $this->redirectSecure($request);
            }
          } else if(!$request->isSecure()) {
            return $this->redirectSecure($request);
          }
        }
      }
    }
    $filterChain->execute();
  }
 
  protected function redirectSecure(sfWebRequest $request) {
    $url = str_replace( 'http', 'https', $request->getUri());
    return $this->getContext()->getController()->redirect($url, 0, 301);
  }
}

apps/frontend/config/filters.yml

ssl:
  class: sfSslFilter

Symfony comment délivrer son contenu static a partir de plusieurs cdn

On crée ce fichier dans le répertoire lib/ ou a l’endroit ou on veut du moment que l autoloader de sf peut le trouver, perso je l’ai mit dans lib/vendor/hio/
sfStatics.class.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
class sfStatics {
  static public $statics;
  static public $number;
  static public $index = 0;
  private static $instance = null;
 
  public static function getInstance($statics) {
    if(is_null(self::$instance))
      self::$instance = new sfStatics($statics);
 
    return self::$instance;
  }
 
  public function __construct($statics) {
    self::$statics = $statics;
    self::$number = sizeof($statics)-1;
  }
 
  public function pickOne($n = null) {
    if(is_null($n)) {
      if(self::$index > self::$number)
        self::$index = 0;
 
      $static = self::$statics[self::$index];
      self::$index++;
    } else {
      if(isset(self::$statics[$n])) {
        $static = self::$statics[$n];
      } else {
        $static = self::$statics[0];
      }
    }
    return $static;
  }
 
  public function __toString() {
    return $this->pickOne();
  }
 
}

ensuite on crée un helper qui va bien
mkdir /lib/helper a la racine de son projet (là ou se trouve ./symfony)

StaticHelper.php

<?php
function pickOneStatic($n = null) {
  $a = sfStatics::getInstance(sfConfig::get('app_static_urls'));
  return $a->pickOne($n);
}

on met la liste de ses cdn dans app.yml (apps/frontend/config/app.yml)

# default values
all:
  static:
    urls: ['http://static1.gik.li', 'http://static2.gik.li', 'http://static3.gik.li', 'http://static4.gik.li']

ensuite on passe au chose serieuse dans ses templates

<link rel="shortcut icon" href="<?php echo pickOneStatic(0)?>/images/favicon.ico" />
<link rel="stylesheet" type="text/css" media="screen" href="<?php echo pickOneStatic(0)?>/css/style.min.css" />

dans ses 2 exemples on voit un 0 en argument (0 = le premier cdn de la liste du app.yml), c’est pour délivrer ce contenu tjs a partir du même cdn par exemple qd vous avez plusieurs fois la même images dans une page ou pour que les fichiers js soit cacher correctement par le navigateur

2 eme exemple:

<?php foreach($images as $image): ?>
<?php if(file_exists(sfConfig::get('sf_web_dir').$image->getPath().sfConfig::get('app_images_thumbs_dir').$image->getName())): ?>
<a href="<?php echo url_for('@show?slug='.$image->getContent()->getSlug()) ?>" title="<?php echo $image->getContent()->getTitle() ?>">
    <img src="<strong><?php echo pickOneStatic()?></strong><?php echo $image->getPath().sfConfig::get('app_images_thumbs_dir').$image->getName() ?>" width="60" height="60" alt="<?php echo $image->getName() ?>"/>
</a>
<?php endif ?>
<?php endforeach ?>

donnera

<a href="/gran-turismo-5-suzuka-sous-la-pluie-en-video-la-claque-tout-simplement-1" title="Gran Turismo 5 : Suzuka sous la pluie en vidéo - La claque, tout simplement"> 
    <img src="http://static1.gik.li/img/2010-11-21/thumbs/051cb8a3476f3fe29ee4975ec32d217c72fb7593.jpg" width="60" height="60" alt="051cb8a3476f3fe29ee4975ec32d217c72fb7593.jpg"/> 
</a> 
<a href="/jolibook-now-on-sale-in-the-uk-first-batch-of-orders-ships-monday" title="Jolibook now on sale in the UK, first batch of orders ships Monday"> 
    <img src="http://static2.gik.li/img/2010-11-21/thumbs/067c639cac46fa7fe93748a9de23504c1ede1701.jpg" width="60" height="60" alt="067c639cac46fa7fe93748a9de23504c1ede1701.jpg"/> 
</a> 
<a href="/ea-sports-on-nba-elite-it-was-just-going-to-be-a-bad-game-nba-elite" title="EA Sports On NBA Elite: &quot;It Was Just Going To Be A Bad Game&quot; [Nba Elite]"> 
    <img src="http://static3.gik.li/img/2010-11-21/thumbs/524068c6bd9e5f1ffd40311f843cdbac8acfbfb8.jpg" width="60" height="60" alt="524068c6bd9e5f1ffd40311f843cdbac8acfbfb8.jpg"/> 
</a> 
<a href="/bellemanie-bellemanie-2010-watercolor-ink-drawing" title="bellemanie:
 
Bellemanie - (2010, Watercolor &amp; ink drawing)"> 
    <img src="http://static4.gik.li/img/2010-11-21/thumbs/58c5c1637ea9f1193fc4415ff3e1dc5e2ac77d40.jpg" width="60" height="60" alt="58c5c1637ea9f1193fc4415ff3e1dc5e2ac77d40.jpg"/> 
</a> 
<a href="/laterality-in-canine-cradling-madscience" title="Laterality in canine cradling [Madscience]"> 
    <img src="http://static1.gik.li/img/2010-11-21/thumbs/feb4a03be8a2a201eac3cdd0cfe8d6fb5e00e624.jpg" width="60" height="60" alt="feb4a03be8a2a201eac3cdd0cfe8d6fb5e00e624.jpg"/> 
</a>

et ainsi de suite a chaque appel de la fonction sans argument ça passera au prochain cdn

Comment minifier le js et css d’un projet symfony simplement

Comment minifier le css et le javascript de son projet symfony

On telecharge yuicompressor chez yahoo yuicompressor

pour des besoin de pure fainéantise, on créé le minify.sh a coter de l’exécutable symfony, on met le .jar de yuicompressor dans le même répertoire ou ailleurs mais il faudra le changer dans le script dans se cas là :)

emacs ou vim minify.sh et on colle ça dedant

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/bin/bash
yui='./yuicompressor-2.4.2.jar' # le path du .jar de yuicompressor
css='./web/css/style.min.css' # le path du css minifier
js='./web/js/be-geek.min.js' # le path du js minifier
 
if [ -f "$css" ]; then
    echo "rm: $css"
    rm $css
fi
 
if [ -f "$css.gz" ]; then
    echo "rm: $css.gz"
    rm $css.gz
fi
 
if [ -f "$js" ]; then
    echo "rm: $js"
    rm $js
fi
 
if [ -f "$js.gz" ]; then
    echo "rm: $js.gz"
    rm $js.gz
fi
 
for i in `ls ./web/css/`
do
    echo $i
    java -jar $yui --type css ./web/css/$i >> $css
done
 
for i in `ls ./web/js/`
do
    echo $i
    java -jar $yui --type js ./web/js/$i >> $js
done
 
echo "gzip $css > $css.gz"
gzip -c -n -3 $css > $css.gz
echo "gzip $js > $js.gz"
gzip -c -n -3 $js > $js.gz
 
echo 'done'

ensuite

bash minify.sh

ce qui nous donne

hio@jupiter:~/www/be-geek.com/trunk$ bash minify
rm: ./web/css/style.min.css
rm: ./web/css/style.min.css.gz
rm: ./web/js/be-geek.min.js
rm: ./web/js/be-geek.min.js.gz
jquery.lightbox-0.5.css
main.css
slides.css
style01.css
jquery.be-geek.js
jquery.lightbox-0.5.min.js
slides.jquery.js
gzip ./web/css/style.min.css > ./web/css/style.min.css.gz
gzip ./web/js/be-geek.min.js > ./web/js/be-geek.min.js.gz
done

et dans le view.yml, on vire les autres .js et .css et on ne met plus que les fichier .js et .css minifier

  stylesheets:    [style.min.css]
  javascripts:    [monjs.min.js]

voila c’était trop dur :)

PHP Symfony, Comment définir un groupe avec sfGuardDoctrinePlugin lors d’une inscription

Tout est dans le titre

protected function processForm(sfWebRequest $request, sfForm $form)
{
  $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
  if($form->isValid())
  {
    $register = $form->save();
    $register->addGroupByName('member');
    $register->addPermissionByName('member');
    $register->profile->setSfGuardUserId($register->id);
    $register->save();
    $this->getUser()->signIn($this->form->getObject());
    $this->redirect('@feeds');
  }
  $this->getUser()->setFlash('error','formular is not correctly filled.');
}

PHP Symfony, exemple d’utilisation de widget et validateur

Voici des exemples d’utilisation des widgets et des validateurs symfony, liste mise a jour au fur et a mesure de mes besoins ^^

Widgets

sfWidgetFormDoctrineChoice

$this->widgetSchema['cat_id'] = new sfWidgetFormDoctrineChoice(array('label' => 'Category',
                                                                      'model' => 'hosts_categories',
                                                                      'add_empty' => true));

sfWidgetFormInputPassword

$this->widgetSchema['password'] = new sfWidgetFormInputPassword();

Validateurs

sfValidatorRegex

$this->validatorSchema['intervalle'] = new sfValidatorRegex(array('pattern' => '/^[0-9]{1}[i,m,d]{1}$/'));

sfValidatorOr

$this->validatorSchema['intervalle'] = new sfValidatorOr(array(new sfValidatorRegex(array('pattern' => '/^[0-9]{1}[i,m,d]{1}$/')),
                                                                new sfValidatorRegex(array('pattern' => '/^[0-9]{1}[i,m,d]{1};[0-9]{2}h[0-9]{2}$/'))));

sfValidatorAnd

$this->validatorSchema->setPostValidator(new sfValidatorAnd(array(new sfValidatorSchemaCompare('repassword',  sfValidatorSchemaCompare::EQUAL, 'password'),
                                                                  new sfValidatorDoctrineUnique(array('model' => 'sfGuardUser',
                                                                                                      'column' => 'username'), array('invalid' => 'This username already taken.')),
                                                                  new sfValidatorDoctrineUnique(array('model' => 'sfGuardUser',
                                                                                                      'column' => 'email_address'), array('invalid' => 'This email address already taken.'))
                                                                  )));

sfValidatorSchemaCompare

$this->validatorSchema['password'] = new sfValidatorString(array('min_length' => 5, 'max_length' => 15));
$this->validatorSchema['repassword'] = new sfValidatorString(array('required' => true));
$this->validatorSchema->setPostValidator(new sfValidatorSchemaCompare('repassword',  sfValidatorSchemaCompare::EQUAL, 'password'));

PHP Symfony, Comment passer une valeur a un objet sfForm dans le backend d’une application

apps/backend/modules/hosts/actions/actions.class.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class hostsActions extends autoHostsActions
{
 
  public function executeCreate(sfWebRequest $request)
  {
    $this->form = $this->configuration->getForm();
    $this->hosts = $this->form->getObject();
 
    $tainted_values = $request->getParameter($this->form->getName());     
    $tainted_values['user_id'] = $this->getUser()->getGuardUser()->getId();
 
    $request->setParameter($this->form->getName(), $tainted_values);
    parent::processForm($request, $this->form);
    $this->setTemplate('new');
  }
}

PHP Symfony, Comment changer les messages par defaut des validateurs Symfony

Comment faire , quand on veut changer tous les messages par défaut des validateurs Symfony , sans les définir un par un par un bete ‘message’ => ‘mais blublu’ et sans allez les changer directement dans les entrailles de symfony ce qui est mal !!! C’est mal !!!

oh oui dit nous père castor
Et bien comme ça

1
2
3
    sfValidatorBase::setInvalidMessage('Champ invalide');
    sfValidatorBase::setRequiredMessage('Champ obligatoire');
    parent::setup();

Ce qui nous donne dans un vrai bout de php

VentesForm.class.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
class VentesForm extends BaseVentesForm
{
  public function configure()
  {
    sfValidatorBase::setInvalidMessage('Champ invalide');
    sfValidatorBase::setRequiredMessage('Champ obligatoire');
    parent::setup();
    unset($this['created_at'], $this['updated_at'],
          $this['expires_at'], $this['is_active']);
    $this->widgetSchema['uid'] = new sfWidgetFormInput(array('type' => 'hidden', 'is_hidden' => true));
    $this->widgetSchema['civ'] = new sfWidgetFormChoice(array('choices' => array('M.' => 'M.', 'Mme' => 'Mme', 'Mlle' => 'Mlle')));
    $this->widgetSchema['adresse1'] = new sfWidgetFormTextarea();
    $this->widgetSchema['adresse2'] = new sfWidgetFormTextarea();
    $this->widgetSchema['adresse3'] = new sfWidgetFormTextarea();
    $this->validatorSchema['email'] = new sfValidatorEmail(array(), array('invalid' => 'L\'adresse email saisie est incorrecte'));
    $this->widgetSchema->setLabel('numeroabo', 'N°Abonné');
  }
}

sfValidatorBase

NOTE:
Deprecated depuis la version 1.4 de symfony remplacer par
sfValidatorBase::setDefaultMessage() method

http://www.symfony-project.org/tutorial/1_4/en/deprecated

1
2
3
sfValidatorBase::setDefaultMessage('invalid', 'Champ invalide');
sfValidatorBase::setDefaultMessage('required', 'Champ obligatoire');
parent::setup();

PHP Symfony Text Helper

Text Helper
http://www.symfony-project.org/api/1_4/TextHelper

<?php
echo use_helper('Text')
echo auto_link_text() // Turns all urls and email addresses into clickable links. The +link+ parameter can limit what should be linked.
echo excerpt_text() // Extracts an excerpt from the +text+ surrounding the +phrase+ with a number of characters on each side determined
echo highlight_text($text, $phrase, $highlighter) // Highlights the +phrase+ where it is found in the +text+ by surrounding it like
echo simple_format_text()  // Returns +text+ transformed into html using very simple formatting rules
echo strip_links_text() // Turns all links into words, like "<a href="something">else</a>" to "else".
echo truncate_text() // Truncates +text+ to the length of +length+ and replaces the last three characters with the +truncate_string+
echo wrap_text() // Word wrap long lines to line_width.
echo _auto_link_email_addresses() // Turns all email addresses into clickable links.
echo _auto_link_urls() // Turns all urls into clickable links
?>