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 all 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
12 changes: 5 additions & 7 deletions src/BaseActiveRecord.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
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;
Expand Down Expand Up @@ -140,15 +141,12 @@ public function getAttributes(array $names = null, array $except = []): array
$names = $this->attributes();
}

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

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

return $values;
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' => 'user1@example.com', 'name' => 'user1'], $attributes);
}

public function testGetAttributesExcept(): void
{
$this->checkFixture($this->db, 'customer');
Expand Down
2 changes: 1 addition & 1 deletion tests/Stubs/ActiveRecord/Cat.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public function getException(): void
*/
public function getThrowable(): float|int
{
return 5/0;
return 5 / 0;
}

public function setNonExistingProperty(string $value): void
Expand Down
Loading