Skip to content

Commit

Permalink
Make order by and select keyword rules use column aliases
Browse files Browse the repository at this point in the history
See #34
  • Loading branch information
lorisleiva committed Apr 30, 2021
1 parent 82c0d74 commit 366f558
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
7 changes: 7 additions & 0 deletions src/Options/SearchStringOptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,13 @@ public function getColumnRule($key): ?ColumnRule
});
}

public function getColumnNameFromAlias($alias): string
{
$columnRule = $this->getColumnRule($alias);

return $columnRule ? $columnRule->column : $alias;
}

public function getRule($key): ?Rule
{
if ($rule = $this->getKeywordRule($key)) {
Expand Down
5 changes: 4 additions & 1 deletion src/Visitors/BuildKeywordsVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,17 @@ protected function buildOrderBy($values)
Collection::wrap($values)->each(function ($value) {
$desc = Str::startsWith($value, '-') ? 'desc' : 'asc';
$column = Str::startsWith($value, '-') ? Str::after($value, '-') : $value;
$column = $this->manager->getColumnNameFromAlias($column);
$qualifiedColumn = SearchStringManager::qualifyColumn($this->builder, $column);
$this->builder->orderBy($qualifiedColumn, $desc);
});
}

protected function buildSelect($values, bool $negated)
{
$columns = Arr::wrap($values);
$columns = Collection::wrap($values)->map(function ($value) {
return $this->manager->getColumnNameFromAlias($value);
});

$columns = $negated
? $this->manager->getColumns()->diff($columns)
Expand Down
20 changes: 20 additions & 0 deletions tests/VisitorBuildKeywordsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,15 @@ public function it_uses_only_the_last_select_that_matches()
$this->assertEquals(['products.description'], $builder->getQuery()->columns);
}

/** @test */
public function it_uses_the_alias_of_select_columns()
{
$model = $this->getModelWithColumns(['created_at' => 'date']);
$builder = $this->getBuilder('fields:date', $model);

$this->assertEquals(['models.created_at'], $builder->getQuery()->columns);
}

/*
* OrderBy
*/
Expand Down Expand Up @@ -106,6 +115,17 @@ public function it_uses_only_the_last_order_by_that_matches()
], $builder->getQuery()->orders);
}

/** @test */
public function it_uses_the_alias_of_order_by_columns()
{
$model = $this->getModelWithColumns(['created_at' => 'date']);
$builder = $this->getBuilder('sort:date', $model);

$this->assertEquals([
[ 'column' => 'models.created_at', 'direction' => 'asc' ],
], $builder->getQuery()->orders);
}

/*
* Limit
*/
Expand Down

0 comments on commit 366f558

Please sign in to comment.