Code Snippets

New project offshoots

So, in the never ending endeavor to make things as easy as possible for people to work with, I have a new mini project (actually two!).

majaxInstallerPlugin for symfony (only tested on 1.4.x)


MajaxInstaller for everyone else!

MajaxInstaller takes an XML configuration and prompts users interactive questions about the files you describe, to get easy configuration details.

The symfony plugin is just designed to be better integrated into symfony, accepting a yaml config file, and adding a majax:install task

There are no phpunit tests yet in the repository for MajaxInstaller, though I have one or two in majaxInstallerPlugin that actually test the base framework.

I look forward to hearing what people think!

A simple example on how to use post validators in symfony

Someone came into the #symfony channel on freenode asking how to add conditional validators that would require a text box to be filled out when a checkbox was ticked. As I realize this is a common question (though the circumstances may change), I wanted to put this example up here as well, for others.

Here’s the example:

class TestForm
  public function configure()
    // ... snip ...
      new sfValidatorCallback(array('callback' => array($this, 'contextualChecks')))
  public function contextualChecks($validator, $values)
    if ($values['checkbox_1'] == 1)
      if ($values['textbox_for_checkbox_1'] == '')
        $error = new sfValidatorError($validator, 'Field is required when Checkbox 1 is checked.');
        $ves = new sfValidatorErrorSchema($validator, array('textbox_for_checkbox_1' => $error));
        throw $ves;
    return $values;

Note: I completely left out returning $values in the initial draft. I apologize!

Taking base_convert past base 36

When building my URL shortener, ZapX, I ran into a bit of a problem. I wanted to be able to make the shortest possible urls using the characters 0-9, a-z, and A-Z, otherwise known as base 62.

PHP’s native base_convert only goes up to base 36, so I was forced to resort to my own devices to get the job done. Long story short, here’s one that goes up to base 62:

function extended_base_convert($dec, $base)
 $numchart = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
 $min_base = 2;
 $max_base = strlen($numchart);
 if ($base < $min_base || $base > $max_base)
  return 'N/A';
 $value = $dec;
 $ptr = ceil($value / $base);
 $buf = array();
 do {
  $buf[$ptr] = substr($numchart, ($value % $base), 1);
  $value = intval($value / $base);
 } while ($value > 0);
 $buf = array_reverse($buf);
 return implode('', $buf);