Issues (368)

src/Files/ArboryFileFactory.php (1 issue)

Severity
1
<?php
2
3
namespace Arbory\Base\Files;
4
5
use Illuminate\Http\UploadedFile;
6
use Illuminate\Database\Eloquent\Model;
7
use Arbory\Base\Repositories\ArboryFilesRepository;
8
use Illuminate\Database\Eloquent\Relations\BelongsTo;
9
10
class ArboryFileFactory
11
{
12
    /**
13
     * @var ArboryFilesRepository
14
     */
15
    private $repository;
16
17
    /**
18
     * @param  ArboryFilesRepository  $repository
19
     */
20
    public function __construct(ArboryFilesRepository $repository)
21
    {
22
        $this->repository = $repository;
23
    }
24
25
    /**
26
     * @param  Model  $model
27
     * @param  UploadedFile|ArboryFile  $file
28
     * @param  string  $relationName
29
     * @return ArboryFile
30
     *
31
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
32
     * @throws \InvalidArgumentException
33
     * @throws \RuntimeException
34
     */
35
    public function make(Model $model, $file, string $relationName)
36
    {
37
        $arboryFile = $this->writeFile($model, $file);
38
        $relation = $model->{$relationName}();
39
40
        if (! $relation instanceof BelongsTo) {
41
            throw new \InvalidArgumentException('Unsupported relation');
42
        }
43
44
        $localKey = explode('.', $relation->getQualifiedForeignKeyName())[1];
45
46
        $model->setAttribute($localKey, $arboryFile->getKey());
47
        $model->setRelation($relationName, $arboryFile);
48
        $model->save();
49
50
        return $arboryFile;
51
    }
52
53
    /**
54
     * @param  Model  $model
55
     * @param  UploadedFile|ArboryFile  $file
56
     * @return ArboryFile|null
57
     *
58
     * @throws \InvalidArgumentException
59
     * @throws \RuntimeException
60
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
61
     */
62
    private function writeFile(Model $model, $file)
63
    {
64
        $arboryFile = null;
65
66
        if ($file instanceof UploadedFile) {
67
            $arboryFile = $this->repository->createFromUploadedFile($file, $model);
68
        } elseif ($file instanceof ArboryFile) {
0 ignored issues
show
$file is always a sub-type of Arbory\Base\Files\ArboryFile.
Loading history...
69
            $contents = $this->repository->getDisk()->get($file->getLocalName());
70
            $arboryFile = $this->repository->createFromBlob($file->getLocalName(), $contents, $model);
71
        } else {
72
            throw new \InvalidArgumentException('Invalid file source');
73
        }
74
75
        return $arboryFile;
76
    }
77
}
78