. */ declare(strict_types=1); namespace FireflyIII\Console\Commands\Upgrade; use FireflyIII\Console\Commands\ShowsFriendlyMessages; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Attachment; use FireflyIII\Models\Note; use Illuminate\Console\Command; use Illuminate\Support\Facades\Log; use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; /** * Class MigrateAttachments */ class MigrateAttachments extends Command { use ShowsFriendlyMessages; public const CONFIG_NAME = '480_migrate_attachments'; /** * The console command description. * * @var string */ protected $description = 'Migrates attachment meta-data.'; /** * The name and signature of the console command. * * @var string */ protected $signature = 'firefly-iii:migrate-attachments {--F|force : Force the execution of this command.}'; /** * Execute the console command. * * @return int * @throws ContainerExceptionInterface * @throws FireflyException * @throws NotFoundExceptionInterface */ public function handle(): int { $start = microtime(true); if ($this->isExecuted() && true !== $this->option('force')) { $this->friendlyInfo('This command has already been executed.'); return 0; } $attachments = Attachment::get(); $count = 0; /** @var Attachment $att */ foreach ($attachments as $att) { // move description: $attDescription = (string)$att->description; if ('' !== $attDescription) { // find or create note: $note = $att->notes()->first(); if (null === $note) { $note = new Note(); $note->noteable()->associate($att); } $note->text = $attDescription; $note->save(); // clear description: $att->description = ''; $att->save(); Log::debug(sprintf('Migrated attachment #%s description to note #%d.', $att->id, $note->id)); $count++; } } if (0 === $count) { $this->friendlyPositive('All attachments are OK.'); } if (0 !== $count) { $this->friendlyInfo(sprintf('Updated %d attachment(s).', $count)); } $end = round(microtime(true) - $start, 2); $this->friendlyInfo(sprintf('Migrated attachment notes in %s seconds.', $end)); $this->markAsExecuted(); return 0; } /** * @return bool * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface */ private function isExecuted(): bool { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { return (bool)$configVar->data; } return false; } /** * */ private function markAsExecuted(): void { app('fireflyconfig')->set(self::CONFIG_NAME, true); } }