From de49318bc69404408662f8a6175650d9b1be28a1 Mon Sep 17 00:00:00 2001 From: Pig Fang Date: Thu, 22 Aug 2019 09:19:58 +0800 Subject: [PATCH] Read options from cache if exists --- app/Services/Option.php | 9 ++++++++- tests/ServicesTest/OptionTest.php | 26 +++++++++++++++++++------- 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/app/Services/Option.php b/app/Services/Option.php index d2a863e4..d7af6b93 100644 --- a/app/Services/Option.php +++ b/app/Services/Option.php @@ -4,14 +4,21 @@ namespace App\Services; use DB; use Illuminate\Support\Arr; +use Illuminate\Filesystem\Filesystem; use Illuminate\Database\QueryException; class Option { protected $items; - public function __construct() + public function __construct(Filesystem $filesystem) { + $cachePath = storage_path('options/cache.php'); + if ($filesystem->exists($cachePath)) { + $this->items = collect($filesystem->getRequire($cachePath)); + return; + } + try { $this->items = DB::table('options')->get()->mapWithKeys(function ($item) { return [$item->option_name => $item->option_value]; diff --git a/tests/ServicesTest/OptionTest.php b/tests/ServicesTest/OptionTest.php index 1361a4d8..6dc052f2 100644 --- a/tests/ServicesTest/OptionTest.php +++ b/tests/ServicesTest/OptionTest.php @@ -11,20 +11,32 @@ class OptionTest extends TestCase public function testGet() { - $repo = new Option(); - $repo->set('k1', '(null)'); - $this->assertNull($repo->get('k1')); + $options = resolve(Option::class); + $options->set('k1', '(null)'); + $this->assertNull($options->get('k1')); $this->assertNull(option()->get('k1')); } public function testSet() { - $repo = new Option(); - $repo->set([ + $options = resolve(Option::class); + $options->set([ 'k1' => 'v1', 'k2' => 'v2', ]); - $this->assertEquals('v1', $repo->get('k1')); - $this->assertEquals('v2', $repo->get('k2')); + $this->assertEquals('v1', $options->get('k1')); + $this->assertEquals('v2', $options->get('k2')); + } + + public function testReadFromCache() + { + $this->mock(\Illuminate\Filesystem\Filesystem::class, function ($mock) { + $path = storage_path('options/cache.php'); + $mock->shouldReceive('exists')->with($path)->once()->andReturn(true); + $mock->shouldReceive('getRequire')->with($path)->once()->andReturn(['k' => 'v']); + }); + + $options = resolve(Option::class); + $this->assertEquals('v', $options->get('k')); } }