Skip to content

Commit

Permalink
Cached config loader.
Browse files Browse the repository at this point in the history
  • Loading branch information
nikolaposa committed Feb 26, 2017
1 parent 60ef51d commit 780387b
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 1 deletion.
5 changes: 5 additions & 0 deletions src/Config/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,9 @@ public static function fromArray(array $config)
{
return new self($config);
}

public function toArray() : array
{
return $this->getArrayCopy();
}
}
28 changes: 27 additions & 1 deletion src/Config/Loader/CachingConfigLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,34 @@
*/
final class CachingConfigLoader implements ConfigLoaderInterface
{
/**
* @var ConfigLoaderInterface
*/
private $configLoader;

/**
* @var string
*/
private $cachedConfigFile;

public function __construct(ConfigLoaderInterface $configLoader, string $cachedConfigFile)
{
$this->configLoader = $configLoader;
$this->cachedConfigFile = $cachedConfigFile;
}

public function __invoke() : Config
{
// TODO: Implement __invoke() method.
if (is_file($this->cachedConfigFile)) {
return Config::fromArray(include $this->cachedConfigFile);
}

$configLoader = $this->configLoader;
/* @var $config Config */
$config = $configLoader();

file_put_contents($this->cachedConfigFile, '<?php return ' . var_export($config->toArray(), true) . ';');

return $config;
}
}
12 changes: 12 additions & 0 deletions tests/Config/ConfigTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,16 @@ public function it_can_accessed_using_array_notation()

$this->assertEquals('pdo_mysql', $config['db']['driver']);
}

/**
* @test
*/
public function it_can_converted_to_array()
{
$config = Config::fromArray([
'foo' => 'bar',
]);

$this->assertEquals(['foo' => 'bar'], $config->toArray());
}
}

0 comments on commit 780387b

Please sign in to comment.