Skip to content

Instantly share code, notes, and snippets.

@kennethdavidbuck
Created May 27, 2013 05:54
Show Gist options
  • Save kennethdavidbuck/5655381 to your computer and use it in GitHub Desktop.
Save kennethdavidbuck/5655381 to your computer and use it in GitHub Desktop.
<?php
namespace Api;
class Cinder extends Metum {
/**
*
*/
public static function find($table,$id,$root = false)
{
$result;
if(is_array($id))
{
$result = static::where($table,$id,$root);
}
else if(!empty($id))
{
$result = static::single($table,$id,$root);
}
else
{
$result = static::all($table, $root);
}
return $result;
}
/**
* Find all table records
*/
private static function all($table, $root = false)
{
$root = static::rootPlural($table, $root);
$result = \DB::table($table);
$result = static::concat($result,$table);
return array($root => $result->get());
}
/**
* Find a subset of objects by id
*/
private static function where($table, $ids, $root = false)
{
$root = static::rootPlural($table,$root);
$result = \DB::table($table)->whereIn('id',$ids);
$result = static::concat($result,$root);
return array($root => $result->get());
}
/**
* Find a single record
*/
private static function single($table, $id, $root = false)
{
$result = \DB::table($table)->where("$table.id",'=',$id);
$result = static::concat($result,$table);
$root = static::rootSingular($table,$root);
return array($root => $result->first());
}
/**
* Add dependency ids as inferred associations from DB
*/
private static function concat($result, $table) {
$parentField = static::parentField($table);
foreach(static::associations($table) as $childTable)
{
$childSingleRoot = static::rootSingular($childTable);
$result->leftJoin(
\DB::raw("(SELECT $parentField AS id,
CONCAT('[',GROUP_CONCAT($childTable.id),']') AS ".$childSingleRoot."_ids
FROM $childTable
GROUP BY $parentField) AS alias"),
function($join) use ($table, $parentField)
{
$join->on("alias.id",'=',"$table.id");
}
);
}
return $result;
}
/**
* Build a singular root
*/
private static function rootSingular($table, $root = false)
{
return $root ? $root : \Str::singular($table);
}
/**
* Build a plural root
*/
private static function rootPlural($table, $root = false)
{
return $root ? $root : \Str::plural($table);
}
/**
* Singularize a given table name add append _id,
* as part of a conventional foreign key.
*/
private static function parentField($table)
{
return static::rootSingular($table).'_id';
}
/**
* Retrieve list of associated tables
*/
private static function associations($parentTable)
{
// Field to look for in association
$parentField = static::parentField($parentTable);
$result = array();
foreach(static::tables() as $key => $table)
{
foreach(static::fields($table) as $field)
{
if($field->Field === $parentField)
{
$result[] = $table;
break;
}
}
}
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment