Skip to content

Commit

Permalink
Fix extensibility issue
Browse files Browse the repository at this point in the history
  • Loading branch information
Tigrov committed Dec 15, 2023
1 parent 41c6691 commit 6620d22
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 5 deletions.
6 changes: 1 addition & 5 deletions src/BaseActiveRecordTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,8 @@ trait BaseActiveRecordTrait
*/
public function __get(string $name)
{
if (isset($this->attributes[$name]) || array_key_exists($name, $this->attributes)) {
return $this->attributes[$name];
}

if ($this->hasAttribute($name)) {
return null;
return $this->getAttribute($name);
}

if (isset($this->related[$name]) || array_key_exists($name, $this->related)) {
Expand Down
11 changes: 11 additions & 0 deletions tests/ActiveRecordTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\Cat;
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\Customer;
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\CustomerClosureField;
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\CustomerExtraAttributes;
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\CustomerWithAlias;
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\Dog;
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\Item;
Expand Down Expand Up @@ -763,4 +764,14 @@ public function testToArrayWithClosure(): void
$customer->toArray(),
);
}

public function testGetExtraArrtibute()
{
$this->checkFixture($this->db, 'customer');

$customerQuery = new ActiveQuery(CustomerExtraAttributes::class, $this->db);
$customer = $customerQuery->findOne(1);

$this->assertSame($customer->sex, 'm');
}
}
48 changes: 48 additions & 0 deletions tests/Stubs/ActiveRecord/CustomerExtraAttributes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

declare(strict_types=1);

namespace Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord;

use Yiisoft\ActiveRecord\ActiveRecord;

/**
* Class CustomerClosureField.
*
* @property int $id
* @property string $name
* @property string $email
* @property string $address
* @property int $status
* @property string $sex
*/
final class CustomerExtraAttributes extends ActiveRecord
{
private array $extraAttributes = [
'sex' => 'm',
];

public function getTableName(): string
{
return 'customer';
}

public function getAttribute(string $name): mixed
{
if (array_key_exists($name, $this->extraAttributes)) {
return $this->extraAttributes[$name];
}

return parent::getAttribute($name);
}

public function getAttributes(array $names = null, array $except = []): array
{
return array_merge(parent::getAttributes($names, $except), $this->extraAttributes);
}

public function hasAttribute($name): bool
{
return array_key_exists($name, $this->extraAttributes) || parent::hasAttribute($name);
}
}

0 comments on commit 6620d22

Please sign in to comment.