Skip to content

Instantly share code, notes, and snippets.

@prochor666
Created October 14, 2014 14:36
Show Gist options
  • Save prochor666/c4fe8cfd34565d9c8be7 to your computer and use it in GitHub Desktop.
Save prochor666/c4fe8cfd34565d9c8be7 to your computer and use it in GitHub Desktop.
<?php namespace Fishcat\Shop\Models\Traits;
use Input;
trait TreeStructure {
public static $repository = false;
/**
* Get nested array of queried entry type
* @param array $params [description]
*/
public static function tree($params = array('parent' => 0, 'uri' => '', 'uriDivider' => '/', 'getChildren' => true))
{
$parent = array_get($params, 'parent', 0);
$uri = array_get($params, 'uri', '');
$uriDivider = array_get($params, 'uriDivider', '/');
$getChildren = array_get($params, 'getChildren', true);
if ( !self::$repository ) {
self::$repository = self::getRepository();
}
$branch = [];
foreach (self::$repository as $element) {
if ($element->parent == $parent) {
if($getChildren === true){
$params['parent'] = $element->id;
$params['uri'] = $uri . $uriDivider . $element->{self::$uriPartial};
$children = self::tree($params);
if ($children) {
$element->children = $children;
}
}
$element = $element->toArray();
// Add internal uri within the tree
$element['uri'] = $uri . $uriDivider . $element[self::$uriPartial];
$branch[] = $element;
}
}
return $branch;
}
public static function getModel()
{
return get_called_class();
}
/**
* Repository of queried entry type,
* returns only requested information.
* @todo Return only requested information
* @return [type] [description]
*/
public static function getRepository()
{
$model = self::getModel();
$query = $model::select(['id', 'parent'])->get();
return $query;
}
/**
* Full repository of queried entry type
* @return [type] [description]
*/
public static function getRepositoryEager()
{
$model = self::getModel();
$repository = call_user_func( [self::getModel(), 'all'] );
return $repository;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment