Created
October 14, 2014 14:36
-
-
Save prochor666/c4fe8cfd34565d9c8be7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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