public function testCanSortByCustomClosure() { $request = Request::create('/', 'GET', ['sort' => ['pogo' => 'desc']]); $query = Sms::where('voip_id', 1); $doc = MasonCollection::make()->setSortTypes([Sort::make('pogo')->setFunction(function (Builder $query, $direction) { $query->orderBy('created', $direction); })])->populate($request, $query); $firstCreated = $doc->items[0]->created; $lastCreated = $doc->items[7]->created; $this->assertLessThan($firstCreated, $lastCreated); }
/** * Which sorting types are supported. The input is an array that can contain a mix of indexed and associative * keys and values. Simple array values as shown below must refer to columns in the database table. * * $allowedTypes[] = 'blahblah'; * $allowedTypes[] = 'yoyoyo'; * * For complex sort types, use the syntax below. The key does not necessarily refer to a column in the database * table. The value must be a closure, which will be called with two arguments. The first is a reference to the * Eloquent query, which the closure is expected to modify by adding one or more calls to $query->orderBy(). * The second argument given to the closure is the requested sort direction, e.g. "asc" or "desc". * * $allowedTypes['foofoo'] = function(Builder $query, $direction) { * $query->orderBy('yip', $direction) * ->orderBy('bang', $direction); * }; * * @param array $allowedTypes List of allowed sorting types for this collection. * @param array $sorting Associative array of default sorting. Keys are sort types. Values are "asc or "desc". * For example: $sorting = ['scheduled' => 'asc', 'created' => 'desc']; * @return $this */ public function setSortTypes(array $allowedTypes, $defaultSorting = []) { $this->allowedSortTypes = []; foreach ($allowedTypes as $index => $type) { if ($type instanceof Sort) { $sort = $type; } else { $sort = new Sort($type); if (!is_numeric($index)) { $sort->setField($index); } } $this->allowedSortTypes[$sort->getName()] = $sort; } $this->defaultSorting = $defaultSorting; return $this; }