RegionRestriction::address_filter PHP Method

address_filter() public static method

Produce a SQL filter to get matching RegionRestrictions to a given address
public static address_filter ( Address $address )
$address Address
    public static function address_filter(Address $address)
    {
        $restrictables = array("Country", "State", "City");
        $where = array();
        $rr = "\"RegionRestriction\".";
        foreach ($restrictables as $field) {
            $where[] = "TRIM(LOWER({$rr}\"{$field}\")) = TRIM(LOWER('" . Convert::raw2sql($address->{$field}) . "')) OR {$rr}\"{$field}\" = '*' OR {$rr}\"{$field}\" = ''";
        }
        // check that the country is set to the uk
        if ($address->Country == 'GB') {
            // will check for partial postcodes (eg. NE, NE17, NE177AH)
            $postcode = self::parse_uk_postcode($address->PostalCode);
            if (isset($postcode['validate']) && $postcode['validate']) {
                $region = preg_replace("/[^a-z]+/i", "", substr($postcode['prefix'], 0, 2));
                $where[] = "TRIM(LOWER({$rr}\"PostalCode\")) = TRIM(LOWER('" . Convert::raw2sql($region) . "')) OR TRIM(LOWER({$rr}\"PostalCode\")) = TRIM(LOWER('" . Convert::raw2sql($postcode['prefix']) . "')) OR TRIM(LOWER({$rr}\"PostalCode\")) = TRIM(LOWER('" . Convert::raw2sql($postcode['prefix'] . $postcode['suffix']) . "')) OR {$rr}\"PostalCode\" = '*' OR {$rr}\"PostalCode\" = ''";
            } else {
                $where[] = "TRIM(LOWER({$rr}\"PostalCode\")) = TRIM(LOWER('" . Convert::raw2sql($address->PostalCode) . "')) OR {$rr}\"PostalCode\" = '*' OR {$rr}\"PostalCode\" = ''";
            }
        } else {
            $where[] = "TRIM(LOWER({$rr}\"PostalCode\")) = TRIM(LOWER('" . Convert::raw2sql($address->PostalCode) . "')) OR {$rr}\"PostalCode\" = '*' OR {$rr}\"PostalCode\" = ''";
        }
        return "(" . implode(") AND (", $where) . ")";
    }

Usage Example

 function getRate($address = null)
 {
     if (!$address) {
         $address = singleton('Address');
     }
     $where = array("\"TaxRate\".\"TaxClassID\" = {$this->ID}", RegionRestriction::address_filter($address));
     $sort = implode(', ', array(RegionRestriction::wildcard_sort("PostalCode"), RegionRestriction::wildcard_sort("City"), RegionRestriction::wildcard_sort("State"), RegionRestriction::wildcard_sort("Country"), "\"Rate\" ASC"));
     if ($rate = DataObject::get_one("TaxRate", "(" . implode(") AND (", $where) . ")", true, $sort)) {
         return $rate->Rate;
     }
     return 0;
 }
All Usage Examples Of RegionRestriction::address_filter