Add simple implementation (command handler) for avatar upload.

This commit is contained in:
Franz Liedke 2015-03-25 14:23:31 +01:00
parent 7f66a77ede
commit a1f723671d
3 changed files with 105 additions and 0 deletions

View File

@ -0,0 +1,30 @@
<?php namespace Flarum\Core\Commands;
use RuntimeException;
class UploadAvatarCommand
{
public $userId;
/**
* @var \Symfony\Component\HttpFoundation\File\UploadedFile
*/
public $file;
public $actor;
public function __construct($userId, $file, $actor)
{
if (empty($userId) || !intval($userId)) {
throw new RuntimeException('No valid user ID specified.');
}
if (is_null($file)) {
throw new RuntimeException('No file to upload');
}
$this->userId = $userId;
$this->file = $file;
$this->actor = $actor;
}
}

View File

@ -0,0 +1,16 @@
<?php namespace Flarum\Core\Events;
use Flarum\Core\Models\User;
class AvatarWillBeUploaded
{
public $user;
public $command;
public function __construct(User $user, $command)
{
$this->user = $user;
$this->command = $command;
}
}

View File

@ -0,0 +1,59 @@
<?php namespace Flarum\Core\Handlers\Commands;
use Flarum\Core\Commands\UploadAvatarCommand;
use Flarum\Core\Events\AvatarWillBeUploaded;
use Flarum\Core\Repositories\UserRepositoryInterface;
use Flarum\Core\Support\DispatchesEvents;
use Illuminate\Support\Str;
use League\Flysystem\Adapter\Local;
use League\Flysystem\FilesystemInterface;
use League\Flysystem\MountManager;
class UploadAvatarCommandHandler
{
use DispatchesEvents;
/**
* @var UserRepositoryInterface
*/
protected $users;
/**
* @var FilesystemInterface
*/
protected $uploadDir;
public function __construct(UserRepositoryInterface $users, FilesystemInterface $uploadDir)
{
$this->users = $users;
$this->uploadDir = $uploadDir;
}
public function handle(UploadAvatarCommand $command)
{
$user = $this->users->findOrFail($command->userId);
// Make sure the current user is allowed to edit the user profile.
// This will let admins and the user themselves pass through, and
// throw an exception otherwise.
$user->assertCan($command->actor, 'edit');
$filename = $command->file->getFilename();
$uploadName = Str::lower(Str::quickRandom()) . '.jpg';
$mount = new MountManager([
'source' => new Local($command->file->getPath()),
'target' => $this->uploadDir,
]);
$user->changeAvatarUrl($uploadName);
event(new AvatarWillBeUploaded($user, $command));
$mount->move("source://$filename", "target://$uploadName");
$user->save();
$this->dispatchEventsFor($user);
return $user;
}
}