MatchObjectFilter::getFilter PHP Method

getFilter() public method

Create SQL where filter
public getFilter ( ) : array
return array of filter statements
    public function getFilter()
    {
        if (!is_array($this->data)) {
            return null;
        }
        $singleton = singleton($this->className);
        $hasones = $singleton->has_one();
        $db = $singleton->db();
        $allowed = array_keys(array_merge($db, $hasones));
        //fields that can be used
        $fields = array_flip(array_intersect($allowed, $this->required));
        //add 'ID' to has one relationship fields
        foreach ($hasones as $key => $value) {
            if (isset($fields[$key])) {
                $fields[$key . "ID"] = $value;
                unset($fields[$key]);
            }
        }
        $new = array();
        foreach ($fields as $field => $value) {
            $field = Convert::raw2sql($field);
            if (array_key_exists($field, $db)) {
                if (isset($this->data[$field])) {
                    $dbfield = $singleton->dbObject($field);
                    $value = $dbfield->prepValueForDB($this->data[$field]);
                    //product correct format for db values
                    // These seems to be a difference in how this works between SS 3.1 and 3.2
                    // It would be great to actually remove this and use something that's more inline with the ORM
                    // But this will get us to 3.2 compatibility and work on every DB I'm aware of.
                    if ($value[0] != "'") {
                        $value = "'{$value}'";
                    }
                    $new[] = "\"{$field}\" = {$value}";
                } else {
                    $new[] = "\"{$field}\" IS NULL";
                }
            } else {
                if (isset($this->data[$field])) {
                    $value = Convert::raw2sql($this->data[$field]);
                    $new[] = "\"{$field}\" = '{$value}'";
                } else {
                    $new[] = "(\"{$field}\" = 0 OR \"{$field}\" IS NULL)";
                }
            }
        }
        return $new;
    }

Usage Example

 public function testMissingValues()
 {
     // Tests that missing values are included in the filter as IS NULL or = 0
     // Missing value for a has_one relationship field.
     $filter = new MatchObjectFilter('Product_OrderItem', array(), array('Product'));
     $this->assertEquals($filter->getFilter(), array('("ProductID" = 0 OR "ProductID" IS NULL)'), 'missing ID value became IS NULL or = 0');
     // Missing value for a db field.
     $filter = new MatchObjectFilter('Product_OrderItem', array(), array('ProductVersion'));
     $this->assertEquals($filter->getFilter(), array('"ProductVersion" IS NULL'), 'missing DB value became IS NULL or = 0');
 }
All Usage Examples Of MatchObjectFilter::getFilter
MatchObjectFilter