Created
September 19, 2020 18:31
-
-
Save iksaku/8be40fea8b6feb85e2f1a8acf29a8fbe to your computer and use it in GitHub Desktop.
A helper trait that provides basic PHP compatibility with @livewire's Sortable package
This file contains hidden or 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 | |
trait Sortable | |
{ | |
/** | |
* This function receives a $newOrder array parameter, which contains the order in which | |
* we should sort our items after being dragged in the UI. The format of the $newOrder is: | |
* | |
* [ | |
* newIndex => [ | |
* order => Numerical order, used in case index keys don't preserve order | |
* value => Reference to the items being dragged. In our case, the "previous index" that the item had. | |
* ] | |
* ] | |
* | |
* With this in mind, we simplify the process by using collection methods and | |
* keep the code cleaner and a little more descriptive by itself. | |
* | |
* @see https://github.com/livewire/sortable | |
* | |
* @param array $haystack | |
* @param array $orderEvent | |
*/ | |
protected function onSort(array &$haystack, array $orderEvent): void | |
{ | |
$haystack = collect($orderEvent) | |
->sortBy('order') | |
->map(fn(array $ref) => $haystack[(int) $ref['value']]) | |
->toArray(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment