yoeriboven's avatar

Removing a config entry for a test

I'm adding a feature to an existing package which will add a new config key/value. Current users don't have this item since this record doesn't exist yet.

To make sure this is not a breaking change I want to test the package when the record is not set.

app('config')->set('shield.enabled', null); sets the enabled key in the shield config file to null but doesn't remove the key from the config entirely, it only changes the value.

How do I unset a config record?

0 likes
2 replies
Sti3bas's avatar
Sti3bas
Best Answer
Level 53

@yoeriboven it seems like there is no built-in way to do this, but you can easily extend Illuminate\Config\Repository class and add unset method which modifies protected $items property where all config values are stored:

use Illuminate\Config\Repository;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Config;
use Tests\TestCase;

class ConfigTest extends TestCase
{
    /** @test */
    public function unset_key()
    {
        app()->instance('config', new class extends Repository {
            public function unset($key)
            {
                Arr::forget($this->items, $key);
            }
        });

        $this->assertFalse(Config::has('test'));

        Config::set('test', 'test');

        $this->assertTrue(Config::has('test'));
        
        Config::set('test', null);
        
        $this->assertTrue(Config::has('test'));
        
        Config::unset('test');

        $this->assertFalse(Config::has('test'));
    }
}

PHPUnit 8.5.2 by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

Time: 181 ms, Memory: 16.00 MB

OK (1 test, 4 assertions)
2 likes

Please or to participate in this conversation.