From: Vincent Vanwaelscappel Date: Wed, 15 Feb 2023 08:33:58 +0000 (+0100) Subject: wip #5718 @0.5 X-Git-Url: http://git.cubedesigners.com/?a=commitdiff_plain;h=2395517dddc2b4b8e8da486c01985d8d6f9f5778;p=cubist_cms-back.git wip #5718 @0.5 --- diff --git a/composer.json b/composer.json index 6d456b7..6778e0c 100644 --- a/composer.json +++ b/composer.json @@ -53,8 +53,7 @@ "laravel/framework": "^v8.83.27", "laravel-lang/lang": "^10.9", "laravel-lang/publisher": "^10.3", - "spatie/laravel-permission": "^4.4|^5.8", - "calebporzio/sushi": "^2.4" + "spatie/laravel-permission": "^4.4|^5.8" }, "require-dev": { "filp/whoops": "^2.14", diff --git a/src/app/Magic/Traits/CustomDataSource.php b/src/app/Magic/Traits/CustomDataSource.php index 1c01e13..9d0581b 100644 --- a/src/app/Magic/Traits/CustomDataSource.php +++ b/src/app/Magic/Traits/CustomDataSource.php @@ -2,7 +2,77 @@ namespace Cubist\Backpack\Magic\Traits; +use Illuminate\Support\Facades\Cache; +use Illuminate\Support\Facades\Log; + trait CustomDataSource { + public static function bootCustomDataSource() + { + $instance = (new static); + if ($instance->shouldRefreshDatabase()) { + $instance->refreshDatabase(); + } + } + + /** + * @return array[] + */ + public function getData() + { + return []; + } + + public function refreshDatabase() + { + $hadError = false; + foreach (array_chunk($this->getData(), $this->getInsertChunkSize()) ?? [] as $inserts) { + if (!empty($inserts)) { + try { + static::insert($inserts); + } catch (\Exception $e) { + $hadError = true; + Log::error($e); + break; + } + } + } + Cache::put($this->getCacheKey() . '_refresh', $hadError ? -1 : time()); + } + + public function getInsertChunkSize() + { + return 100; + } + + public function shouldRefreshDatabase() + { + $lastDatabaseRefresh = Cache::get($this->getCacheKey() . '_refresh', -1); + return $lastDatabaseRefresh < $this->getDataLastChange(); + } + + public function getDataLastChange() + { + $file = $this->getDataLastChangeFile(); + if ($file === '') { + return 0; + } + if (!file_exists($file)) { + touch($file); + } + return filemtime($file); + } + + public function getDataLastChangeFile() + { + return ''; + } + + + public function getCacheKey() + { + return 'custom_data_source_' . get_class($this); + } + }