Skip to content

Commit 466722e

Browse files
committed
[config] Add new MutableConfig
This is to make it easier to override config values at runtime Mainly created to make it easier to change configs in tests
1 parent b6f0c7c commit 466722e

File tree

2 files changed

+92
-0
lines changed

2 files changed

+92
-0
lines changed

src/MutableConfig.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace Stefna\Config;
4+
5+
final class MutableConfig implements Config
6+
{
7+
use GetConfigTrait;
8+
9+
/** @var array<string, mixed> */
10+
private array $config = [];
11+
12+
public function __construct(
13+
private readonly Config $rootConfig,
14+
) {}
15+
16+
public function getRawValue(string $key): mixed
17+
{
18+
if (isset($this->config[$key])) {
19+
return $this->config[$key];
20+
}
21+
return $this->rootConfig->get($key);
22+
}
23+
24+
public function setConfigValue(string $key, mixed $value): void
25+
{
26+
$this->config[$key] = $value;
27+
}
28+
29+
public function resetConfigValue(string $key): void
30+
{
31+
unset($this->config[$key]);
32+
}
33+
}

tests/MutableConfigTest.php

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace Stefna\Config\Tests;
4+
5+
use PHPUnit\Framework\TestCase;
6+
use Stefna\Config\ArrayConfig;
7+
use Stefna\Config\MutableConfig;
8+
use Stefna\Config\Tests\Stub\TestStub;
9+
10+
final class MutableConfigTest extends AbstractConfigTestCase
11+
{
12+
public function testOverrideValue(): void
13+
{
14+
$config = $this->getConfig();
15+
$key = 'testString';
16+
$originalValue = $config->get($key);
17+
$newValue = 'overrideValue';
18+
19+
$config->setConfigValue($key, $newValue);
20+
21+
$this->assertNotSame($originalValue, $newValue);
22+
$this->assertSame($newValue, $config->getString($key));
23+
}
24+
25+
public function testOverrideDotKeyValues(): void
26+
{
27+
$config = $this->getConfig();
28+
$key = 'deep.nesting.int';
29+
$originalValue = $config->get($key);
30+
$newValue = 42;
31+
32+
$config->setConfigValue($key, $newValue);
33+
34+
$this->assertNotSame($originalValue, $newValue);
35+
$this->assertSame($newValue, $config->getInt($key));
36+
}
37+
38+
public function testOverrideTestValue(): void
39+
{
40+
$config = $this->getConfig();
41+
$key = 'nesting.test';
42+
$originalValue = $config->get($key);
43+
$newValue = 'overrideValue';
44+
45+
$config->setConfigValue($key, $newValue);
46+
47+
$this->assertNotSame($originalValue, $newValue);
48+
$this->assertSame($newValue, $config->get($key));
49+
50+
$config->resetConfigValue($key);
51+
52+
$this->assertSame($originalValue, $config->get($key));
53+
}
54+
55+
public function getConfig(): MutableConfig
56+
{
57+
return new MutableConfig($this->getDefaultArrayConfig());
58+
}
59+
}

0 commit comments

Comments
 (0)