diff --git a/src/BaseActiveRecord.php b/src/BaseActiveRecord.php index d6cb497e3..2550d6179 100644 --- a/src/BaseActiveRecord.php +++ b/src/BaseActiveRecord.php @@ -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; @@ -140,15 +141,12 @@ public function getAttributes(array $names = null, array $except = []): array $names = $this->attributes(); } - /** @psalm-var list $names */ - foreach ($names as $name) { - /** @psalm-var mixed */ - $values[$name] = $this->$name; + if ($except !== []) { + $names = array_diff($names, $except); } - /** @psalm-var list $except */ - foreach ($except as $name) { - unset($values[$name]); + foreach ($names as $name) { + $values[$name] = $this->$name; } return $values; diff --git a/tests/ActiveQueryTest.php b/tests/ActiveQueryTest.php index 4fa25063b..3ef924af4 100644 --- a/tests/ActiveQueryTest.php +++ b/tests/ActiveQueryTest.php @@ -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'); diff --git a/tests/Stubs/ActiveRecord/Cat.php b/tests/Stubs/ActiveRecord/Cat.php index dc9a402d3..97ff4cf28 100644 --- a/tests/Stubs/ActiveRecord/Cat.php +++ b/tests/Stubs/ActiveRecord/Cat.php @@ -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