dataClass = $dataClass; $this->dataQuery = new DataQuery($this->dataClass); parent::__construct(); } /** * Set the DataModel * * @param DataModel $model */ public function setDataModel(DataModel $model) { $this->model = $model; } /** * Get the dataClass name for this DataList, ie the DataObject ClassName * * @return string */ public function dataClass() { return $this->dataClass; } /** * When cloning this object, clone the dataQuery object as well */ public function __clone() { $this->dataQuery = clone $this->dataQuery; } /** * Return the internal {@link DataQuery} object for direct manipulation * * @return DataQuery */ public function dataQuery() { return $this->dataQuery; } /** * Returns the SQL query that will be used to get this DataList's records. Good for debugging. :-) * * @return SQLQuery */ public function sql() { return $this->dataQuery->query()->sql(); } /** * Add a WHERE clause to the query. * * @param string $filter Escaped SQL statement * @return DataList */ public function where($filter) { $this->dataQuery->where($filter); return $this; } /** * Returns true if this DataList can be sorted by the given field. * * @param string $fieldName * @return boolean */ public function canSortBy($fieldName) { return $this->dataQuery()->query()->canSortBy($fieldName); } /** * * @param string $fieldName * @return boolean */ public function canFilterBy($fieldName) { if($t = singleton($this->dataClass)->hasDatabaseField($fieldName)){ return true; } return false; } /** * Add an join clause to this data list's query. * * @param type $join Escaped SQL statement * @return DataList * @deprecated 3.0 */ public function join($join) { Deprecation::notice('3.0', 'Use innerJoin() or leftJoin() instead.'); $this->dataQuery->join($join); return $this; } /** * Restrict the records returned in this query by a limit clause * * @param int $limit * @param int $offset */ public function limit($limit, $offset = 0) { if(!$limit && !$offset) { return $this; } if($limit && !is_numeric($limit)) { Deprecation::notice('3.0', 'Please pass limits as 2 arguments, rather than an array or SQL fragment.'); } $this->dataQuery->limit($limit, $offset); return $this; } /** * Set the sort order of this data list * * @see SS_List::sort() * @see SQLQuery::orderby * @example $list->sort('Name'); // default ASC sorting * @example $list->sort('Name DESC'); // DESC sorting * @example $list->sort('Name', 'ASC'); * @example $list->sort(array('Name'=>'ASC,'Age'=>'DESC')); * * @param String|array Escaped SQL statement. If passed as array, all keys and values are assumed to be escaped. * @return DataList */ public function sort() { if(count(func_get_args()) == 0) { return $this; } if(count(func_get_args()) > 2) { throw new InvalidArgumentException('This method takes zero, one or two arguments'); } if(count(func_get_args()) == 2) { // sort('Name','Desc') if(!in_array(strtolower(func_get_arg(1)),array('desc','asc'))){ user_error('Second argument to sort must be either ASC or DESC'); } $this->dataQuery->sort(func_get_arg(0), func_get_arg(1)); } else if(is_string(func_get_arg(0)) && func_get_arg(0)){ // sort('Name ASC') if(stristr(func_get_arg(0), ' asc') || stristr(func_get_arg(0), ' desc')) { $this->dataQuery->sort(func_get_arg(0)); } else { $this->dataQuery->sort(func_get_arg(0), 'ASC'); } } else if(is_array(func_get_arg(0))) { // sort(array('Name'=>'desc')); $this->dataQuery->sort(null, null); // wipe the sort foreach(func_get_arg(0) as $col => $dir) { // Convert column expressions to SQL fragment, while still allowing the passing of raw SQL fragments. try { $relCol = $this->getRelationName($col); } catch(InvalidArgumentException $e) { $relCol = $col; } $this->dataQuery->sort($relCol, $dir, false); } } return $this; } /** * Filter the list to include items with these charactaristics * * @see SS_List::filter() * * @example $list->filter('Name', 'bob'); // only bob in the list * @example $list->filter('Name', array('aziz', 'bob'); // aziz and bob in list * @example $list->filter(array('Name'=>'bob, 'Age'=>21)); // bob with the age 21 * @example $list->filter(array('Name'=>'bob, 'Age'=>array(21, 43))); // bob with the Age 21 or 43 * @example $list->filter(array('Name'=>array('aziz','bob'), 'Age'=>array(21, 43))); // aziz with the age 21 or 43 and bob with the Age 21 or 43 * * @todo extract the sql from $customQuery into a SQLGenerator class * * @param string|array Escaped SQL statement. If passed as array, all keys and values are assumed to be escaped. * @return DataList */ public function filter() { // Validate and process arguments $arguments = func_get_args(); switch(sizeof($arguments)) { case 1: $filters = $arguments[0]; break; case 2: $filters = array($arguments[0] => $arguments[1]); break; default: throw new InvalidArgumentException('Incorrect number of arguments passed to filter()'); } $clone = clone $this; $clone->addFilter($filters); return $clone; } /** * Modify this DataList, adding a filter */ public function addFilter($filterArray) { $SQL_Statements = array(); foreach($filterArray as $field => $value) { if(is_array($value)) { $customQuery = 'IN (\''.implode('\',\'',Convert::raw2sql($value)).'\')'; } else { $customQuery = '= \''.Convert::raw2sql($value).'\''; } if(stristr($field,':')) { $fieldArgs = explode(':',$field); $field = array_shift($fieldArgs); foreach($fieldArgs as $fieldArg){ $comparisor = $this->applyFilterContext($field, $fieldArg, $value); } } else { if($field == 'ID') { $field = sprintf('"%s"."ID"', ClassInfo::baseDataClass($this->dataClass)); } else { $field = '"' . Convert::raw2sql($field) . '"'; } $SQL_Statements[] = $field . ' ' . $customQuery; } } if(count($SQL_Statements)) { foreach($SQL_Statements as $SQL_Statement){ $this->dataQuery->where($SQL_Statement); } } return $this; } /** * Filter this DataList by a callback function. * The function will be passed each record of the DataList in turn, and must return true for the record to be included. * Returns the filtered list. * * Note that, in the current implementation, the filtered list will be an ArrayList, but this may change in a future * implementation. */ public function filterByCallback($callback) { if(!is_callable($callback)) throw new LogicException("DataList::filterByCallback() must be passed something callable."); $output = new ArrayList; foreach($this as $item) { if($callback($item)) $output->push($item); } return $output; } /** * Translates a Object relation name to a Database name and apply the relation join to * the query. Throws an InvalidArgumentException if the $field doesn't correspond to a relation * * @param string $field * @return string */ public function getRelationName($field) { if(!preg_match('/^[A-Z0-9._]+$/i', $field)) { throw new InvalidArgumentException("Bad field expression $field"); } if(strpos($field,'.') === false) { return '"'.$field.'"'; } $relations = explode('.', $field); $fieldName = array_pop($relations); $relationModelName = $this->dataQuery->applyRelation($field); return '"'.$relationModelName.'"."'.$fieldName.'"'; } /** * Translates the comparisator to the sql query * * @param string $field - the fieldname in the db * @param string $comparisators - example StartsWith, relates to a filtercontext * @param string $value - the value that the filtercontext will use for matching * @todo Deprecated SearchContexts and pull their functionality into the core of the ORM */ private function applyFilterContext($field, $comparisators, $value) { $t = singleton($this->dataClass())->dbObject($field); $className = "{$comparisators}Filter"; if(!class_exists($className)){ throw new InvalidArgumentException('There are no '.$comparisators.' comparisator'); } $t = new $className($field,$value); $t->apply($this->dataQuery()); } /** * Exclude the list to not contain items with these characteristics * * @see SS_List::exclude() * @example $list->exclude('Name', 'bob'); // exclude bob from list * @example $list->exclude('Name', array('aziz', 'bob'); // exclude aziz and bob from list * @example $list->exclude(array('Name'=>'bob, 'Age'=>21)); // exclude bob that has Age 21 * @example $list->exclude(array('Name'=>'bob, 'Age'=>array(21, 43))); // exclude bob with Age 21 or 43 * @example $list->exclude(array('Name'=>array('bob','phil'), 'Age'=>array(21, 43))); // bob age 21 or 43, phil age 21 or 43 would be excluded * * @todo extract the sql from this method into a SQLGenerator class * * @param string|array Escaped SQL statement. If passed as array, all keys and values are assumed to be escaped. * @return DataList */ public function exclude() { $numberFuncArgs = count(func_get_args()); $whereArguments = array(); if($numberFuncArgs == 1 && is_array(func_get_arg(0))) { $whereArguments = func_get_arg(0); } elseif($numberFuncArgs == 2) { $whereArguments[func_get_arg(0)] = func_get_arg(1); } else { throw new InvalidArgumentException('Incorrect number of arguments passed to exclude()'); } $SQL_Statements = array(); foreach($whereArguments as $fieldName => $value) { if($fieldName == 'ID') { $fieldName = sprintf('"%s"."ID"', ClassInfo::baseDataClass($this->dataClass)); } else { $fieldName = '"' . Convert::raw2sql($fieldName) . '"'; } if(is_array($value)){ $SQL_Statements[] = ($fieldName . ' NOT IN (\''.implode('\',\'', Convert::raw2sql($value)).'\')'); } else { $SQL_Statements[] = ($fieldName . ' != \''.Convert::raw2sql($value).'\''); } } $this->dataQuery->whereAny($SQL_Statements); return $this; } /** * This method returns a list does not contain any DataObjects that exists in $list * * It does not return the resulting list, it only adds the constraints on the database to exclude * objects from $list. * The $list passed needs to contain the same dataclass as $this * * @param SS_List $list * @return DataList * @throws BadMethodCallException */ public function subtract(SS_List $list) { if($this->dataclass() != $list->dataclass()) { throw new InvalidArgumentException('The list passed must have the same dataclass as this class'); } $newlist = clone $this; $newlist->dataQuery->subtract($list->dataQuery()); return $newlist; } /** * Add an inner join clause to this data list's query. * * @param string $table Table name (unquoted) * @param string $onClause Escaped SQL statement, e.g. '"Table1"."ID" = "Table2"."ID"' * @param string $alias - if you want this table to be aliased under another name * @return DataList */ public function innerJoin($table, $onClause, $alias = null) { $this->dataQuery->innerJoin($table, $onClause, $alias); return $this; } /** * Add an left join clause to this data list's query. * * @param string $table Table name (unquoted) * @param string $onClause Escaped SQL statement, e.g. '"Table1"."ID" = "Table2"."ID"' * @param string $alias - if you want this table to be aliased under another name * @return DataList */ public function leftJoin($table, $onClause, $alias = null) { $this->dataQuery->leftJoin($table, $onClause, $alias); return $this; } /** * Return an array of the actual items that this DataList contains at this stage. * This is when the query is actually executed. * * @return array */ public function toArray() { $query = $this->dataQuery->query(); $rows = $query->execute(); $results = array(); foreach($rows as $row) { $results[] = $this->createDataObject($row); } return $results; } /** * Return this list as an array and every object it as an sub array as well * * @return type */ public function toNestedArray() { $result = array(); foreach($this as $item) { $result[] = $item->toMap(); } return $result; } public function debug() { $val = "