fourfiveone/address-formatter

A simple, flexible package for formatting addresses.

This package's canonical repository appears to be gone and the package has been frozen as a result.

1.0.4 2018-01-31 16:41 UTC

This package is not auto-updated.

Last update: 2020-04-26 16:06:49 UTC


README

A simple, flexible package for formatting addresses.

Table Of Contents

Introduction

This genisis of this package comes from trying to find a dead simple address formatter that allows for a variable amount of street lines. Other packages either had no capacity for a variable amount of street lines or allowed an arbitrary maximum of street lines. This package currently only supports US formatted addresses but will hopefully expand to other formats in the future.

This package is licensed under the GPL v3.0. For more information please see the LICENSE.txt file.

Documentation

Basic Use Case

use FourFiveOne\AddressFormatter\AddressFormatter

...

$formatter = new AddressFormatter;

$formatter->set('recipiant', 'Elwood Blues');
$formatter->set('street', '1060 W. Addison');
$formatter->set('city', 'Chicago');
$formatter->set('state', 'IL');
$formatter->set('postal_code', '60613');

echo $formatter->format();

---

Outputs:

Elwood Blues
1060 W. Addison
Chicago, IL 660613

Keys

The address is broken down into the following keys:

  • recipiant
  • street
  • city
  • state
  • postal_code
  • country

If an invalid key is passed to one of the functions, an InvalidKeyException will be thrown.

Get

Getting a single field can be done with:

$formatter->get($key);

Set

Setting a single field can be done with:

$formatter->set($key, $value);

There area few small things that can be done to make your life easier. Both the 'recipiant' and 'street' keys can have multiple lines and are stored as arrays in the class. You can pass in a string or an array to set either of these. For example, both of the following works:

$formatter->set('street', '1060 W. Addison');
$formatter->set('street', ['1060 W. Addison', 'Apt. 1']);

Often times, address lines are stored in the database as separate columns as address_1, address_2, etc... There is a helper function to add a line to the street array one at a time:

$dbResult = [
    'address_1' => '1060 W. Addison',
    'address_2' => 'Apt. 1',
];

foreach( $dbResult as $key => $value ) {
    switch($key) {
    case 'address_1':
    case 'address_2':
        $formatter->addStreetLine($value);
        break;

    ...

    }
}

This works for the recipiant field as well.

Format

To display the formatted address simply output the return of the format() function:

echo $formatter->format();

The format function takes into account if certain fields are null and adjusts the line breaks and punctuation accordingly. Any combination of fields present and/or missing should be displayed properly.