Skip to content

Commit fc0d9a5

Browse files
authored
Merge pull request #13 from thetar/patch-1
Added setIndent()
2 parents c175980 + ee8a47c commit fc0d9a5

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

README.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,23 @@ By default it will look for a `title` column. You can send a custom column name
5959
Model::orderBy('parent_id')->get()->nest()->listsFlattened('name');
6060
```
6161

62+
Four spaces are used to indent by default, to use your own use the `setIndent()` method, followed by the `listsFlattened()` method:
63+
64+
```php
65+
Model::orderBy('parent_id')->get()->nest()->setIndent('> ')->listsFlattened();
66+
```
67+
68+
Results:
69+
70+
```php
71+
[
72+
'22' => 'Item 1 Title',
73+
'10' => '> Child 1 Title',
74+
'17' => '> Child 2 Title',
75+
'14' => 'Item 2 Title',
76+
]
77+
```
78+
6279
## Nesting a subtree
6380

6481
This package remove items that have missing ancestor, this doesn’t allow you to nest a branch of a tree.

src/NestableCollection.php

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ class NestableCollection extends Collection
1818
private $total;
1919
private $parentColumn;
2020
private $removeItemsWithMissingAncestor = true;
21+
private $indentChars = '    ';
2122

2223
public function __construct($items = [])
2324
{
@@ -87,9 +88,10 @@ public function nest()
8788
*
8889
* @return array
8990
*/
90-
public function listsFlattened($column = 'title', BaseCollection $collection = null, $level = 0, array &$flattened = [], $indentChars = '    ')
91+
public function listsFlattened($column = 'title', BaseCollection $collection = null, $level = 0, array &$flattened = [], $indentChars = null)
9192
{
9293
$collection = $collection ?: $this;
94+
$indentChars = $indentChars ?: $this->indentChars;
9395
foreach ($collection as $item) {
9496
$flattened[$item->id] = str_repeat($indentChars, $level).$item->$column;
9597
if ($item->items) {
@@ -100,6 +102,17 @@ public function listsFlattened($column = 'title', BaseCollection $collection = n
100102
return $flattened;
101103
}
102104

105+
/**
106+
* Change the default indent characters when flattening lists
107+
*
108+
* @param string $indentChars
109+
* @return $this
110+
*/
111+
public function setIndent(string $indentChars) {
112+
$this->indentChars = $indentChars;
113+
return $this;
114+
}
115+
103116
/**
104117
* Force keeping items that have a missing ancestor.
105118
*

0 commit comments

Comments
 (0)