. */ declare(strict_types=1); namespace FireflyIII\Factory; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Attachment; use FireflyIII\Models\Note; use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionJournal; use FireflyIII\User; /** * Class AttachmentFactory */ class AttachmentFactory { private User $user; /** * @param array $data * * @return Attachment|null * @throws FireflyException */ public function create(array $data): ?Attachment { // append if necessary. $model = !str_contains($data['attachable_type'], 'FireflyIII') ? sprintf('FireflyIII\\Models\\%s', $data['attachable_type']) : $data['attachable_type']; // get journal instead of transaction. if (Transaction::class === $model) { /** @var Transaction|null $transaction */ $transaction = $this->user->transactions()->find((int)$data['attachable_id']); if (null === $transaction) { throw new FireflyException('Unexpectedly could not find transaction'); } $data['attachable_id'] = $transaction->transaction_journal_id; $model = TransactionJournal::class; } // create attachment: $attachment = Attachment::create( [ 'user_id' => $this->user->id, 'attachable_id' => $data['attachable_id'], 'attachable_type' => $model, 'md5' => '', 'filename' => $data['filename'], 'title' => '' === $data['title'] ? null : $data['title'], 'description' => null, 'mime' => '', 'size' => 0, 'uploaded' => 0, ] ); $notes = (string)($data['notes'] ?? ''); if ('' !== $notes) { $note = new Note(); $note->noteable()->associate($attachment); $note->text = $notes; $note->save(); } return $attachment; } /** * @param User $user */ public function setUser(User $user): void { $this->user = $user; } }