mirror of
https://github.com/silverstripe/silverstripe-framework
synced 2024-10-22 14:05:37 +02:00
NEW Adding a shuffle method to ArrayList (#8984)
* NEW Adding a shuffle method to ArrayList * API Add shuffle to DataList for ArrayList parity
This commit is contained in:
parent
ec71cdd103
commit
350888bf50
@ -572,6 +572,18 @@ class ArrayList extends ViewableData implements SS_List, Filterable, Sortable, L
|
||||
return $list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shuffle the items in this array list
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function shuffle()
|
||||
{
|
||||
shuffle($this->items);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the given column can be used to filter the records.
|
||||
*
|
||||
|
@ -1133,6 +1133,16 @@ class DataList extends ViewableData implements SS_List, Filterable, Sortable, Li
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shuffle the datalist using a random function provided by the SQL engine
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function shuffle()
|
||||
{
|
||||
return $this->sort(DB::get_conn()->random());
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove every element in this DataList.
|
||||
*
|
||||
|
@ -1236,4 +1236,19 @@ class ArrayListTest extends SapphireTest
|
||||
$list->setDataClass(DataObject::class);
|
||||
$this->assertEquals(DataObject::class, $list->dataClass());
|
||||
}
|
||||
|
||||
public function testShuffle()
|
||||
{
|
||||
$upperLimit = 50;
|
||||
|
||||
$list = new ArrayList(range(1, $upperLimit));
|
||||
|
||||
$list->shuffle();
|
||||
|
||||
for ($i = 1; $i <= $upperLimit; $i++) {
|
||||
$this->assertContains($i, $list);
|
||||
}
|
||||
|
||||
$this->assertNotEquals(range(1, $upperLimit), $list->toArray());
|
||||
}
|
||||
}
|
||||
|
@ -1837,4 +1837,11 @@ class DataListTest extends SapphireTest
|
||||
$list->column("Title")
|
||||
);
|
||||
}
|
||||
|
||||
public function testShuffle()
|
||||
{
|
||||
$list = Team::get()->shuffle();
|
||||
|
||||
$this->assertSQLContains(DB::get_conn()->random() . ' AS "_SortColumn', $list->dataQuery()->sql());
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user