Tweak cache policy of parsing YAML
This commit is contained in:
parent
5718567bea
commit
21d416671a
@ -10,17 +10,27 @@ class Yaml
|
||||
/** @var Repository */
|
||||
protected $cache;
|
||||
|
||||
protected $prefix = 'yaml-trans-';
|
||||
|
||||
public function __construct(Repository $cache)
|
||||
{
|
||||
$this->cache = $cache;
|
||||
}
|
||||
|
||||
public function parse(string $path): array
|
||||
public function parse(string $path)
|
||||
{
|
||||
$key = 'yaml-trans-'.md5($path).'-'.filemtime($path);
|
||||
$prefix = $this->prefix.md5($path).'-';
|
||||
$cacheTime = intval($this->cache->get($prefix.'time', 0));
|
||||
$fileTime = filemtime($path);
|
||||
|
||||
return $this->cache->rememberForever($key, function () use ($path) {
|
||||
return YamlParser::parseFile($path);
|
||||
});
|
||||
if ($fileTime > $cacheTime) {
|
||||
$content = YamlParser::parseFile($path);
|
||||
$this->cache->put($prefix.'content', $content);
|
||||
$this->cache->put($prefix.'time', $fileTime);
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
return $this->cache->get($prefix.'content', []);
|
||||
}
|
||||
}
|
||||
|
29
tests/ServicesTest/TranslationsTest/YamlTest.php
Normal file
29
tests/ServicesTest/TranslationsTest/YamlTest.php
Normal file
@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace Tests;
|
||||
|
||||
use App\Services\Translations\Yaml;
|
||||
use Illuminate\Contracts\Cache\Repository;
|
||||
|
||||
class YamlTest extends TestCase
|
||||
{
|
||||
public function testParse()
|
||||
{
|
||||
$path = resource_path('lang/en/general.yml');
|
||||
$prefix = 'yaml-trans-'.md5($path).'-';
|
||||
$this->mock(Repository::class, function ($mock) use ($prefix, $path) {
|
||||
$mock->shouldReceive('get')
|
||||
->with($prefix.'time', 0)
|
||||
->twice()
|
||||
->andReturn(0, filemtime($path) + 100000);
|
||||
$mock->shouldReceive('put')->twice();
|
||||
$mock->shouldReceive('get')
|
||||
->with($prefix.'content', [])
|
||||
->once()
|
||||
->andReturn([]);
|
||||
});
|
||||
|
||||
$this->app->make(Yaml::class)->parse($path);
|
||||
$this->app->make(Yaml::class)->parse($path);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user