Skip to content

Commit eb86518

Browse files
authored
Refactor BaseActiveRecord::getAttributes() (#279)
1 parent 6d9864b commit eb86518

3 files changed

Lines changed: 17 additions & 8 deletions

File tree

src/BaseActiveRecord.php

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
use Yiisoft\Db\Helper\DbStringHelper;
2323

2424
use function array_combine;
25+
use function array_diff;
2526
use function array_flip;
2627
use function array_intersect;
2728
use function array_key_exists;
@@ -140,15 +141,12 @@ public function getAttributes(array $names = null, array $except = []): array
140141
$names = $this->attributes();
141142
}
142143

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

149-
/** @psalm-var list<string> $except */
150-
foreach ($except as $name) {
151-
unset($values[$name]);
148+
foreach ($names as $name) {
149+
$values[$name] = $this->$name;
152150
}
153151

154152
return $values;

tests/ActiveQueryTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2103,6 +2103,17 @@ public function testGetAttributes(): void
21032103
$this->assertEquals($attributes, $attributesExpected);
21042104
}
21052105

2106+
public function testGetAttributesOnly(): void
2107+
{
2108+
$this->checkFixture($this->db, 'customer');
2109+
2110+
$customer = new ActiveQuery(Customer::class, $this->db);
2111+
2112+
$attributes = $customer->findOne(1)->getAttributes(['id', 'email', 'name']);
2113+
2114+
$this->assertEquals(['id' => 1, 'email' => 'user1@example.com', 'name' => 'user1'], $attributes);
2115+
}
2116+
21062117
public function testGetAttributesExcept(): void
21072118
{
21082119
$this->checkFixture($this->db, 'customer');

tests/Stubs/ActiveRecord/Cat.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ public function getException(): void
2727
*/
2828
public function getThrowable(): float|int
2929
{
30-
return 5/0;
30+
return 5 / 0;
3131
}
3232

3333
public function setNonExistingProperty(string $value): void

0 commit comments

Comments
 (0)