Skip to content

Commit

Permalink
Add “Abs” function (#21)
Browse files Browse the repository at this point in the history
Co-authored-by: tpetry <github@tpetry.me>
  • Loading branch information
morloderex and tpetry authored Nov 10, 2023
1 parent ab94832 commit 7d15482
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,15 @@ BlogArticle::select([
->get();
```

#### Math
```php
use Tpetry\QueryExpressions\Function\Math\{
Abs,
};

new Abs(string|Expression $expression);
```

#### String
```php
use Tpetry\QueryExpressions\Function\String\{
Expand Down
31 changes: 31 additions & 0 deletions src/Function/Math/Abs.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

namespace Tpetry\QueryExpressions\Function\Math;

use Illuminate\Contracts\Database\Query\Expression;
use Illuminate\Database\Grammar;
use Tpetry\QueryExpressions\Concerns\IdentifiesDriver;
use Tpetry\QueryExpressions\Concerns\StringizeExpression;

class Abs implements Expression
{
use IdentifiesDriver;
use StringizeExpression;

public function __construct(
private readonly string|Expression $expression,
) {
}

public function getValue(Grammar $grammar): string
{
$expression = $this->stringize($grammar, $this->expression);

return match ($this->identify($grammar)) {
'mysql', 'sqlite' => "(abs({$expression}))",
'pgsql', 'sqlsrv' => "abs({$expression})",
};
}
}
25 changes: 25 additions & 0 deletions tests/Function/Math/AbsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

declare(strict_types=1);

use Illuminate\Database\Query\Expression;
use Illuminate\Database\Schema\Blueprint;
use Tpetry\QueryExpressions\Function\Math\Abs;

it('can abs a column')
->expect(new Abs('val'))
->toBeExecutable(function (Blueprint $table) {
$table->integer('val');
})
->toBeMysql('(abs(`val`))')
->toBePgsql('abs("val")')
->toBeSqlite('(abs("val"))')
->toBeSqlsrv('abs([val])');

it('can abs an expression')
->expect(new Abs(new Expression('sum(1)')))
->toBeExecutable()
->toBeMysql('(abs(sum(1)))')
->toBePgsql('abs(sum(1))')
->toBeSqlite('(abs(sum(1)))')
->toBeSqlsrv('abs(sum(1))');

0 comments on commit 7d15482

Please sign in to comment.