Skip to content

Commit

Permalink
Simplify ColumnsTrait::fieldAlias
Browse files Browse the repository at this point in the history
  • Loading branch information
roxblnfk committed Nov 24, 2023
1 parent 6b57cd9 commit 3f542c7
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 5 deletions.
8 changes: 3 additions & 5 deletions src/Select/Traits/ColumnsTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,11 @@ trait ColumnsTrait
public function fieldAlias(string $field): ?string
{
// The field can be a JSON path separated by ->
if (\str_contains($field, '->')) {
$parts = \explode('->', $field, 2);
$p = \explode('->', $field, 2);

return isset($this->columns[$parts[0]]) ? \sprintf('%s->%s', $this->columns[$parts[0]], $parts[1]) : null;
}
$p[0] = $this->columns[$p[0]] ?? null;

return $this->columns[$field] ?? null;
return $p[0] === null ? null : \implode('->', $p);
}

/**
Expand Down
56 changes: 56 additions & 0 deletions tests/ORM/Unit/Select/Traits/ColumnsTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

declare(strict_types=1);

namespace Cycle\ORM\Tests\Unit\Select\Traits;

use PHPUnit\Framework\TestCase;

final class ColumnsTrait extends TestCase
{
private const FIELDS = ['id' => 'column_id'];

public static function getColumnsDataProvider(): iterable
{
yield ['id', 'column_id'];
yield ['name', null];
yield ['id->foo', 'column_id->foo'];
yield ['name->foo', null];
yield ['->foo', null];
yield ['', null];
}

/**
* @dataProvider getColumnsDataProvider
*/
public function testGetColumns(string $input, ?string $expected): void
{
$class = $this->prepareClass();

for ($i = 10000; $i > 0; --$i) {
$class->fieldAlias($input);
}

$this->assertSame($expected, $class->fieldAlias($input));
}

private function prepareClass(): object
{
return new class(self::FIELDS) {
use \Cycle\ORM\Select\Traits\ColumnsTrait
{
fieldAlias as public;
}

public function __construct(array $columns)
{
$this->columns = $columns;
}

public function getAlias(): string
{
return 'test';
}
};
}
}

0 comments on commit 3f542c7

Please sign in to comment.