Skip to content

Commit 7d15482

Browse files
morloderextpetry
andauthored
Add “Abs” function (tpetry#21)
Co-authored-by: tpetry <[email protected]>
1 parent ab94832 commit 7d15482

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,15 @@ BlogArticle::select([
253253
->get();
254254
```
255255

256+
#### Math
257+
```php
258+
use Tpetry\QueryExpressions\Function\Math\{
259+
Abs,
260+
};
261+
262+
new Abs(string|Expression $expression);
263+
```
264+
256265
#### String
257266
```php
258267
use Tpetry\QueryExpressions\Function\String\{

src/Function/Math/Abs.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Tpetry\QueryExpressions\Function\Math;
6+
7+
use Illuminate\Contracts\Database\Query\Expression;
8+
use Illuminate\Database\Grammar;
9+
use Tpetry\QueryExpressions\Concerns\IdentifiesDriver;
10+
use Tpetry\QueryExpressions\Concerns\StringizeExpression;
11+
12+
class Abs implements Expression
13+
{
14+
use IdentifiesDriver;
15+
use StringizeExpression;
16+
17+
public function __construct(
18+
private readonly string|Expression $expression,
19+
) {
20+
}
21+
22+
public function getValue(Grammar $grammar): string
23+
{
24+
$expression = $this->stringize($grammar, $this->expression);
25+
26+
return match ($this->identify($grammar)) {
27+
'mysql', 'sqlite' => "(abs({$expression}))",
28+
'pgsql', 'sqlsrv' => "abs({$expression})",
29+
};
30+
}
31+
}

tests/Function/Math/AbsTest.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Illuminate\Database\Query\Expression;
6+
use Illuminate\Database\Schema\Blueprint;
7+
use Tpetry\QueryExpressions\Function\Math\Abs;
8+
9+
it('can abs a column')
10+
->expect(new Abs('val'))
11+
->toBeExecutable(function (Blueprint $table) {
12+
$table->integer('val');
13+
})
14+
->toBeMysql('(abs(`val`))')
15+
->toBePgsql('abs("val")')
16+
->toBeSqlite('(abs("val"))')
17+
->toBeSqlsrv('abs([val])');
18+
19+
it('can abs an expression')
20+
->expect(new Abs(new Expression('sum(1)')))
21+
->toBeExecutable()
22+
->toBeMysql('(abs(sum(1)))')
23+
->toBePgsql('abs(sum(1))')
24+
->toBeSqlite('(abs(sum(1)))')
25+
->toBeSqlsrv('abs(sum(1))');

0 commit comments

Comments
 (0)