Skip to content

Commit 4e7f9af

Browse files
authored
feat: Merging Attributes During Injection (#10738)
1 parent d105e10 commit 4e7f9af

7 files changed

Lines changed: 449 additions & 1 deletion

File tree

‎docs/changelogs/v4.8.0.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,7 @@ Release Date: Unreleased
341341
### Others
342342

343343
- **Config:** Added optional `CodeIgniter\Config\Merge` directives for [Registrars](../general/configuration.md#registrars) to control replacing, deep merging, and ordered list additions. Existing registrar merge behavior is unchanged. See [Controlling how values are merged](../general/configuration.md#controlling-how-values-are-merged).
344+
- **Entity:** Added a new `CodeIgniter\Entity\Entity::$mergeAttributesOnInject` property. See [Merging Attributes During Injection](../models/entities.md#merging-attributes-during-injection).
344345
- **Float and Double Casting:** Added support for precision and rounding mode when casting to float or double in entities.
345346
- Added `CodeIgniter\Input\InputData`, `ValidatedInput`, and `InputDataFactory` for reusable typed input data objects.
346347
- Float and Double casting now throws `CastException::forInvalidFloatRoundingMode()` if a rounding mode other than up, down, even, or odd is provided.

‎docs/models/entities.md‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -780,3 +780,88 @@ For scalar values (strings, integers, floats, booleans, null), the Entity uses d
780780
#### Objects and Arrays
781781

782782
For objects and arrays, the Entity JSON-encodes and normalizes the values for comparison. This means that modifications to nested structures, object properties, array elements, nested entities (using `toRawArray()`), enums (`BackedEnum` and `UnitEnum`), datetime objects (`DateTimeInterface`), collections (`Traversable`), value objects with `__toString()`, and objects implementing `JsonSerializable` or `toArray()` will be properly detected.
783+
784+
## Merging Attributes During Injection
785+
786+
!!! success "Available from version 4.8.0"
787+
788+
When a model loads a row into an entity, it calls `injectRawData()` with the selected columns. By default, this replaces the entity's attributes. In the example below, loading only `id` and `role` would drop both the `isBanned` default and the `profile` object created by the constructor.
789+
790+
Set `$mergeAttributesOnInject` to `true` on your entity class to keep existing values for keys the row omits. For keys the row supplies, the incoming value takes precedence, including `null`. The entity also accepts incoming keys that were never declared in `$attributes`.
791+
792+
```php
793+
<?php
794+
795+
namespace App\Entities;
796+
797+
use CodeIgniter\Entity\Entity;
798+
use stdClass;
799+
800+
class User extends Entity
801+
{
802+
protected $attributes = [
803+
'id' => null,
804+
'role' => 'user',
805+
'isBanned' => '0',
806+
'profile' => null,
807+
];
808+
public function __construct(?array $data = null)
809+
{
810+
parent::__construct($data);
811+
$this->attributes['profile'] = new stdClass();
812+
}
813+
}
814+
815+
// $mergeAttributesOnInject = false
816+
// 1. Manual user creation
817+
$user = new User();
818+
819+
// The initial values are exactly there
820+
var_dump(
821+
$user->role, // 'user'
822+
$user->isBanned, // '0'
823+
$user->toArray()['isBanned'], // '0'
824+
$user->profile instanceof stdClass, // true
825+
$user->hasChanged(), // true
826+
);
827+
828+
// 2. The result does not contain these values: "isBanned", "profile"
829+
$user2 = model(UserModel::class)->select('`id`, `role`')->find(10);
830+
// or manually
831+
$user2 = (new User())->injectRawData([
832+
'id' => 10,
833+
'role' => 'admin',
834+
]);
835+
836+
var_dump(
837+
$user2->role, // 'admin'
838+
$user2->isBanned, // null
839+
array_key_exists('isBanned', $user2->toArray()), // false
840+
$user2->profile instanceof stdClass, // false
841+
$user2->hasChanged(), // false
842+
);
843+
844+
// $mergeAttributesOnInject = true
845+
$user3 = (new User())->injectRawData([
846+
'id' => 15,
847+
'role' => 'admin',
848+
]);
849+
850+
var_dump(
851+
$user3->role, // 'admin'
852+
$user3->isBanned, // '0'
853+
$user3->toArray()['isBanned'], // '0'
854+
$user3->profile instanceof stdClass, // true
855+
$user3->hasChanged(), // false
856+
);
857+
```
858+
859+
The direct call to `injectRawData()` illustrates what happens when a model configured to return `User` entities loads a row containing only `id` and `role`. The entity keeps the `isBanned` default and the `profile` object. It records the merged attributes as its original state, so `hasChanged()` returns `false` immediately after loading, even though the incoming role differs from the default.
860+
861+
### Updating a Partially Loaded Entity
862+
863+
An attribute retained after loading may differ from the value stored in the database. For example, suppose the `isBanned` column contains `'1'`. If the query selects only `id` and `role`, the loaded entity retains its default of `'0'` for `isBanned`.
864+
865+
With [`$updateOnlyChanged`](model.md#updateonlychanged) enabled (the default), changing `role` and updating the entity leaves the stored `isBanned` value alone. With `$updateOnlyChanged` disabled, the same update can also write `'0'` to `isBanned` if the field is in [`$allowedFields`](model.md#allowedfields). To update just the role, pass `['role' => $newRole]` to the model's `update()` method.
866+
867+
When `$skipValidation = false` and [`$cleanValidationRules = false`](model.md#cleanvalidationrules), `BaseModel::transformDataToArray()` extracts all attributes regardless of `$updateOnlyChanged`. Retained defaults can therefore overwrite omitted database columns even with `$updateOnlyChanged = true`.

‎system/Entity/Entity.php‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,11 @@ class Entity implements JsonSerializable
126126
*/
127127
protected ?DataCaster $dataCaster = null;
128128

129+
/**
130+
* Merge the raw input data with the initial attributes.
131+
*/
132+
protected bool $mergeAttributesOnInject = false;
133+
129134
/**
130135
* Holds info whenever properties have to be casted.
131136
*/
@@ -504,7 +509,11 @@ private function normalizeValue(mixed $data): mixed
504509
*/
505510
public function injectRawData(array $data)
506511
{
507-
$this->attributes = $data;
512+
if ($this->mergeAttributesOnInject) {
513+
$this->attributes = array_merge($this->attributes, $data);
514+
} else {
515+
$this->attributes = $data;
516+
}
508517

509518
$this->syncOriginal();
510519

‎tests/_support/Entity/Member.php‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace Tests\Support\Entity;
15+
16+
use CodeIgniter\Entity\Entity;
17+
18+
class Member extends Entity
19+
{
20+
protected $attributes = [
21+
'id' => 0,
22+
'name' => 'unknown',
23+
'email' => 'unknown',
24+
'country' => 'unknown',
25+
'created_at' => '2026-11-10 14:50:00',
26+
'updated_at' => '2026-11-10 14:50:00',
27+
'deleted_at' => null,
28+
29+
// The property is not stored in the database
30+
'profile' => 'unknown',
31+
];
32+
33+
public function __construct(?array $data = null)
34+
{
35+
parent::__construct($data);
36+
37+
$this->attributes['profile'] = 'profile';
38+
}
39+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace Tests\Support\Entity;
15+
16+
class MemberStrict extends Member
17+
{
18+
protected bool $mergeAttributesOnInject = true;
19+
}

‎tests/system/Entity/EntityTest.php‎

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1656,6 +1656,121 @@ public function testDataCasterInitEmptyCasts(): void
16561656
$this->assertSame('12345', $entity->first);
16571657
}
16581658

1659+
public function testMergeAttributesOnInjectIsFalse(): void
1660+
{
1661+
$entity = new class () extends Entity {
1662+
protected bool $mergeAttributesOnInject = false;
1663+
1664+
// The "user" attribute is not for DB
1665+
// The "_secure" attribute is hidden
1666+
protected $attributes = [
1667+
'type' => 'Normal',
1668+
'limit' => 10,
1669+
'user' => 'John',
1670+
'_secure' => 'High',
1671+
'reports' => 0,
1672+
];
1673+
protected $original = [
1674+
'type' => 'None',
1675+
'limit' => 0,
1676+
'user' => null,
1677+
'_secure' => 'Low',
1678+
];
1679+
protected $datamap = [
1680+
'payload' => 'DB_PAYLOAD_FIELD',
1681+
'votes' => 'DB_VOTES_FIELD',
1682+
'reports' => 'DB_REPORTS_FIELD',
1683+
];
1684+
};
1685+
1686+
$entity->injectRawData([
1687+
// Missing "type", "user" attributes
1688+
'limit' => 15,
1689+
'_secure' => 'Normal',
1690+
'extra' => 'undefined',
1691+
'DB_PAYLOAD_FIELD' => 'PayloadData',
1692+
]);
1693+
$this->assertSame(
1694+
[
1695+
'limit' => 15,
1696+
'_secure' => 'Normal',
1697+
'extra' => 'undefined',
1698+
'DB_PAYLOAD_FIELD' => 'PayloadData',
1699+
],
1700+
$entity->toRawArray(),
1701+
);
1702+
$this->assertSame(
1703+
[
1704+
'limit' => 15,
1705+
'extra' => 'undefined',
1706+
'payload' => 'PayloadData',
1707+
'votes' => null,
1708+
'reports' => null,
1709+
],
1710+
$entity->toArray(),
1711+
);
1712+
}
1713+
1714+
public function testMergeAttributesOnInjectIsTrue(): void
1715+
{
1716+
$entity = new class () extends Entity {
1717+
protected bool $mergeAttributesOnInject = true;
1718+
1719+
// The "user" attribute is not for DB
1720+
// The "_secure" attribute is hidden
1721+
protected $attributes = [
1722+
'type' => 'Normal',
1723+
'limit' => 10,
1724+
'user' => 'John',
1725+
'_secure' => 'High',
1726+
'reports' => 0,
1727+
];
1728+
protected $original = [
1729+
'type' => 'None',
1730+
'limit' => 0,
1731+
'user' => null,
1732+
'_secure' => 'Low',
1733+
];
1734+
protected $datamap = [
1735+
'payload' => 'DB_PAYLOAD_FIELD',
1736+
'votes' => 'DB_VOTES_FIELD',
1737+
'reports' => 'DB_REPORTS_FIELD',
1738+
];
1739+
};
1740+
1741+
$entity->injectRawData([
1742+
// Missing "type", "user" attributes
1743+
'limit' => 15,
1744+
'_secure' => 'Normal',
1745+
'extra' => 'undefined',
1746+
'DB_PAYLOAD_FIELD' => 'PayloadData',
1747+
]);
1748+
$this->assertSame(
1749+
[
1750+
'type' => 'Normal',
1751+
'limit' => 15,
1752+
'user' => 'John',
1753+
'_secure' => 'Normal',
1754+
'reports' => 0,
1755+
'extra' => 'undefined',
1756+
'DB_PAYLOAD_FIELD' => 'PayloadData',
1757+
],
1758+
$entity->toRawArray(),
1759+
);
1760+
$this->assertSame(
1761+
[
1762+
'type' => 'Normal',
1763+
'limit' => 15,
1764+
'user' => 'John',
1765+
'reports' => null,
1766+
'extra' => 'undefined',
1767+
'payload' => 'PayloadData',
1768+
'votes' => null,
1769+
],
1770+
$entity->toArray(),
1771+
);
1772+
}
1773+
16591774
private function getEntity(): object
16601775
{
16611776
return new class () extends Entity {

0 commit comments

Comments
 (0)