Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

ModelCacheManager.php 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace App\Utilities;
  3. use Closure;
  4. use Illuminate\Support\Facades\{Cache, Log};
  5. class ModelCacheManager
  6. {
  7. public static function cacheData(string $csv, string $cacheKey, ?Closure $transformer = null, $expiration = null): void
  8. {
  9. $expiration = $expiration ?? now()->addDays(1);
  10. Cache::remember($cacheKey, $expiration, static function () use ($csv, $transformer) {
  11. $dataCollection = collect();
  12. $handle = fopen($csv, 'rb');
  13. if (! $handle) {
  14. Log::error("Could not open CSV file at path: {$csv}");
  15. return $dataCollection;
  16. }
  17. $headers = fgetcsv($handle);
  18. if (! $headers) {
  19. Log::error("CSV file headers could not be read from path: {$csv}");
  20. fclose($handle);
  21. return $dataCollection;
  22. }
  23. while (($row = fgetcsv($handle)) !== false) {
  24. $rowData = array_combine($headers, $row);
  25. // Decode JSON 'timezones' field before storing
  26. if (isset($rowData['timezones'])) {
  27. $rowData['timezones'] = json_decode($rowData['timezones'], true);
  28. }
  29. if ($transformer) {
  30. $rowData = $transformer($rowData);
  31. }
  32. $dataCollection->push($rowData);
  33. }
  34. fclose($handle);
  35. return $dataCollection;
  36. });
  37. }
  38. }