Code snippets for symfony 1.x

Navigation

Extra Number Helpers

Here are some extra helpers that I don't think are in symfony anywhere. They would fit rather nicely in the 'Number' helper group.

Example

<!-- someTemplateSuccess.php -->
<?php use_helper('NumberPlus') ?>
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Phone</th>
      <th>Credit Card</th>
      <th>Exp.</th>
      <th>Income</th>
      <th>SSN</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($users as $user): ?>
      <tr>
        <td><?php echo $user->getName() ?></td>
        <td><?php echo format_phone($user->getPhone()) ?></td>
        <td><?php echo mask_credit_card($user->getCc()) ?></td>
        <td><?php echo format_exp($user->getExp()) ?></td>
        <td><?php echo format_usd($user->getIncome()) ?></td>
        <td><?php echo format_ssn($user->getSsn()) ?></td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

The Code

<?php
 
/**
 * Formats a number by injecting nonnumeric characters in a specified format
 * into the string in the positions they appear in the format.
 *
 * <strong>Example:</strong>
 * <code>
 *  echo format_string('1234567890', '(000) 000-0000');
 *  // => (123) 456-7890
 *
 *  echo format_string('1234567890', '000.000.0000');
 *  // => 123.456.7890
 * </code>
 *
 * @param string the string to format
 * @param string the format to apply
 * @return the formatted string
 */
function format_string($string, $format)
{
   if ($format == '' || $string == '') return $string;
 
   $result = '';
   $fpos = 0;
   $spos = 0;
   while ((strlen($format) - 1) >= $fpos)
   {
       if (is_alphanumeric(substr($format, $fpos, 1)))
       {
           $result .= substr($string, $spos, 1);
           $spos++;
       }
       else
       {
           $result .= substr($format, $fpos, 1);
       }
 
       $fpos++;
   }
 
   return $result;
}
 
/**
 * Transforms a number by masking characters in a specified mask format,
 * and ignoring characters that should be injected into the string without
 * matching a character from the original string (defaults to space).
 *
 * <strong>Example:</strong>
 * <code>
 *  echo mask_string('1234567812345678', '************0000');
 *  // => ************5678
 *
 *  echo mask_string('1234567812345678', '**** **** **** 0000');
 *  // => **** **** **** 5678
 *
 *  echo mask_string('1234567812345678', '**** - **** - **** - 0000', ' -');
 *  // => **** - **** - **** - 5678
 * </code>
 *
 * @param string the string to transform
 * @param string the mask format
 * @param string a string (defaults to a single space) containing characters to ignore in the format
 * @return string the masked string
 */
function mask_string($string, $format, $ignore = ' ')
{
    if ($format == '' || $string == '') return $string;
 
    $result = '';
    $fpos = 0;
    $spos = 0;
    while ((strlen($format) - 1) >= $fpos)
    {
        if (is_alphanumeric(substr($format, $fpos, 1)))
        {
            $result .= substr($string, $spos, 1);
            $spos++;
        }
        else
        {
            $result .= substr($format, $fpos, 1);
 
            if (strpos($ignore, substr($format, $fpos, 1)) === false) $spos++;
        }
 
        $fpos++;
    }
 
    return $result;
}
 
/**
 * Formats a phone number.
 *
 * @param string the unformatted phone number to format
 * @param string the format to use, defaults to '(000) 000-0000'
 * @return string the formatted string
 *
 * @see format_string
 */
function format_phone($string, $format = '(000) 000-0000')
{
    return format_string($string, $format);
}
 
/**
 * Formats a variable length phone number, using a standard format.
 *
 * <strong>Example:</strong>
 * <code>
 *  echo smart_format_phone('1234567');
 *  // => 123-4567
 *
 *  echo smart_format_phone('1234567890');
 *  // => (123) 456-7890
 *
 *  echo smart_format_phone('91234567890');
 *  // => 9 (123) 456-7890
 *
 *  echo smart_format_phone('123456');
 *  // => 123456
 * </code>
 *
 * @param string the unformatted phone number to format
 *
 * @see format_string
 */
function smart_format_phone($string)
{
    switch (strlen($string))
    {
        case 7:
            return format_string($string, '000-0000');
        case 10:
            return format_string($string, '(000) 000-0000');
        case 11:
            return format_string($string, '0 (000) 000-0000');
        default:
            return $string;
    }
}
 
/**
 * Formats a U.S. Social Security Number.
 *
 * <strong>Example:</strong>
 * <code>
 *  echo format_ssn('123456789');
 *  // => 123-45-6789
 * </code>
 *
 * @param string the unformatted ssn to format
 * @param string the format to use, defaults to '000-00-0000'
 *
 * @see format_string
 */
function format_ssn($string, $format = '000-00-0000')
{
    return format_string($string, $format);
}
 
/**
 * Formats a credit card expiration string. Expects 4-digit string (MMYY).
 *
 * @param string the unformatted expiration string to format
 * @param string the format to use, defaults to '00-00'
 *
 * @see format_string
 */
function format_exp($string, $format = '00-00')
{
    return format_string($string, $format);
}
 
/**
 * Formats (masks) a credit card.
 *
 * @param string the unformatted credit card number to format
 * @param string the format to use, defaults to '**** **** **** 0000'
 *
 * @see mask_string
 */
function mask_credit_card($string, $format = '**** **** **** 0000')
{
    return mask_string($string, $format);
}
 
/**
 * Formats a USD currency value with two decimal places and a dollar sign.
 *
 * @param string the unformatted amount to format
 * @param string the format to use, defaults to '$%0.2f'
 *
 * @see sprintf
 */
function format_usd($money, $dollar = true, $format = '%0.2f')
{
    return ($dollar ? '$' : '') . sprintf($format, $money);
}
 
/**
 * Determines if a string has only alpha/numeric characters.
 *
 * @param string the string to check as alpha/numeric
 *
 * @see is_numeric
 * @see preg_match
 */
function is_alphanumeric($string)
{
    return preg_match('/[0-9a-zA-Z]/', $string);
}

NOTE: Place this in something like myproj/apps/myapp/lib/helper/NumberPlusHelper.php

by Stephen Riesenberg on 2007-03-16, tagged helper  number  template 

Comments on this snippet

gravatar icon
#1 Jan Markmann on 2007-03-16 at 11:26

looks like format_string can not take formats that specify how to handle strings that are longer than the format string itself.

also all formats seem to apply to the US only, should be a little more international, phone numbers used to include country codes and in some country the area code may be longer than 3 diggits.

by the way format_usd() is already handlet by format_currency() from the number helpers.

is_alphanumeric() could be done without a regex, its just checking a simple character, what about a simple condition thats matches its ascii integer values range.

Too me it looks like this is more an extension of the NumberHelper than the TextHelper. Perhaps take a look at the NumberHelper and how it works using sfNumberFormat::format(), and addapt that for your new helper, that might bring you to a cleaner and more international approach that. Then it might become a real candiate to get integrated into the existing number helper.

gravatar icon
#2 Stephen Riesenberg on 2007-03-17 at 02:54

Finally, somebody commented on a snippet, even if it is constructive criticism. Yeah, I admit I wasn't going for a terribly i18n-ized feel here. Also, you're right, the format_usd for instance is already done by format_currency. For some reason, I'm too lazy to remove things that wouldn't apply... heh.

Also, a possible reason why such helpers aren't already in the symfony core might be because something like format_phone would be less elegant if it handled all cultures. Kind of how format_number (in NumberHelper) is obfuscated by using the sfNumberFormat class.

Thanks. I'll think about it.

gravatar icon
#3 Stephen Riesenberg on 2007-03-17 at 02:57

Shoot, I forgot to say: I think the important thing here is format_string and mask_string, not really the other wrapper functions. The observant reader might realize it's up to them to put these helpers to good use... Unless someone wants to contribute helpers based on mine? (duh duh duh!!!)

gravatar icon
#4 halfer on 2007-03-20 at 06:39

mask_credit_card() sounds like a good idea, but it implies that a credit card is kept on record in full. Generally this is not a good idea - it's much safer to store most of the card and force the user to enter the last few digits, as an additional security measure. Sorry to provide further criticism, hope it is constructive ;-)

gravatar icon
#5 Stephen Riesenberg on 2007-03-23 at 11:31

Hmm... I'm sure that argument could go both ways. I'm pretty sure stores like Amazon do store the whole thing, since I have ordered before without entering any numbers. Not to mention, I have no say over the types of information my client needs to store. I see your point on the security issue, however. And I think you're right that mask_credit_card() wouldn't make much sense in a situation where you're not storing the whole number.