Skip to content

Commit

Permalink
Refactor BaseActiveRecord::getAttributes()
Browse files Browse the repository at this point in the history
  • Loading branch information
Tigrov committed Dec 17, 2023
1 parent 6d9864b commit e5c7f9b
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 12 deletions.
18 changes: 6 additions & 12 deletions src/BaseActiveRecord.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,13 @@
use Yiisoft\Db\Helper\DbStringHelper;

use function array_combine;
use function array_diff;
use function array_diff_key;
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 +137,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

0 comments on commit e5c7f9b

Please sign in to comment.