Tweak cache policy of parsing YAML

This commit is contained in:
Pig Fang 2019-09-08 09:19:32 +08:00
parent 5718567bea
commit 21d416671a
2 changed files with 44 additions and 5 deletions

View File

@ -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', []);
}
}

View 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);
}
}