Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor BaseActiveRecord::getAttributes() #279

Merged
merged 6 commits into from
Dec 29, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 5 additions & 12 deletions src/BaseActiveRecord.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@
use Yiisoft\Db\Helper\DbStringHelper;

use function array_combine;
use function array_diff;
use function array_flip;
use function array_intersect;
use function array_key_exists;
use function array_keys;
use function array_map;
use function array_search;
use function array_values;
use function count;
Expand Down Expand Up @@ -134,24 +136,15 @@ public function getAttribute(string $name): mixed

public function getAttributes(array $names = null, array $except = []): array
{
$values = [];

if ($names === null) {
$names = $this->attributes();
}

/** @psalm-var list<string> $names */
foreach ($names as $name) {
/** @psalm-var mixed */
$values[$name] = $this->$name;
}

/** @psalm-var list<string> $except */
foreach ($except as $name) {
unset($values[$name]);
if ($except !== []) {
$names = array_diff($names, $except);
}

return $values;
return array_combine($names, array_map([$this, 'getAttribute'], $names));
}

public function getIsNewRecord(): bool
Expand Down
11 changes: 11 additions & 0 deletions tests/ActiveQueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2103,6 +2103,17 @@ public function testGetAttributes(): void
$this->assertEquals($attributes, $attributesExpected);
}

public function testGetAttributesOnly(): void
{
$this->checkFixture($this->db, 'customer');

$customer = new ActiveQuery(Customer::class, $this->db);

$attributes = $customer->findOne(1)->getAttributes(['id', 'email', 'name']);

$this->assertEquals(['id' => 1, 'email' => '[email protected]', 'name' => 'user1'], $attributes);
}

public function testGetAttributesExcept(): void
{
$this->checkFixture($this->db, 'customer');
Expand Down
Loading