"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",
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);
+ }
+
}