Skip to content

Commit 6190f89

Browse files
committed
feat(model): add insert-only fields
- add $insertOnlyFields and setInsertOnlyFields() to Model - prevent configured fields from being submitted during update operations - allow insert-only fields during insert and insertBatch - document the Model-level protection boundaries - add coverage for update, save, updateBatch, entity, and protect(false) paths Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com>
1 parent 4e8c5de commit 6190f89

10 files changed

Lines changed: 296 additions & 2 deletions

File tree

‎system/BaseModel.php‎

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,13 @@ abstract class BaseModel
155155
*/
156156
protected $allowedFields = [];
157157

158+
/**
159+
* Fields that may be inserted but not updated through Model write methods.
160+
*
161+
* @var list<string>
162+
*/
163+
protected $insertOnlyFields = [];
164+
158165
/**
159166
* If true, will set created_at, and updated_at
160167
* values during insert and update routines.
@@ -1162,7 +1169,10 @@ public function updateBatch(?array $set = null, ?string $index = null, int $batc
11621169

11631170
// Must be called first so we don't
11641171
// strip out updated_at values.
1165-
$this->ensureNoDisallowedFields($row, $index === null ? [] : [$index]);
1172+
$ignoredFields = $index === null ? [] : [$index];
1173+
1174+
$this->ensureNoInsertOnlyFields($row, $ignoredFields);
1175+
$this->ensureNoDisallowedFields($row, $ignoredFields);
11661176
$row = $this->doProtectFields($row);
11671177

11681178
// Restore updateIndex value in case it was wiped out
@@ -1375,6 +1385,20 @@ public function setAllowedFields(array $allowedFields)
13751385
return $this;
13761386
}
13771387

1388+
/**
1389+
* Sets the fields that may be inserted but not updated.
1390+
*
1391+
* @param list<string> $insertOnlyFields
1392+
*
1393+
* @return $this
1394+
*/
1395+
public function setInsertOnlyFields(array $insertOnlyFields)
1396+
{
1397+
$this->insertOnlyFields = $insertOnlyFields;
1398+
1399+
return $this;
1400+
}
1401+
13781402
/**
13791403
* Sets whether or not we should whitelist data set during
13801404
* updates or inserts against $this->availableFields.
@@ -1462,6 +1486,37 @@ protected function ensureNoDisallowedFields(array $row, array $ignoredFields = [
14621486
}
14631487
}
14641488

1489+
/**
1490+
* Throws when update data contains fields that may only be inserted.
1491+
*
1492+
* @param row_array $row
1493+
* @param list<string> $ignoredFields
1494+
*
1495+
* @throws DataException
1496+
*/
1497+
protected function ensureNoInsertOnlyFields(array $row, array $ignoredFields = []): void
1498+
{
1499+
if (! $this->protectFields || $this->allowedFields === [] || $this->insertOnlyFields === []) {
1500+
return;
1501+
}
1502+
1503+
$insertOnlyFields = [];
1504+
1505+
foreach (array_keys($row) as $key) {
1506+
if (in_array($key, $ignoredFields, true)) {
1507+
continue;
1508+
}
1509+
1510+
if (in_array($key, $this->insertOnlyFields, true)) {
1511+
$insertOnlyFields[] = $key;
1512+
}
1513+
}
1514+
1515+
if ($insertOnlyFields !== []) {
1516+
throw DataException::forInsertOnlyFields(static::class, $insertOnlyFields);
1517+
}
1518+
}
1519+
14651520
/**
14661521
* Ensures that only the fields that are allowed to be inserted are in
14671522
* the data array.
@@ -1496,6 +1551,7 @@ protected function doProtectFieldsForInsert(array $row): array
14961551
*/
14971552
protected function doProtectFieldsForUpdate(array $row): array
14981553
{
1554+
$this->ensureNoInsertOnlyFields($row);
14991555
$this->ensureNoDisallowedFields($row);
15001556

15011557
return $this->doProtectFields($row);

‎system/Commands/Generators/Views/model.tpl.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ class {class} extends Model
1616
protected $useSoftDeletes = false;
1717
protected $protectFields = true;
1818
protected $allowedFields = [];
19+
protected $insertOnlyFields = [];
1920

2021
protected bool $throwOnDisallowedFields = false;
2122
protected bool $allowEmptyInserts = false;

‎system/Database/Exceptions/DataException.php‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,16 @@ public static function forDisallowedFields(string $model, array $fields)
8383
return new static(lang('Database.disallowedFields', [$model, implode(', ', $fields)]));
8484
}
8585

86+
/**
87+
* @param list<string> $fields
88+
*
89+
* @return DataException
90+
*/
91+
public static function forInsertOnlyFields(string $model, array $fields)
92+
{
93+
return new static(lang('Database.insertOnlyFields', [$model, implode(', ', $fields)]));
94+
}
95+
8696
/**
8797
* @return DataException
8898
*/

‎system/Language/en/Database.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
'invalidArgument' => 'You must provide a valid "{0}".',
1818
'invalidAllowedFields' => 'Allowed fields must be specified for model: "{0}"',
1919
'disallowedFields' => 'Fields are not allowed for model "{0}": {1}',
20+
'insertOnlyFields' => 'Fields cannot be updated for model "{0}": {1}',
2021
'emptyDataset' => 'There is no data to {0}.',
2122
'emptyPrimaryKey' => 'There is no primary key defined when trying to make {0}.',
2223
'failGetFieldData' => 'Failed to get field data from database.',

‎system/Model.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -785,6 +785,7 @@ protected function doProtectFieldsForInsert(array $row): array
785785

786786
protected function doProtectFieldsForUpdate(array $row): array
787787
{
788+
$this->ensureNoInsertOnlyFields($row, [$this->primaryKey]);
788789
$this->ensureNoDisallowedFields($row, [$this->primaryKey]);
789790

790791
return $this->doProtectFields($row);
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
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 CodeIgniter\Models;
15+
16+
use CodeIgniter\Database\Exceptions\DataException;
17+
use PHPUnit\Framework\Attributes\Group;
18+
use Tests\Support\Entity\User;
19+
use Tests\Support\Models\UserModel;
20+
use Tests\Support\Models\ValidModel;
21+
22+
/**
23+
* @internal
24+
*/
25+
#[Group('DatabaseLive')]
26+
final class InsertOnlyFieldsModelTest extends LiveModelTestCase
27+
{
28+
public function testInsertAllowsInsertOnlyFields(): void
29+
{
30+
$this->createModel(UserModel::class)->setInsertOnlyFields(['email'])->insert([
31+
'name' => 'Insert Only',
32+
'email' => 'insert-only@example.com',
33+
'country' => 'US',
34+
]);
35+
36+
$this->seeInDatabase('user', [
37+
'email' => 'insert-only@example.com',
38+
]);
39+
}
40+
41+
public function testInsertBatchAllowsInsertOnlyFields(): void
42+
{
43+
$result = $this->createModel(UserModel::class)->setInsertOnlyFields(['email'])->insertBatch([
44+
[
45+
'name' => 'Insert Only Batch',
46+
'email' => 'insert-only-batch@example.com',
47+
'country' => 'US',
48+
],
49+
]);
50+
51+
$this->assertSame(1, $result);
52+
$this->seeInDatabase('user', [
53+
'email' => 'insert-only-batch@example.com',
54+
]);
55+
}
56+
57+
public function testUpdateThrowsOnInsertOnlyFields(): void
58+
{
59+
$this->expectException(DataException::class);
60+
$this->expectExceptionMessage('Fields cannot be updated for model "Tests\Support\Models\UserModel": email');
61+
62+
$this->createModel(UserModel::class)->setInsertOnlyFields(['email'])->update(1, [
63+
'name' => 'Insert Only Update',
64+
'email' => 'insert-only-update@example.com',
65+
]);
66+
}
67+
68+
public function testSaveUpdateThrowsOnInsertOnlyFields(): void
69+
{
70+
$this->expectException(DataException::class);
71+
$this->expectExceptionMessage('Fields cannot be updated for model "Tests\Support\Models\UserModel": email');
72+
73+
$this->createModel(UserModel::class)->setInsertOnlyFields(['email'])->save([
74+
'id' => 1,
75+
'name' => 'Insert Only Save',
76+
'email' => 'insert-only-save@example.com',
77+
]);
78+
}
79+
80+
public function testSetUpdateThrowsOnInsertOnlyFields(): void
81+
{
82+
$this->expectException(DataException::class);
83+
$this->expectExceptionMessage('Fields cannot be updated for model "Tests\Support\Models\UserModel": email');
84+
85+
$this->createModel(UserModel::class)->setInsertOnlyFields(['email'])
86+
->where('id', 1)
87+
->set('email', 'insert-only-set@example.com')
88+
->update(null, ['name' => 'Insert Only Set']);
89+
}
90+
91+
public function testUpdateBatchThrowsOnInsertOnlyFields(): void
92+
{
93+
$this->expectException(DataException::class);
94+
$this->expectExceptionMessage('Fields cannot be updated for model "Tests\Support\Models\UserModel": email');
95+
96+
$this->createModel(UserModel::class)->setInsertOnlyFields(['email'])->updateBatch([
97+
[
98+
'id' => 1,
99+
'name' => 'Insert Only Batch',
100+
'email' => 'insert-only-update-batch@example.com',
101+
],
102+
], 'id');
103+
}
104+
105+
public function testUpdateBatchAllowsInsertOnlyFieldAsIndex(): void
106+
{
107+
$result = $this->createModel(UserModel::class)->setInsertOnlyFields(['email'])->updateBatch([
108+
[
109+
'email' => 'derek@world.com',
110+
'name' => 'Insert Only Batch Index',
111+
],
112+
], 'email');
113+
114+
$this->assertSame(1, $result);
115+
$this->seeInDatabase('user', [
116+
'email' => 'derek@world.com',
117+
'name' => 'Insert Only Batch Index',
118+
]);
119+
}
120+
121+
public function testEntityUpdateThrowsOnChangedInsertOnlyFields(): void
122+
{
123+
$model = new class ($this->db) extends UserModel {
124+
protected $returnType = User::class;
125+
protected $insertOnlyFields = ['email'];
126+
};
127+
128+
$user = $model->find(1);
129+
$this->assertInstanceOf(User::class, $user);
130+
131+
$user->email = 'insert-only-entity@example.com';
132+
133+
$this->expectException(DataException::class);
134+
$this->expectExceptionMessage('Fields cannot be updated for model "' . $model::class . '": email');
135+
136+
$model->update($user->id, $user);
137+
}
138+
139+
public function testEntityUpdateAllowsUnchangedInsertOnlyFields(): void
140+
{
141+
$model = new class ($this->db) extends UserModel {
142+
protected $returnType = User::class;
143+
protected $insertOnlyFields = ['email'];
144+
};
145+
146+
$user = $model->find(1);
147+
$this->assertInstanceOf(User::class, $user);
148+
149+
$user->name = 'Insert Only Entity';
150+
151+
$this->assertTrue($model->update($user->id, $user));
152+
$this->seeInDatabase('user', [
153+
'id' => 1,
154+
'name' => 'Insert Only Entity',
155+
]);
156+
}
157+
158+
public function testProtectFalseBypassesInsertOnlyFields(): void
159+
{
160+
$result = $this->createModel(UserModel::class)->setInsertOnlyFields(['email'])->protect(false)->update(1, [
161+
'email' => 'insert-only-disabled@example.com',
162+
]);
163+
164+
$this->assertTrue($result);
165+
$this->seeInDatabase('user', [
166+
'id' => 1,
167+
'email' => 'insert-only-disabled@example.com',
168+
]);
169+
}
170+
171+
public function testValidationRunsBeforeInsertOnlyFields(): void
172+
{
173+
$model = $this->createModel(ValidModel::class)->setInsertOnlyFields(['description']);
174+
$this->setPrivateProperty($model, 'cleanValidationRules', false);
175+
176+
$this->assertFalse($model->update(1, [
177+
'description' => 'Insert only description',
178+
]));
179+
$this->assertArrayHasKey('name', $model->errors());
180+
}
181+
}

‎user_guide_src/source/changelogs/v4.8.0.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,7 @@ Model
274274

275275
- Added new ``chunkRows()`` method to ``CodeIgniter\Model`` for processing large datasets in smaller chunks.
276276
- Added new ``firstOrInsert()`` method to ``CodeIgniter\Model`` that finds the first row matching the given attributes or inserts a new one. See :ref:`model-first-or-insert`.
277+
- Added ``$insertOnlyFields`` and ``setInsertOnlyFields()`` to ``CodeIgniter\Model`` to prevent configured fields from being submitted during Model update operations. See :ref:`model-insert-only-fields`.
277278
- Added ``$throwOnDisallowedFields`` and ``throwOnDisallowedFields()`` to ``CodeIgniter\Model`` to throw a ``DataException`` when write data contains fields that would otherwise be discarded by ``$allowedFields``. See :ref:`model-throw-on-disallowed-fields`.
278279

279280
Libraries

‎user_guide_src/source/models/model.rst‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,31 @@ potential mass assignment vulnerabilities.
163163

164164
.. note:: The `$primaryKey`_ field should never be an allowed field.
165165

166+
.. _model-insert-only-fields:
167+
168+
$insertOnlyFields
169+
-----------------
170+
171+
.. versionadded:: 4.8.0
172+
173+
This array may contain fields that can be set during ``insert()`` and
174+
``insertBatch()`` calls, but cannot be submitted during ``update()``,
175+
``updateBatch()``, or update-side ``save()`` calls.
176+
177+
This is useful for values that should be created once and then left unchanged
178+
through normal Model writes, such as public IDs, external references, or
179+
generated slugs.
180+
181+
.. literalinclude:: model/069.php
182+
183+
Fields listed here must also be listed in `$allowedFields`_ when field
184+
protection is enabled. This is Model-level protection only. It does not create a
185+
database constraint, does not inspect previous database values, and does not
186+
intercept direct Query Builder writes. Calling ``protect(false)`` disables this
187+
protection.
188+
189+
You may also change this setting with the ``setInsertOnlyFields()`` method.
190+
166191
.. _model-throw-on-disallowed-fields:
167192

168193
$throwOnDisallowedFields
@@ -944,6 +969,11 @@ When throwing on disallowed fields is enabled, operation fields such as the
944969
primary key passed to ``update()`` or the index passed to ``updateBatch()`` may
945970
still be used to locate rows.
946971

972+
If some allowed fields should only be set during insert operations, list them
973+
in `$insertOnlyFields`_:
974+
975+
.. literalinclude:: model/069.php
976+
947977
Occasionally, you will find times where you need to be able to change these elements. This is often during
948978
testing, migrations, or seeds. In these cases, you can turn the protection on or off:
949979

‎user_guide_src/source/models/model/005.php‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ class UserModel extends Model
1414
protected $returnType = 'array';
1515
protected $useSoftDeletes = true;
1616

17-
protected $allowedFields = ['name', 'email'];
17+
protected $allowedFields = ['name', 'email'];
18+
protected $insertOnlyFields = [];
1819

1920
protected bool $allowEmptyInserts = false;
2021
protected bool $updateOnlyChanged = true;
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<?php
2+
3+
namespace App\Models;
4+
5+
use CodeIgniter\Model;
6+
7+
class UserModel extends Model
8+
{
9+
protected $allowedFields = ['public_id', 'name', 'email'];
10+
11+
protected $insertOnlyFields = ['public_id'];
12+
}

0 commit comments

Comments
 (0)