Completed
Push — master ( b4f9ef...be3a9a )
by Freek
01:46
created

PersonalData::copyLocalFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Spatie\PersonalDataDownload;
4
5
use Illuminate\Filesystem\Filesystem;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Support\Facades\Storage;
8
use Spatie\TemporaryDirectory\TemporaryDirectory;
9
10
class PersonalData
11
{
12
    /** @var \Spatie\TemporaryDirectory\TemporaryDirectory */
13
    protected $temporaryDirectory;
14
15
    /** @var array */
16
    protected $files = [];
17
18
    /** @var \Illuminate\Database\Eloquent\Model */
19
    public $user;
20
21
    public function __construct(TemporaryDirectory $temporaryDirectory)
22
    {
23
        $this->temporaryDirectory = $temporaryDirectory;
24
    }
25
26
    public function forUser(Model $user)
27
    {
28
        $this->user = $user;
29
30
        return $this;
31
    }
32
33
    /**
34
     * @param string $nameInDownload
35
     * @param array|string $content
36
     */
37
    public function addContent(string $nameInDownload, $content)
38
    {
39
        if (! is_string($content)) {
40
            $content = json_encode($content);
41
        }
42
43
        $path = $this->temporaryDirectory->path($nameInDownload);
44
45
        $this->files[] = $path;
46
47
        file_put_contents($path, $content);
48
    }
49
50
    public function addFile(string $pathToFile, string $diskName = null)
51
    {
52
        return is_null($diskName)
53
            ? $this->copyLocalFile($pathToFile)
54
            : $this->copyFileFromDisk($pathToFile, $diskName);
55
    }
56
57
    public function files(): array
58
    {
59
        return $this->files;
60
    }
61
62
    protected function copyLocalFile(string $pathToFile)
63
    {
64
        $fileName = pathinfo($pathToFile, PATHINFO_BASENAME);
65
66
        $destination = $this->temporaryDirectory->path($fileName);
67
68
        (new Filesystem())->copy($pathToFile, $destination);
69
70
        $this->files[] = $destination;
71
72
        return $this;
73
    }
74
75
    protected function copyFileFromDisk(string $pathOnDisk, string $diskName)
76
    {
77
        $stream = Storage::disk($diskName)->readStream($pathOnDisk);
78
79
        $pathInTemporaryDirectory = $this->temporaryDirectory->path($pathOnDisk);
80
81
        file_put_contents($pathInTemporaryDirectory, stream_get_contents($stream), FILE_APPEND);
82
83
        return $this;
84
    }
85
}
86