1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\PersonalDataDownload\Jobs; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Facades\Mail; |
6
|
|
|
use Spatie\PersonalDataDownload\Exceptions\InvalidUser; |
7
|
|
|
use Spatie\PersonalDataDownload\Zip; |
8
|
|
|
use Illuminate\Database\Eloquent\Model; |
9
|
|
|
use Illuminate\Support\Facades\Storage; |
10
|
|
|
use Illuminate\Contracts\Queue\ShouldQueue; |
11
|
|
|
use Spatie\PersonalDataDownload\PersonalData; |
12
|
|
|
use Illuminate\Contracts\Filesystem\Filesystem; |
13
|
|
|
use Spatie\TemporaryDirectory\TemporaryDirectory; |
14
|
|
|
|
15
|
|
|
class CreatePersonalDataDownloadJob implements ShouldQueue |
16
|
|
|
{ |
17
|
|
|
/** @var \Illuminate\Database\Eloquent\Model */ |
18
|
|
|
protected $user; |
19
|
|
|
|
20
|
|
|
public function __construct(Model $user) |
21
|
|
|
{ |
22
|
|
|
$this->ensureValidUser($user); |
23
|
|
|
|
24
|
|
|
$this->user = $user; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function handle() |
28
|
|
|
{ |
29
|
|
|
$temporaryDirectory = (new TemporaryDirectory())->create(); |
30
|
|
|
|
31
|
|
|
$personalData = (new PersonalData($temporaryDirectory))->forUser($this->user); |
32
|
|
|
|
33
|
|
|
$this->user->selectPersonalData($personalData); |
34
|
|
|
|
35
|
|
|
$zipFilename = $this->zipPersonalData($personalData, $this->getDisk(), $temporaryDirectory); |
36
|
|
|
|
37
|
|
|
$temporaryDirectory->delete(); |
38
|
|
|
|
39
|
|
|
$this->mailZip($zipFilename); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
protected function selectPersonalData(TemporaryDirectory $temporaryDirectory): PersonalData |
43
|
|
|
{ |
44
|
|
|
$personalData = new PersonalData($temporaryDirectory); |
45
|
|
|
|
46
|
|
|
$this->user->selectPersonalData($personalData); |
47
|
|
|
|
48
|
|
|
return $personalData; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
protected function zipPersonalData( |
52
|
|
|
PersonalData $personalData, |
53
|
|
|
Filesystem $filesystem, |
54
|
|
|
TemporaryDirectory $temporaryDirectory |
55
|
|
|
): string { |
56
|
|
|
$zip = Zip::createForPersonalData($personalData, $temporaryDirectory); |
57
|
|
|
|
58
|
|
|
$zipFilename = pathinfo($zip->path(), PATHINFO_BASENAME); |
59
|
|
|
|
60
|
|
|
$filesystem->writeStream($zipFilename, fopen($zip->path(), 'r')); |
61
|
|
|
|
62
|
|
|
return $zipFilename; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
public function getDisk(): Filesystem |
66
|
|
|
{ |
67
|
|
|
return Storage::disk(config('personal-data-download.disk')); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
protected function mailZip(string $zipFilename) |
71
|
|
|
{ |
72
|
|
|
$mailableClass = config('personal-data-download.mailable'); |
73
|
|
|
|
74
|
|
|
Mail::to($this->user)->send(new $mailableClass($zipFilename)); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
protected function ensureValidUser(Model $user) |
78
|
|
|
{ |
79
|
|
|
if (! method_exists($user, 'selectPersonalData')) { |
80
|
|
|
throw InvalidUser::doesNotHaveSelectPersonalDataMethod($user); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|