Skip to content

Commit 8809160

Browse files
committed
feat: Merging Attributes During Injection
1 parent 7fd9386 commit 8809160

5 files changed

Lines changed: 217 additions & 31 deletions

File tree

‎docs/changelogs/v4.8.0.md‎

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,8 @@ Release Date: Unreleased
6565

6666
- **CLI:** The `Console::run()` method now accepts an optional `array $tokens` parameter. This allows you to pass an array of command tokens directly to the console runner, which is useful for testing or programmatically running commands. If not provided, it will default to using the global `$argv`.
6767

68-
- **CodeIgniter:** The deprecated parameters in methods have been removed:
69-
- `CodeIgniter\CodeIgniter::handleRequest()` no longer accepts the deprecated `$cacheConfig` and `$returnResponse` parameters.
68+
- **CodeIgniter:** The deprecated parameters in methods have been removed:
69+
- `CodeIgniter\CodeIgniter::handleRequest()` no longer accepts the deprecated `$cacheConfig` and `$returnResponse` parameters.
7070
- `$cacheConfig` is no longer used and is now hard deprecated. A deprecation notice will be triggered if this is passed to the method.
7171
- `$returnResponse` has been removed, since it was already deprecated and unused.
7272
- The updated method signature is now `handleRequest(?RouteCollectionInterface $routes, ?Cache $cacheConfig = null)`.
@@ -75,7 +75,7 @@ Release Date: Unreleased
7575

7676
- **Config:** `CodeIgniter\Config\Services::request()` no longer accepts any parameter.
7777

78-
- **Database:** The following methods have had their signatures updated to remove deprecated parameters:
78+
- **Database:** The following methods have had their signatures updated to remove deprecated parameters:
7979
- `CodeIgniter\Database\Forge::_createTable()` no longer accepts the deprecated `$ifNotExists` parameter. The method signature is now `_createTable(string $table, array $attributes)`.
8080

8181
- **HTTP:** `CodeIgniter\HTTP\OutgoingRequest::__construct()` now requires the `$uri` parameter, which was previously `?URI $uri = null`. Passing `null` only worked when a `Host` header was supplied in the same call, since the constructor otherwise dereferences the URI to set that header. Consequently `OutgoingRequest::getUri()` now returns `URI` instead of `URI|null`, matching `OutgoingRequestInterface`. See [Upgrading from 4.7.x to 4.8.0](../installation/upgrade_480.md) for the migration.
@@ -86,41 +86,41 @@ Release Date: Unreleased
8686

8787
### Property Scope Changes
8888

89-
- **HTTP:** The following properties have changed their scope (visibility):
89+
- **HTTP:** The following properties have changed their scope (visibility):
9090
- `CodeIgniter\HTTP\RequestTrait::$ipAddress` is now private (previously protected).
9191

9292
### Method Scope Changes
9393

9494
- **CLI:** `CodeIgniter\CLI\Commands::getCommandAlternatives()` is now public (previously protected).
9595

96-
- **HTTP:** The following methods have changed their scope (visibility):
96+
- **HTTP:** The following methods have changed their scope (visibility):
9797
- `CodeIgniter\HTTP\URI::setUri()` is now private (previously public).
9898
- `CodeIgniter\HTTP\URI::refreshPath()` is now protected (previously public).
9999
- `CodeIgniter\HTTP\SiteURI::refreshPath()` is now protected (previously public).
100100

101101
### Removed Deprecated Items
102102

103-
- **Autoloader:** Removed the following deprecated methods:
103+
- **Autoloader:** Removed the following deprecated methods:
104104
- `CodeIgniter\Autoloader\Autoloader::sanitizeFileName()`
105105
- `CodeIgniter\Autoloader\Autoloader::discoverComposerNamespaces()`
106106

107107
- **Bootstrap:** The deprecated **system/bootstrap.php** file has been removed.
108108

109-
- **Cache:** Removed the following deprecated methods and constant:
109+
- **Cache:** Removed the following deprecated methods and constant:
110110
- `CodeIgniter\Cache\Handlers\BaseHandler::RESERVED_CHARACTERS` (deprecated since v4.1.5)
111111
- `CodeIgniter\Cache\Handlers\FileHandler::writeFile()` (deprecated since v4.6.0)
112112
- `CodeIgniter\Cache\Handlers\FileHandler::deleteFile()` (deprecated since v4.6.0)
113113
- `CodeIgniter\Cache\Handlers\FileHandler::getDirFileInfo()` (deprecated since v4.6.0)
114114
- `CodeIgniter\Cache\Handlers\FileHandler::getFileInfo()` (deprecated since v4.6.0)
115115

116-
- **CLI:** Removed the following deprecated properties and methods:
116+
- **CLI:** Removed the following deprecated properties and methods:
117117
- `CodeIgniter\CLI\BaseCommand::getPad()`
118118
- `CodeIgniter\CLI\CLI::$readline_support`
119119
- `CodeIgniter\CLI\CLI::$wait_msg`
120120
- `CodeIgniter\CLI\CLI::isWindows()`
121121
- `CodeIgniter\CLI\GeneratorTrait::execute()`
122122

123-
- **CodeIgniter:** Removed the following deprecated properties and methods:
123+
- **CodeIgniter:** Removed the following deprecated properties and methods:
124124
- `CodeIgniter\CodeIgniter::$cacheTTL`
125125
- `CodeIgniter\CodeIgniter::$returnResponse`
126126
- `CodeIgniter\CodeIgniter::initializeKint()`
@@ -136,10 +136,10 @@ Release Date: Unreleased
136136
- `CodeIgniter\CodeIgniter::callExit()`
137137
- `CodeIgniter\Test\MockCodeIgniter::callExit()`
138138

139-
- **Config:** Removed the following deprecated property:
139+
- **Config:** Removed the following deprecated property:
140140
- `CodeIgniter\Config\BaseService::$services` (deprecated since v4.5.0)
141141

142-
- **Database:** Removed the following deprecated properties and methods:
142+
- **Database:** Removed the following deprecated properties and methods:
143143
- `CodeIgniter\Database\BaseBuilder::setInsertBatch()`
144144
- `CodeIgniter\Database\BaseBuilder::setUpdateBatch()`
145145
- `CodeIgniter\Database\BaseBuilder::cleanClone()`
@@ -151,7 +151,7 @@ Release Date: Unreleased
151151
- `CodeIgniter\Database\OCI8\Forge::getError()`
152152
- `CodeIgniter\Database\SQLSRV\Forge::$createTableIfStr`
153153

154-
- **Debug:** Removed the following deprecated properties and methods:
154+
- **Debug:** Removed the following deprecated properties and methods:
155155
- `CodeIgniter\Debug\Toolbar\Collectors\BaseCollector::cleanPath()` (deprecated since v4.2.0)
156156
- `CodeIgniter\Debug\Exceptions::$ob_level` (deprecated since v4.4.0)
157157
- `CodeIgniter\Debug\Exceptions::$viewPath` (deprecated since v4.4.0)
@@ -164,20 +164,20 @@ Release Date: Unreleased
164164
- `CodeIgniter\Debug\Exceptions::describeMemory()` (deprecated since v4.4.0)
165165
- `CodeIgniter\Debug\Exceptions::highlightFile()` (deprecated since v4.4.0)
166166

167-
- **Exceptions:** Removed the following static constructors of `FrameworkException` and its child classes:
167+
- **Exceptions:** Removed the following static constructors of `FrameworkException` and its child classes:
168168
- `CodeIgniter\Exceptions\DownloadException::forCannotSetCache()`
169169
- `CodeIgniter\Exceptions\FrameworkException::forMissingExtension()`
170170
- `CodeIgniter\Honeypot\Exceptions\HoneypotException::forNoHiddenValue()`
171171
- `CodeIgniter\HTTP\Exceptions\HTTPException::forInvalidSameSiteSetting()`
172172
- `CodeIgniter\Security\Exceptions\SecurityException::forInvalidSameSite()`
173173
- `CodeIgniter\Session\Exceptions\SessionException::forInvalidSameSiteSetting()`
174174

175-
- **Filters:** Removed the following deprecated properties and methods:
175+
- **Filters:** Removed the following deprecated properties and methods:
176176
- `CodeIgniter\Filters\Filters::$arguments` (deprecated since v4.6.0)
177177
- `CodeIgniter\Filters\Filters::$argumentsClass` (deprecated since v4.6.0)
178178
- `CodeIgniter\Filters\Filters::getArguments()` (deprecated since v4.6.0)
179179

180-
- **HTTP:** Removed the following deprecated properties and methods:
180+
- **HTTP:** Removed the following deprecated properties and methods:
181181
- `CodeIgniter\HTTP\Message::getHeaders()` (deprecated since v4.0.5)
182182
- `CodeIgniter\HTTP\Message::getHeader()` (deprecated since v4.0.5)
183183
- `CodeIgniter\HTTP\RequestTrait::getEnv()` (deprecated since v4.4.4)
@@ -190,7 +190,7 @@ Release Date: Unreleased
190190
- `CodeIgniter\HTTP\SiteURI::setBaseURL()` (deprecated since v4.4.0)
191191
- `CodeIgniter\HTTP\SiteURI::setURI()` (deprecated since v4.4.0)
192192

193-
- **Security:** Removed the following deprecated properties and methods:
193+
- **Security:** Removed the following deprecated properties and methods:
194194
- `CodeIgniter\Security\SecurityInterface::sanitizeFilename()` (deprecated since v4.6.2)
195195
- `CodeIgniter\Security\Security::sanitizeFilename()` (deprecated since v4.6.2)
196196
- `CodeIgniter\Security\Security::$csrfProtection` (deprecated since v4.4.0)
@@ -339,6 +339,7 @@ Release Date: Unreleased
339339
### Others
340340

341341
- **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).
342+
- **Entity:** Added a new `CodeIgniter\Entity\Entity::$mergeAttributesOnInject` property. See [Merging Attributes During Injection](../models/entities.md#merging-attributes-during-injection).
342343
- **Float and Double Casting:** Added support for precision and rounding mode when casting to float or double in entities.
343344
- Added `CodeIgniter\Input\InputData`, `ValidatedInput`, and `InputDataFactory` for reusable typed input data objects.
344345
- Float and Double casting now throws `CastException::forInvalidFloatRoundingMode()` if a rounding mode other than up, down, even, or odd is provided.
@@ -348,15 +349,15 @@ Release Date: Unreleased
348349

349350
## Message Changes
350351

351-
- Added new language keys:
352+
- Added new language keys:
352353
- `Cache.unsupportedLockStore` (`CacheException::forUnsupportedLockStore()`)
353354
- `CLI.commandAlias` and `CLI.helpAliases` (command alias rendering in `list` and `help`)
354355
- `CLI.altCommandNone`, `CLI.altCommandRun`, and `CLI.altCommandSelect` (correcting a mistyped command)
355356
- `CLI.generator.invalidCommandType` (`make:command` rejecting an invalid `--type`)
356357
- `CLI.generator.invalidReturnType` (`make:model` rejecting an invalid `--return`)
357358
- `Commands.invalidCommandAlias`, `Commands.commandAliasSameAsName`, `Commands.duplicateCommandAlias`, `Commands.aliasClashesWithCommandName`, and `Commands.aliasClashesWithAlias` (command alias validation)
358359

359-
- Removed deprecated language keys tied to removed exception constructors:
360+
- Removed deprecated language keys tied to removed exception constructors:
360361
- `Core.missingExtension` (`FrameworkException::forMissingExtension()`)
361362
- `HTTP.cannotSetCache` (`DownloadException::forCannotSetCache()`)
362363
- `HTTP.disallowedAction`

‎docs/installation/upgrade_480.md‎

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,10 @@ public function handle($level, $message, array $context = []): bool
144144

145145
The context array may contain the CI global context data under the `HandlerInterface::GLOBAL_CONTEXT_KEY` (`'_ci_context'`) key when `$logGlobalContext` is enabled in `Config\Logger`.
146146

147+
### Entity
148+
149+
If you redefine the Entity base class or modify the `injectRawData()` method, you need to add a new `$mergeAttributesOnInject` property. See [Merging Attributes During Injection](../models/entities.md#merging-attributes-during-injection).
150+
147151
## Project Files
148152

149153
Some files in the **project space** (root, app, public, writable) received updates. Due to these files being outside of the **system** scope they will not be changed without your intervention.
@@ -157,39 +161,39 @@ The following files received significant changes (including deprecations or visu
157161

158162
#### Config
159163

160-
- **app/Config/Filters.php**
164+
- **app/Config/Filters.php**
161165
- Added a new filter named `requestid` that adds a unique request ID to each request in the application's context.
162166

163-
- **app/Config/Generators.php**
167+
- **app/Config/Generators.php**
164168
- `Config\Generators::$views` added entries for `make:request`, `make:test`, and `make:transformer`, and dropped the stale `session:migration` entry.
165169

166-
- **app/Config/Logger.php**
170+
- **app/Config/Logger.php**
167171
- `Config\Logger::$handlers` added a new key `stopChainOnFailure` to the `FileHandler` and `ErrorlogHandler` settings.
168172

169-
- **app/Config/Mimes.php**
173+
- **app/Config/Mimes.php**
170174
- `Config\Mimes::$mimes` added a new key `md` for Markdown files.
171175

172-
- **app/Config/Routing.php**
176+
- **app/Config/Routing.php**
173177
- `Config\Routing::$placeholderSamples` was added to provide sample values for custom route placeholders so the `spark routes` command can resolve their filters.
174178

175-
- **app/Config/Security.php**
179+
- **app/Config/Security.php**
176180
- `Config\Security::$csrfFetchMetadata` and `Config\Security::$csrfFetchMetadataRejectSameSite` were added for Fetch Metadata based CSRF protection.
177181

178182
#### Error Views
179183

180-
- **app/Views/errors/cli/error_exception.php**
184+
- **app/Views/errors/cli/error_exception.php**
181185
- Shows the backtrace also when the command runs with `-v`.
182186

183-
- **app/Views/errors/html/debug.css**
187+
- **app/Views/errors/html/debug.css**
184188
- Added styles for the **Copy Details** button.
185189

186-
- **app/Views/errors/html/debug.js**
190+
- **app/Views/errors/html/debug.js**
187191
- Added clipboard handling for the **Copy Details** button.
188192

189-
- **app/Views/errors/html/error_exception.php**
193+
- **app/Views/errors/html/error_exception.php**
190194
- Added a **Copy Details** button to detailed HTML exception pages.
191195

192-
- **app/Views/errors/html/error_report.php**
196+
- **app/Views/errors/html/error_report.php**
193197
- Added a Markdown error report partial used by the **Copy Details** button.
194198

195199
### All Changes

‎docs/models/entities.md‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -780,3 +780,62 @@ 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+
By default, your entity can contain the initial state of the attributes. When working with objects, you can rely on the fact that all the necessary properties are available. However, after receiving the object from the database, you may find that the entity is not complete and some properties are missing.
789+
790+
Suppose there is no `isBanned` field in the table, and the `profile` property is virtual and filled in another way.
791+
792+
With the `$mergeAttributesOnInject = false` you will get errors because by default properties are overwritten in `injectRawData()`.
793+
794+
```php
795+
<?php
796+
class User extends Entity {
797+
protected $attributes = [
798+
'id' => null,
799+
'role' => 'user',
800+
'isBanned' => '0',
801+
'profile' => null,
802+
];
803+
public function __construct(?array $data = null)
804+
{
805+
parent::__construct($data);
806+
$this->attributes['profile'] = new Profile();
807+
}
808+
}
809+
810+
// Manual user creation
811+
$user = new User([...]);
812+
813+
// The values are exactly there
814+
echo $user->isBanned; // '0'
815+
echo $user->toArray()['isBanned']; // '0'
816+
var_dump($user->profile instanceof Profile); // true
817+
818+
// Getting the user from the database
819+
$user2 = model(UserModel::class)->find(1);
820+
821+
// The values will be empty
822+
echo $user2->isBanned; // null
823+
echo $user2->toArray()['isBanned']; // Undefined
824+
var_dump($user2->profile instanceof Profile); // false
825+
```
826+
827+
To change the behavior, toggle the `$mergeAttributesOnInject = true` flag. As a result, you will get the expected list of attributes.
828+
829+
```php
830+
<?php
831+
832+
// Getting the user from the database
833+
$user2 = model(UserModel::class)->find(1);
834+
835+
echo $user2->isBanned; // '0'
836+
echo $user2->toArray()['isBanned']; // '0'
837+
var_dump($user2->profile instanceof Profile); // true
838+
```
839+
840+
!!! note "Note"
841+
The flag does not matter if you have not defined the keys in `$attributes`.

‎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 input data (from the Database) 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

0 commit comments

Comments
 (0)