Skip to content

Instantly share code, notes, and snippets.

@Kovah
Last active December 4, 2024 08:15
Show Gist options
  • Save Kovah/834fef5d25b06aed6ae0ad087e6fd6ff to your computer and use it in GitHub Desktop.
Save Kovah/834fef5d25b06aed6ae0ad087e6fd6ff to your computer and use it in GitHub Desktop.
Health Dashboard: Import Job
<?php
namespace App\Modules\AppleHealth\Jobs;
use App\Modules\AppleHealth\Models\HealthMetric; // @see https://gist.github.com/Kovah/3f3ce850f90f9070784f30d6915893da
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
class ProcessImportJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(private readonly int $userId, private readonly string $file)
{
}
public function handle()
{
ini_set('precision', 17);
// $this->file equals something like 'metrics/HealthAutoExport-2024-11-25.json'
$fileContent = Storage::disk('local_applehealth')->get($this->file);
$data = json_decode($fileContent, associative: false, flags: JSON_THROW_ON_ERROR);
try {
$this->processMetrics($data->data);
} catch (Exception $e) {
Log::error($e->getMessage());
return;
}
}
protected function processMetrics(object $data): void
{
foreach ($data->metrics as $metric) {
if (empty($metric->data)) {
continue;
}
$newEntries = collect();
foreach ($metric->data as $entry) {
// Export Health Format: 2022-08-18 08:50:00 +0200
$date = Carbon::createFromFormat('Y-m-d H:i:s O', $entry->date)->setTimezone('UTC');
// properly store sleep analysis data, which consists of array data
if ($metric->name === 'sleep_analysis') {
unset($entry->date);
$newEntries->push([
'user_id' => $this->userId,
'name' => $metric->name,
'value' => json_encode($entry),
'date' => $date,
]);
continue;
}
$newEntries->push([
'user_id' => $this->userId,
'name' => $metric->name,
'value' => (string)($entry->qty ?? $entry->Avg),
'date' => $date,
]);
}
// Update or create entries, unique columns are user_id, name and date
HealthMetric::upsert($newEntries->toArray(), ['user_id', 'name', 'date'], ['value']);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment