diff --git a/src/ORM/ArrayList.php b/src/ORM/ArrayList.php index cd60f6eb7..caa139542 100644 --- a/src/ORM/ArrayList.php +++ b/src/ORM/ArrayList.php @@ -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. * diff --git a/src/ORM/DataList.php b/src/ORM/DataList.php index 9110caabb..d5c9df54a 100644 --- a/src/ORM/DataList.php +++ b/src/ORM/DataList.php @@ -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. * diff --git a/tests/php/ORM/ArrayListTest.php b/tests/php/ORM/ArrayListTest.php index ede838515..29e99b007 100644 --- a/tests/php/ORM/ArrayListTest.php +++ b/tests/php/ORM/ArrayListTest.php @@ -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()); + } } diff --git a/tests/php/ORM/DataListTest.php b/tests/php/ORM/DataListTest.php index a00290c3f..1f5bcd09a 100755 --- a/tests/php/ORM/DataListTest.php +++ b/tests/php/ORM/DataListTest.php @@ -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()); + } }