/
AvatarUploader.php
59 lines (46 loc) · 1.27 KB
/
AvatarUploader.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
<?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\User;
use Illuminate\Support\Str;
use Intervention\Image\Image;
use League\Flysystem\FilesystemInterface;
class AvatarUploader
{
protected $uploadDir;
public function __construct(FilesystemInterface $uploadDir)
{
$this->uploadDir = $uploadDir;
}
/**
* @param User $user
* @param Image $image
*/
public function upload(User $user, Image $image)
{
if (extension_loaded('exif')) {
$image->orientate();
}
$encodedImage = $image->fit(100, 100)->encode('png');
$avatarPath = Str::random().'.png';
$this->remove($user);
$user->changeAvatarPath($avatarPath);
$this->uploadDir->put($avatarPath, $encodedImage);
}
public function remove(User $user)
{
$avatarPath = $user->avatar_path;
$user->afterSave(function () use ($avatarPath) {
if ($this->uploadDir->has($avatarPath)) {
$this->uploadDir->delete($avatarPath);
}
});
$user->changeAvatarPath(null);
}
}