/
PersonalDataSelection.php
98 lines (71 loc) · 2.53 KB
/
PersonalDataSelection.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
namespace Spatie\PersonalDataExport;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Facades\Storage;
use Spatie\TemporaryDirectory\TemporaryDirectory;
use Spatie\PersonalDataExport\Exceptions\CouldNotAddToPersonalDataSelection;
class PersonalDataSelection
{
/** @var \Spatie\TemporaryDirectory\TemporaryDirectory */
protected $temporaryDirectory;
/** @var array */
protected $files = [];
/** @var \Illuminate\Database\Eloquent\Model */
public $user;
public function __construct(TemporaryDirectory $temporaryDirectory)
{
$this->temporaryDirectory = $temporaryDirectory;
}
public function files(): array
{
return $this->files;
}
public function forUser(ExportsPersonalData $user)
{
$this->user = $user;
return $this;
}
/**
* @param string $nameInDownload
* @param array|string $content
*/
public function add(string $nameInDownload, $content)
{
if (! is_string($content)) {
$content = json_encode($content);
}
$path = $this->temporaryDirectory->path($nameInDownload);
$this->ensureDoesNotOverwriteExistingFile($path);
$this->files[] = $path;
file_put_contents($path, $content);
}
public function addFile(string $pathToFile, string $diskName = null)
{
return is_null($diskName)
? $this->copyLocalFile($pathToFile)
: $this->copyFileFromDisk($pathToFile, $diskName);
}
protected function copyLocalFile(string $pathToFile)
{
$fileName = pathinfo($pathToFile, PATHINFO_BASENAME);
$destination = $this->temporaryDirectory->path($fileName);
$this->ensureDoesNotOverwriteExistingFile($destination);
(new Filesystem())->copy($pathToFile, $destination);
$this->files[] = $destination;
return $this;
}
protected function copyFileFromDisk(string $pathOnDisk, string $diskName)
{
$stream = Storage::disk($diskName)->readStream($pathOnDisk);
$pathInTemporaryDirectory = $this->temporaryDirectory->path($pathOnDisk);
$this->ensureDoesNotOverwriteExistingFile($pathInTemporaryDirectory);
file_put_contents($pathInTemporaryDirectory, stream_get_contents($stream), FILE_APPEND);
return $this;
}
protected function ensureDoesNotOverwriteExistingFile(string $path)
{
if (file_exists($path)) {
throw CouldNotAddToPersonalDataSelection::fileAlreadyAddedToPersonalDataSelection($path);
}
}
}