Exemplo n.º 1
0
 /**
  * Get a set objects
  * 
  * @param string $criteria sql criteria
  * @param array $placeholders
  * @param callable $run will be applied to all objects, return values will replace objects and result will be filtered to remove nulls
  * 
  * @return array of objects
  */
 public static function all($criteria = null, $placeholders = array(), $run = null)
 {
     $query = 'SELECT * FROM ' . static::getDBTable();
     // Build filters if required
     if ($criteria) {
         $where = null;
         $order = null;
         $group = null;
         if (is_array($criteria)) {
             if (array_key_exists('where', $criteria)) {
                 $where = $criteria['where'];
             }
             if (array_key_exists('order', $criteria)) {
                 $order = $criteria['order'];
             }
             if (array_key_exists('group', $criteria)) {
                 $group = $criteria['group'];
             }
         } else {
             $where = $criteria;
         }
         if ($where) {
             $query .= ' WHERE ' . $where;
         }
         if ($group) {
             $query .= ' GROUP BY ' . $group;
         }
         if ($order) {
             $query .= ' ORDER BY ' . $order;
         }
     }
     // Look for primary key(s) name(s)
     $pk = array();
     foreach (static::getDataMap() as $k => $d) {
         if (array_key_exists('primary', $d) && $d['primary']) {
             $pk[] = $k;
         }
     }
     // Prepare query depending on contents
     if (preg_match('`\\s+[^\\s]+\\s+IN\\s+:[^\\s]+(\\s+|$)`i', $query)) {
         $statement = DBI::prepareInQuery($query, array_filter($placeholders, 'is_array'));
     } else {
         $statement = DBI::prepare($query);
     }
     // run it
     $statement->execute($placeholders);
     // Fetch records, register them with id build from primary key(s) value(s)
     $objects = array();
     foreach ($statement->fetchAll() as $r) {
         $id = array();
         foreach ($pk as $k) {
             $id[] = $r[$k];
         }
         $id = implode('-', $id);
         $objects[$id] = static::fromData($id, $r);
     }
     // Apply callback if provided
     if ($run && is_callable($run)) {
         $new_things = array();
         foreach ($objects as $id => $o) {
             $objects[$id] = $run($o);
         }
         $objects = array_filter($objects, function ($o) {
             return !is_null($o);
         });
     }
     return $objects;
 }