From 21d416671a075ed6fb636192abbc8b9a8f088c82 Mon Sep 17 00:00:00 2001 From: Pig Fang Date: Sun, 8 Sep 2019 09:19:32 +0800 Subject: [PATCH] Tweak cache policy of parsing YAML --- app/Services/Translations/Yaml.php | 20 +++++++++---- .../TranslationsTest/YamlTest.php | 29 +++++++++++++++++++ 2 files changed, 44 insertions(+), 5 deletions(-) create mode 100644 tests/ServicesTest/TranslationsTest/YamlTest.php diff --git a/app/Services/Translations/Yaml.php b/app/Services/Translations/Yaml.php index bc6cc9d4..de2b0c11 100644 --- a/app/Services/Translations/Yaml.php +++ b/app/Services/Translations/Yaml.php @@ -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', []); } } diff --git a/tests/ServicesTest/TranslationsTest/YamlTest.php b/tests/ServicesTest/TranslationsTest/YamlTest.php new file mode 100644 index 00000000..43a073a2 --- /dev/null +++ b/tests/ServicesTest/TranslationsTest/YamlTest.php @@ -0,0 +1,29 @@ +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); + } +}