Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 128 additions & 0 deletions system/Config/BaseConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use CodeIgniter\Autoloader\FileLocatorInterface;
use CodeIgniter\Exceptions\ConfigException;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\Exceptions\RuntimeException;
use Config\Encryption;
use Config\Modules;
Expand Down Expand Up @@ -311,6 +312,14 @@ protected function registerProperties()
}

foreach ($properties as $property => $value) {
// Directives are recognized only at the property root.
if ($value instanceof Merge) {
$this->{$property} = $this->applyMerge($this->{$property} ?? null, $value);

continue;
}

// Legacy behavior - unchanged, and on the hot path with no extra checks.
if (isset($this->{$property}) && is_array($this->{$property}) && is_array($value)) {
$this->{$property} = array_merge($this->{$property}, $value);
} else {
Expand All @@ -319,4 +328,123 @@ protected function registerProperties()
}
}
}

/**
* Applies a property-root Merge directive against the current value.
*
* REPLACE is terminal - its payload is taken verbatim. The list strategies
* (APPEND/PREPEND/BEFORE/AFTER) resolve via mergeList(). BY_KEY recurses via
* mergeByKey(), honoring nested directives.
*/
private function applyMerge(mixed $current, Merge $directive): mixed
{
return match ($directive->strategy) {
Merge::REPLACE => $directive->value,
Merge::BY_KEY => $this->mergeByKey(is_array($current) ? $current : [], $directive->value),
Merge::APPEND, Merge::PREPEND, Merge::BEFORE, Merge::AFTER => $this->mergeList(is_array($current) ? $current : [], $directive),
default => throw new InvalidArgumentException('Unknown merge strategy: ' . $directive->strategy),
};
}

/**
* Resolves a list directive (APPEND, PREPEND, BEFORE, AFTER) against the
* current value treated as a list.
*
* The directives never introduce a duplicate value: the incoming payload is
* de-duplicated against itself (keeping first-seen order) and values already
* in the list are not added again. Duplicates that already exist in the
* current list are left untouched. Then:
* - APPEND/PREPEND add only the values that are absent - already-present
* values are left where they are (no relocation).
* - BEFORE/AFTER move an already-present value to the anchor position, but
* only when the anchor exists. If the anchor is missing they fall back to
* APPEND/PREPEND respectively and do not relocate already-present values.
*
* The anchor is matched strictly (===) against the list elements, using the
* first match. Do not use a value as both the anchor and an inserted value.
*
* @param array<array-key, mixed> $current
*
* @return list<mixed>
*/
private function mergeList(array $current, Merge $directive): array
{
$current = array_values($current);

// De-duplicate the payload itself (strict, first-seen order) so a value
// repeated within it is not inserted twice.
$incoming = [];

foreach ($directive->value as $value) {
if (! in_array($value, $incoming, true)) {
$incoming[] = $value;
}
}

$anchored = $directive->strategy === Merge::BEFORE || $directive->strategy === Merge::AFTER;
$anchorFound = $anchored && in_array($directive->anchor, $current, true);

if ($anchorFound) {
// Move-to-position: pull out any present copies, then insert the
// whole incoming block at the (recomputed) anchor position.
$current = array_values(array_filter(
$current,
static fn ($value): bool => ! in_array($value, $incoming, true),
));

$index = (int) array_search($directive->anchor, $current, true);
$offset = $directive->strategy === Merge::AFTER ? $index + 1 : $index;

array_splice($current, $offset, 0, $incoming);

return $current;
}

// APPEND/PREPEND, or BEFORE/AFTER with a missing anchor: add only the
// values not already present, without relocating anything.
$incoming = array_values(array_filter(
$incoming,
static fn ($value): bool => ! in_array($value, $current, true),
));

return $directive->strategy === Merge::PREPEND || $directive->strategy === Merge::BEFORE
? array_merge($incoming, $current)
: array_merge($current, $incoming);
}

/**
* Recursive by-key merge used by Merge::byKey(): string keys recurse, integer
* keys append, scalar leaves are replaced, and nested Merge directives are
* honored. A missing/non-array current child uses [] as its base, so directives
* in brand-new subtrees are still resolved.
*
* @param array<array-key, mixed> $current
* @param array<array-key, mixed> $incoming
*
* @return array<array-key, mixed>
*/
private function mergeByKey(array $current, array $incoming): array
{
foreach ($incoming as $key => $value) {
if ($value instanceof Merge) {
if (is_int($key)) {
// No stable current element at an appended position; resolve against null.
$current[] = $this->applyMerge(null, $value);
} else {
$current[$key] = $this->applyMerge($current[$key] ?? null, $value);
}
} elseif (is_int($key)) {
$current[] = $value;
} elseif (is_array($value)) {
$current[$key] = $this->mergeByKey(
isset($current[$key]) && is_array($current[$key]) ? $current[$key] : [],
$value,
);
} else {
$current[$key] = $value;
}
}

return $current;
}
}
168 changes: 168 additions & 0 deletions system/Config/Merge.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
<?php

declare(strict_types=1);

/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace CodeIgniter\Config;

use CodeIgniter\Exceptions\InvalidArgumentException;

/**
* Describes how a Registrar value should be merged into an existing
* Config property. Interpreted when returned as the value of a config
* property; nested directives are honored inside Merge::byKey().
*
* @see \CodeIgniter\Config\BaseConfig
*/
final readonly class Merge
{
/**
* Discard the existing value and use the new one.
*/
public const REPLACE = 'replace';

/**
* Add absent list items to the end of the existing value.
*/
public const APPEND = 'append';

/**
* Add absent list items to the front of the existing value.
*/
public const PREPEND = 'prepend';

/**
* Insert list items immediately before the anchor element.
*/
public const BEFORE = 'before';

/**
* Insert list items immediately after the anchor element.
*/
public const AFTER = 'after';

/**
* Deep-merge by key: string keys recurse, integer keys append, scalars replace.
*/
public const BY_KEY = 'byKey';

/**
* @param mixed $value Any value for REPLACE; array for the list strategies and BY_KEY.
* @param mixed $anchor The element BEFORE/AFTER position against (matched strictly).
*/
private function __construct(
public string $strategy,
public mixed $value,
public mixed $anchor = null,
) {
}

/**
* Replace the existing value entirely (terminal: the payload is used
* verbatim). Accepts any type, so it works for scalars too:
* Merge::replace(false), Merge::replace('driver'), Merge::replace(null),
* or arrays (e.g. ['a','b'] + ['c'] => ['c']).
*/
public static function replace(mixed $value): self
{
return new self(self::REPLACE, $value);
}

/**
* Append absent list items to the end of the existing value
* (e.g. ['a','b'] + ['b','c'] => ['a','b','c']). Values already present are
* left where they are. The payload is literal - for nested control, use
* byKey() rather than nesting directives in an append() payload. List keys
* are not preserved: the value is treated as a list.
*
* @param list<mixed> $value
*/
public static function append(array $value): self
{
return new self(self::APPEND, $value);
}

/**
* Prepend absent list items to the front of the existing value
* (e.g. ['a','b'] + ['c'] => ['c','a','b']). Values already present are left
* where they are. List keys are not preserved: the value is treated as a list.
*
* @param list<mixed> $value
*/
public static function prepend(array $value): self
{
return new self(self::PREPEND, $value);
}

/**
* Insert list items immediately before the first element equal (===) to
* $anchor. An already-present value is moved to this position. If the anchor
* is not in the list this falls back to prepend() and does not relocate
* already-present values. List keys are not preserved.
*
* @param list<mixed> $value
*
* @throws InvalidArgumentException if $anchor is also one of the inserted values.
*/
public static function before(mixed $anchor, array $value): self
{
self::assertAnchorNotInPayload($anchor, $value, self::BEFORE);

return new self(self::BEFORE, $value, $anchor);
}

/**
* Insert list items immediately after the first element equal (===) to
* $anchor. An already-present value is moved to this position. If the anchor
* is not in the list this falls back to append() and does not relocate
* already-present values. List keys are not preserved.
*
* @param list<mixed> $value
*
* @throws InvalidArgumentException if $anchor is also one of the inserted values.
*/
public static function after(mixed $anchor, array $value): self
{
self::assertAnchorNotInPayload($anchor, $value, self::AFTER);

return new self(self::AFTER, $value, $anchor);
}

/**
* Guards against anchoring a before()/after() insert on a value that is also
* being inserted. That request is contradictory - the anchor would be removed
* by de-duplication before it could be located - so it is rejected outright.
*
* @param list<mixed> $value
*/
private static function assertAnchorNotInPayload(mixed $anchor, array $value, string $strategy): void
{
if (in_array($anchor, $value, true)) {
throw new InvalidArgumentException(
'Merge::' . $strategy . '() cannot use a value that is also being inserted as its anchor.',
);
}
}

/**
* Deep-merge into the existing value by key: associative (string) keys are
* merged/recursed, list (integer) keys append, scalar leaves are replaced.
* Nested Merge directives ARE honored within the payload. Named byKey() to
* distance it from PHP's array_merge_recursive(), which collects scalars
* into arrays.
*
* @param array<array-key, mixed> $value
*/
public static function byKey(array $value): self
{
return new self(self::BY_KEY, $value);
}
}
37 changes: 37 additions & 0 deletions tests/_support/Config/MergeOrderRegistrar.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

declare(strict_types=1);

/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace Tests\Support\Config;

use CodeIgniter\Config\Merge;

/**
* Registrar exercising the ordering directives (prepend/before/after) through
* the real registrar flow, including nesting inside byKey() for a Filters-style
* globals list.
*/
class MergeOrderRegistrar
{
public static function MergeRegistrarConfig(): array
{
return [
// Order a filter relative to an existing one in a nested list.
'globals' => Merge::byKey([
'before' => Merge::after('csrf', ['auth']),
'after' => Merge::prepend(['honeypot']),
]),
// Property-root list ordering.
'list' => Merge::before('a', ['z']),
];
}
}
30 changes: 30 additions & 0 deletions tests/_support/Config/MergePlainRegistrar.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace Tests\Support\Config;

/**
* Plain-array registrar (no directives) used to assert the legacy shallow
* merge behavior is unchanged — nested siblings are dropped.
*/
class MergePlainRegistrar
{
public static function MergeRegistrarConfig(): array
{
return [
'arrayNested' => [
'key2' => ['val4' => 'subVal4'],
],
];
}
}
Loading
Loading