Fakoli Framework
data_item.inc File Reference

Go to the source code of this file.

Classes

class  DataItem
 DataItem is the generic base class for database mapped classes. More...
 
class  DataItemFieldComparator
 Simple field comparator to support sorting arrays of DataItems by the values in a specified field. More...
 

Functions

 querySingle ($class)
 Performs a query against the database and returns a matching singleton object. More...
 
 queryValue ($class, $func)
 Query the database to calculate an aggregate value. More...
 
 reindexList ($list, $field, $autoPromote=true)
 Reindex an indexed or grouped query result by a different field. More...
 
 regroupList ($list, $field)
 Regroup an indexed or grouped query result by a different field. More...
 
 removeDuplicates ($list, $field="")
 Remove duplicate DataItems from a list, based on the value of a field. More...
 
 sortList (&$list, $field)
 Sorts an array of DataItems based on the values in the specified field. More...
 
 updateSortOrder ($class, $field="sort_order", $params=null)
 Utility method to update sort order for the selected class of objects based on an array that maps primary keys to sort order values. More...
 
 toXML ($tag, $objects, $header="<?xml version=\.0\encoding=\so-8859-1>")
 
 toJSON ($items)
 
 toJSONGrouped ($items)
 
 displayFieldAsList ($items, $field, $separator=", ")
 
 formatItems ($items, $template, $separator="")
 Format a list of DataItems using the specified templated. More...
 
 extractItems ($items, $indexFormat, $valueFormat)
 
 extractFieldValues ($items, $field)
 Extract the field values for the specified field from a list of DataItems. More...
 
 extractIndexedFieldValues ($items, $field)
 Extract the field values for the specified field from a list of DataItems and return them in an array indexed by the primary key values of the source DataItems. More...
 
 findItem ($items, $field, $value)
 Find the first item in the array that matches the supplied value for the specified field. More...
 
 findItemIndex ($items, $field, $value)
 Find the index of the first item in the array that matches the supplied value for the specified field. More...
 
 restoreHTML ($text)
 
 dumpCSV ($class, $items, $filepath, $filter=null, $append=false)
 Dump a raw representation of a list of DataItems to CSV (one column per field, default format only) More...
 

Function Documentation

◆ displayFieldAsList()

displayFieldAsList (   $items,
  $field,
  $separator = ", " 
)

Definition at line 2018 of file data_item.inc.

2019 {
2020  return formatItems($items, "{".$field."}", $separator);
2021 }
formatItems($items, $template, $separator="")
Format a list of DataItems using the specified templated.
Definition: data_item.inc:2031

◆ dumpCSV()

dumpCSV (   $class,
  $items,
  $filepath,
  $filter = null,
  $append = false 
)

Dump a raw representation of a list of DataItems to CSV (one column per field, default format only)

Parameters
$classclass name of the items to be dumped
$itemsthe items to dump
$filepaththe output file path

Definition at line 2143 of file data_item.inc.

2144 {
2145  $obj = new $class;
2146  $obj->filter = $filter;
2147 
2148  $fields = $obj->getFieldArray();
2149 
2150  if ($append)
2151  {
2152  $fp = fopen($filepath, "a");
2153  }
2154  else
2155  {
2156  $fp = fopen($filepath, "w");
2157  fputcsv($fp, $fields);
2158  }
2159 
2160  foreach($items as $item)
2161  {
2162  $vals = array();
2163  foreach($fields as $field)
2164  {
2165  $vals[] = $item->get($field);
2166  }
2167  fputcsv($fp, $vals);
2168  }
2169  fclose($fp);
2170 }

◆ extractFieldValues()

extractFieldValues (   $items,
  $field 
)

Extract the field values for the specified field from a list of DataItems.

Parameters
$itemsthe DataItems on which to perform the extraction
$fieldthe name of the field to extract
Returns
array an array of the field values in the same order as the presented DataItem list.

Definition at line 2064 of file data_item.inc.

2065 {
2066  $out = array();
2067  foreach($items as $item)
2068  {
2069  $out[] = $item->get($field);
2070  }
2071  return $out;
2072 }

◆ extractIndexedFieldValues()

extractIndexedFieldValues (   $items,
  $field 
)

Extract the field values for the specified field from a list of DataItems and return them in an array indexed by the primary key values of the source DataItems.

Parameters
$itemsthe DataItems on which to perform the extraction
$fieldthe name of the field to extract
Returns
array an array of the field values indexed by the primary key values from the DataItem list.

Definition at line 2081 of file data_item.inc.

2082 {
2083  $out = array();
2084  foreach($items as $item)
2085  {
2086  $out[$item->get($item->getPrimaryKey())] = $item->get($field);
2087  }
2088 
2089  return $out;
2090 }

◆ extractItems()

extractItems (   $items,
  $indexFormat,
  $valueFormat 
)

Definition at line 2047 of file data_item.inc.

2048 {
2049  $list = array();
2050  foreach($items as $item)
2051  {
2052  $list[$item->format($indexFormat)] = $item->format($valueFormat);
2053  }
2054 
2055  return $list;
2056 }

◆ findItem()

findItem (   $items,
  $field,
  $value 
)

Find the first item in the array that matches the supplied value for the specified field.

Parameters
array$itemsthe items to search
string$fieldthe name of the field to match
mixed$valuethe value that must be matched
Returns
DataItem the first matching object, or null if no match is found

Definition at line 2100 of file data_item.inc.

2101 {
2102  foreach($items as $item)
2103  {
2104  if ($item->get($field) == $value) return $item;
2105  }
2106 
2107  return null;
2108 }

◆ findItemIndex()

findItemIndex (   $items,
  $field,
  $value 
)

Find the index of the first item in the array that matches the supplied value for the specified field.

Parameters
array$itemsthe items to search
string$fieldthe name of the field to match
mixed$valuethe value that must be matched
Returns
mixed the index of the first matching object, or false if no match was found

Definition at line 2118 of file data_item.inc.

2119 {
2120  $idx = 0;
2121 
2122  foreach($items as $item)
2123  {
2124  if ($item->get($field) == $value) return $idx;
2125  ++$idx;
2126  }
2127 
2128  return false;
2129 }

◆ formatItems()

formatItems (   $items,
  $template,
  $separator = "" 
)

Format a list of DataItems using the specified templated.

The list is returned as a string with the specifed separator between records.

Parameters
array$itemsthe DataItems to format
string$templatethe format template
string$separatorthe separator to use between records
Returns
string

Definition at line 2031 of file data_item.inc.

2032 {
2033  $list = "";
2034  $first = true;
2035 
2036  foreach($items as $item)
2037  {
2038  if (!$item) continue;
2039  if (!$first) $list .= $separator;
2040  $list .= $item->format($template);
2041  $first = false;
2042  }
2043 
2044  return $list;
2045 }

◆ querySingle()

querySingle (   $class)

Performs a query against the database and returns a matching singleton object.

If the query returns more than one object, and error is thrown.

Parameters
string$classthe class name of the object to query
string$constraintsoptional constraint clause to apply to the query in the form "WHERE ... [ORDER BY ...]"

Definition at line 1711 of file data_item.inc.

1712 {
1713  $constraints = "";
1714 
1715  if (func_num_args() > 1)
1716  {
1717  $constraints = func_get_arg(1);
1718  }
1719 
1720  $result = query($class, $constraints);
1721 
1722  if (count($result) > 1)
1723  {
1724  throw new DataItemException("Ambiguous singleton query");
1725  }
1726 
1727  if (count($result) == 1)
1728  {
1729  return $result[0];
1730  }
1731 
1732  return null;
1733 }
query($class)
Performs a query against the database, returning an array of DataItem objects of the specified class...
Definition: query.inc:360

◆ queryValue()

queryValue (   $class,
  $func 
)

Query the database to calculate an aggregate value.

The database table associated with the specified class is used as the source for the data.

Parameters
string$classthe class name of the object to query
string$functhe value or function to retrieve
string$constraintsoptional constraint clause to apply to the query

Definition at line 1743 of file data_item.inc.

1744 {
1745  $constraints = "";
1746  $value = null;
1747 
1748  if (func_num_args() > 2)
1749  {
1750  $constraints = func_get_arg(2);
1751 
1752  if (func_num_args() > 3)
1753  {
1754  $value = func_get_arg(3);
1755  }
1756  }
1757 
1758  $prototype = new $class;
1759 
1760  if ($constraints == "") $constraints = "WHERE 1=1"; //TODO - tidy this up some day
1761  $constraints .= " ".$prototype->getIdentityConstraint();
1762 
1763  $query = "SELECT $func as result FROM {$prototype->table} $constraints";
1764 
1765  trace($query, 3);
1766 
1767  try
1768  {
1770 
1771  $result = $db->prepare($query);
1772  $result->execute();
1773 
1774  if ($row = $result->fetch())
1775  {
1776  $value = $row['result'];
1777  }
1778 
1779  unset($result);
1780  }
1781  catch(PDOException $e)
1782  {
1783  $err = "queryValue() failed - " . $e->getMessage();
1784  trace($err, 2);
1785  throw new DataItemException($err);
1786  }
1787 
1788  return $value;
1789 }
trace($msg, $lvl, $callStack=null)
Send output to the trace log.
Definition: functions.inc:959
static getConnection()
Retrieves a reference to the global database connection.

◆ regroupList()

regroupList (   $list,
  $field 
)

Regroup an indexed or grouped query result by a different field.

Parameters
array$listan array of DataItem-derived objects, as returned by query(), indexedQuery() or groupedQuery()
string$fieldthe field by which to regroup the list

Definition at line 1849 of file data_item.inc.

1850 {
1851  $result = array();
1852 
1853  foreach($list as $elt)
1854  {
1855  if (is_array($elt))
1856  {
1857  foreach ($elt as $e)
1858  {
1859  $result[$e->$field][] = $e;
1860  }
1861  }
1862  else
1863  {
1864  $result[$elt->$field][] = $elt;
1865  }
1866  }
1867 
1868  return $result;
1869 }

◆ reindexList()

reindexList (   $list,
  $field,
  $autoPromote = true 
)

Reindex an indexed or grouped query result by a different field.

Parameters
array$listan array of DataItem-derived objects, as returned by query(), indexedQuery() or groupedQuery()
string$fieldthe field by which to reindex the list

Definition at line 1799 of file data_item.inc.

1800 {
1801  $result = array();
1802 
1803  foreach($list as $elt)
1804  {
1805  if (is_array($elt))
1806  {
1807  foreach($elt as $e)
1808  {
1809  if (array_key_exists($e->$field, $result))
1810  {
1811  if (!is_array($result[$e->$field]))
1812  {
1813  $result[$e->$field] = array($result[$e->$field]);
1814  }
1815  $result[$e->$field][] = $e;
1816  }
1817  else
1818  {
1819  $result[$e->$field] = $e;
1820  }
1821  }
1822  }
1823  else
1824  {
1825  if (array_key_exists($elt->$field, $result) && $autoPromote)
1826  {
1827  if (!is_array($result[$elt->$field]))
1828  {
1829  $result[$elt->$field] = array($result[$elt->$field]);
1830  }
1831  $result[$elt->$field][] = $elt;
1832  }
1833  else
1834  {
1835  $result[$elt->$field] = $elt;
1836  }
1837  }
1838  }
1839 
1840  return $result;
1841 }

◆ removeDuplicates()

removeDuplicates (   $list,
  $field = "" 
)

Remove duplicate DataItems from a list, based on the value of a field.

If no field is specified, the items' primary key is used. It is assumed that all the objects in the list are of the same class. A filtered copy of the list is returned. The original list is left unchanged.

Parameters
array$listthe list of DataItems from which duplicates are to be removed
string$fieldthe name of the field to use to determine duplicity.
Returns
a filtered list containing no duplicates.

Definition at line 1882 of file data_item.inc.

1883 {
1884  if (count($list) == 0) return $list;
1885 
1886  if ($field == "")
1887  {
1888  $field = $list[0]->primary_key;
1889  }
1890 
1891  $found = array();
1892  $filtered = array();
1893  foreach($list as $item)
1894  {
1895  if (!array_key_exists($item->$field, $found))
1896  {
1897  $filtered[] = $item;
1898  }
1899 
1900  $found[$item->$field] = true;
1901  }
1902 
1903  return $filtered;
1904 }

◆ restoreHTML()

restoreHTML (   $text)

Definition at line 2131 of file data_item.inc.

2132 {
2133  $v = str_replace( array("[_[OPENTAG]_]", "[_[CLOSETAG]_]", "[_[AMPERSAND]_]"), array("<", ">", "&"), $text);
2134  return $v;
2135 }

◆ sortList()

sortList ( $list,
  $field 
)

Sorts an array of DataItems based on the values in the specified field.

Parameters
array$listan array of DataItems
string$fieldthe field to sort by
Returns
the sorted list

Definition at line 1931 of file data_item.inc.

1932 {
1933  $cmp = new DataItemFieldComparator($field);
1934 
1935  usort($list, array($cmp, "compare"));
1936 
1937  return $list;
1938 }
Simple field comparator to support sorting arrays of DataItems by the values in a specified field...
Definition: data_item.inc:1910

◆ toJSON()

toJSON (   $items)

Definition at line 1994 of file data_item.inc.

1995 {
1996  $out = array();
1997 
1998  foreach($items as $item)
1999  {
2000  $out[] = $item->toJSON();
2001  }
2002 
2003  return "[".implode(", ", $out)."]";
2004 }

◆ toJSONGrouped()

toJSONGrouped (   $items)

Definition at line 2006 of file data_item.inc.

2007 {
2008  $out = array();
2009 
2010  foreach($items as $key => $group)
2011  {
2012  $out[] = "\"$key\": ".toJSON($group);
2013  }
2014 
2015  return "{".implode(", ", $out)."}";
2016 }

◆ toXML()

toXML (   $tag,
  $objects,
  $header = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" 
)

Definition at line 1981 of file data_item.inc.

1982 {
1983  $xml = "$header\n<$tag>\n";
1984 
1985  foreach($objects as $obj)
1986  {
1987  $xml .= $obj->toXML(1);
1988  }
1989  $xml .= "</$tag>\n";
1990 
1991  return $xml;
1992 }

◆ updateSortOrder()

updateSortOrder (   $class,
  $field = "sort_order",
  $params = null 
)

Utility method to update sort order for the selected class of objects based on an array that maps primary keys to sort order values.

This method is designed to make drag and drop sorting easier to implement.

Parameters
string$classthe class of DataItem that is being resorted
string$fieldthe field that contains the sort order value

Definition at line 1947 of file data_item.inc.

1948 {
1949  if (!$params) $params = $_GET;
1950  $obj = new $class;
1951  $pk = $obj->getPrimaryKey();
1952 
1953  $tx = new DataTransaction();
1954 
1955  try
1956  {
1957  foreach($params[$pk] as $id => $sort_order)
1958  {
1959  checkNumeric($id);
1960  checkNumeric($sort_order);
1961 
1962  $item = new $class();
1963  $item->joinTransaction($tx);
1964 
1965  $item->filter = new InclusionFilter($pk, $field);
1966 
1967  $item->load($id);
1968  $item->set($field, $sort_order);
1969  $item->save();
1970  }
1971 
1972  $tx->commit();
1973  }
1974  catch(Exception $e)
1975  {
1976  $tx->rollback();
1977  throw $e;
1978  }
1979 }
Used to place a filter on the contents of a DataItem-derived object.
The DataTransaction class wraps the underlying database&#39;s transaction model.
Definition: transaction.inc:44
checkNumeric($p)
Security helper function.
Definition: functions.inc:630