/** @test */ public function it_applies_valid_sorts_when_sorts_configured() { $this->setMocks(); $createdAtSort = new Sort('created_at', 'ASC'); $nameSort = new Sort('name', 'DESC'); $surnameSort = new Sort('surname', 'DESC'); $otherSort = new Sort('field', 'ASC'); $this->parser->shouldReceive('getFilters')->once(); $this->parser->shouldReceive('getSorts')->once()->andReturn(collect([$createdAtSort, $nameSort, $surnameSort, $otherSort])); $filter = $this->createFilterMock('NotEmptyQueryFilter'); $filter->shouldReceive('applySortCreatedAt')->with($createdAtSort->getOrder()); $filter->shouldReceive('applySimpleSort')->once()->with($nameSort)->passthru(); $filter->shouldReceive('applySimpleSort')->once()->with($surnameSort)->passthru(); $filter->shouldNotReceive('applySortField'); $filter->shouldNotReceive('applySimpleFilter')->with($otherSort); $this->query->shouldReceive('orderBy')->once()->with($nameSort->getField(), $nameSort->getOrder()); $this->query->shouldReceive('orderBy')->once()->with($surnameSort->getField(), $surnameSort->getOrder()); $filter->shouldReceive('applyDefaultSorts')->once()->withNoArgs()->passthru(); $filter->applySorts($this->query); $this->assertEquals(collect(['created_at', 'name', 'surname']), $filter->getAppliedSorts()); }
/** * Get parameters for sorting * * @return Collection */ public function getSorts() { $sortInput = $this->request->input($this->sortName, ''); $sortFields = $this->collection->make(is_array($sortInput) ? $sortInput : explode($this->sortFieldsSeparator, $sortInput)); $sorts = $this->collection->make(); $sortFields->each(function ($field) use($sorts) { $s = new Sort(); $order = 'ASC'; if (starts_with($field, $this->sortDescSign)) { $order = 'DESC'; $field = mb_substr($field, mb_strlen($this->sortDescSign)); } if ($field = trim($field)) { $s->setField($field); $s->setOrder($order); $sorts->put($field, $s); } }); return $sorts->values(); }