Skip to content

Commit

Permalink
Merge pull request #13 from thetar/patch-1
Browse files Browse the repository at this point in the history
Added setIndent()
  • Loading branch information
sdebacker authored Apr 5, 2017
2 parents c175980 + ee8a47c commit fc0d9a5
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,23 @@ By default it will look for a `title` column. You can send a custom column name
Model::orderBy('parent_id')->get()->nest()->listsFlattened('name');
```

Four spaces are used to indent by default, to use your own use the `setIndent()` method, followed by the `listsFlattened()` method:

```php
Model::orderBy('parent_id')->get()->nest()->setIndent('> ')->listsFlattened();
```

Results:

```php
[
'22' => 'Item 1 Title',
'10' => '> Child 1 Title',
'17' => '> Child 2 Title',
'14' => 'Item 2 Title',
]
```

## Nesting a subtree

This package remove items that have missing ancestor, this doesn’t allow you to nest a branch of a tree.
Expand Down
15 changes: 14 additions & 1 deletion src/NestableCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class NestableCollection extends Collection
private $total;
private $parentColumn;
private $removeItemsWithMissingAncestor = true;
private $indentChars = '    ';

public function __construct($items = [])
{
Expand Down Expand Up @@ -87,9 +88,10 @@ public function nest()
*
* @return array
*/
public function listsFlattened($column = 'title', BaseCollection $collection = null, $level = 0, array &$flattened = [], $indentChars = '    ')
public function listsFlattened($column = 'title', BaseCollection $collection = null, $level = 0, array &$flattened = [], $indentChars = null)
{
$collection = $collection ?: $this;
$indentChars = $indentChars ?: $this->indentChars;
foreach ($collection as $item) {
$flattened[$item->id] = str_repeat($indentChars, $level).$item->$column;
if ($item->items) {
Expand All @@ -100,6 +102,17 @@ public function listsFlattened($column = 'title', BaseCollection $collection = n
return $flattened;
}

/**
* Change the default indent characters when flattening lists
*
* @param string $indentChars
* @return $this
*/
public function setIndent(string $indentChars) {
$this->indentChars = $indentChars;
return $this;
}

/**
* Force keeping items that have a missing ancestor.
*
Expand Down

0 comments on commit fc0d9a5

Please sign in to comment.