I am using Laravel 5's Command Bus and I am unclear how to implement a validator class.
I would like to create a ResizeImageCommandValidator class that checks that the image is actually an image before attempting to resize the image.
The code I'd like to pull out is here from the ResizeImageCommandHandler resize method.
if (!($image instanceof Image))
{
throw new ImageInvalidException('ResizeImageCommandHandler');
}
The idea came from Laracasts Commands and Domain Events, but Jeffrey doesn't use the Laravel 5 architecture.
Here's the code.
ResizeImageCommandHandler.php
<?php namespace App\Handlers\Commands;
use App\Commands\ResizeImageCommand;
use App\Exceptions\ImageInvalidException;
use Illuminate\Queue\InteractsWithQueue;
use Intervention\Image\Image;
class ResizeImageCommandHandler {
/**
* Create the command handler.
*/
public function __construct()
{
}
/**
* Handle the command.
*
* @param ResizeImageCommand $command
* @return void
*/
public function handle($command)
{
$this->resizeImage($command->image, $command->dimension);
}
/**
* Resize the image by width, designed for square image only
* @param Image $image Image to resize
* @param $dimension
* @throws ImageInvalidException
*/
private function resizeImage(&$image, $dimension)
{
if (!($image instanceof Image))
{
throw new ImageInvalidException('ResizeImageCommandHandler');
}
$image->resize($dimension, null, $this->constrainAspectRatio());
}
/**
* @return callable
*/
private function constrainAspectRatio()
{
return function ($constraint) {
$constraint->aspectRatio();
};
}
}
ResizeImageCommand.php
<?php namespace App\Commands;
use App\Commands\Command;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldBeQueued;
use Image;
class ResizeImageCommand extends Command {
use InteractsWithQueue, SerializesModels;
public $image;
public $savePath;
public $dimension;
/**
* Create a new command instance.
* @param Image $image
* @param string $savePath
* @param int $dimension
* @param int $pose_id
* @param int $state_id
*/
public function __construct(&$image, $savePath, $dimension)
{
$this->image = $image;
$this->savePath = $savePath;
$this->dimension = $dimension;
}
}