1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Service\enso\avatars; |
4
|
|
|
|
5
|
|
|
use Illuminate\Http\File; |
6
|
|
|
use Illuminate\Support\Collection; |
7
|
|
|
use Illuminate\Support\Facades\DB; |
8
|
|
|
use Illuminate\Support\Facades\Storage; |
9
|
|
|
use Illuminate\Support\Str; |
10
|
|
|
use App\Models\enso\Avatars\Avatar; |
11
|
|
|
use App\Models\User; |
12
|
|
|
use Laravolt\Avatar\Facade as Service; |
13
|
|
|
|
14
|
|
|
class DefaultAvatar |
15
|
|
|
{ |
16
|
|
|
private const Filename = 'avatar'; |
17
|
|
|
private const Extension = 'jpg'; |
18
|
|
|
private const FontSize = 128; |
19
|
|
|
|
20
|
|
|
private $user; |
21
|
|
|
private $avatar; |
22
|
|
|
private $filePath; |
23
|
|
|
|
24
|
|
|
public function __construct(User $user) |
25
|
|
|
{ |
26
|
|
|
$this->user = $user; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function create() |
30
|
|
|
{ |
31
|
|
|
DB::transaction(fn () => $this->findOrCreate() |
32
|
|
|
->generate() |
33
|
|
|
->attach()); |
34
|
|
|
|
35
|
|
|
return $this->avatar; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
private function findOrCreate(): self |
39
|
|
|
{ |
40
|
|
|
$this->avatar = $this->user->avatar() |
41
|
|
|
->firstOrCreate(['user_id' => $this->user->id]); |
42
|
|
|
|
43
|
|
|
return $this; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
private function generate(): self |
47
|
|
|
{ |
48
|
|
|
Service::create($this->user->person->name) |
|
|
|
|
49
|
|
|
->setDimension(Avatar::Width, Avatar::Height) |
50
|
|
|
->setFontSize(self::FontSize) |
51
|
|
|
->setBackground($this->background()) |
52
|
|
|
->save($this->filePath()); |
53
|
|
|
|
54
|
|
|
return $this; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
private function attach(): void |
58
|
|
|
{ |
59
|
|
|
$avatar = new File($this->filePath()); |
60
|
|
|
|
61
|
|
|
$this->avatar->attach($avatar, $this->originalName(), $this->user); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
private function originalName(): string |
65
|
|
|
{ |
66
|
|
|
return self::Filename.$this->user->id.'.'.self::Extension; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
private function hashName(): string |
70
|
|
|
{ |
71
|
|
|
return Str::random(40).'.'.self::Extension; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
private function filePath(): string |
75
|
|
|
{ |
76
|
|
|
return $this->filePath ??= Storage::path( |
77
|
|
|
$this->avatar->folder().DIRECTORY_SEPARATOR.$this->hashName() |
78
|
|
|
); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
private function background(): string |
82
|
|
|
{ |
83
|
|
|
return (new Collection( |
84
|
|
|
config('laravolt.avatar.backgrounds') |
85
|
|
|
))->random(); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|
Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.