Skip to content

Instantly share code, notes, and snippets.

@MacDada
Last active November 20, 2016 20:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MacDada/81f870ff4b5e839ccb407f6d14125415 to your computer and use it in GitHub Desktop.
Save MacDada/81f870ff4b5e839ccb407f6d14125415 to your computer and use it in GitHub Desktop.
Authorization and Use Cases: option 1: authorization inside Use Case
<?php
namespace Foo\Bar\Application\UseCase;
use Foo\Bar\Application\AuthorizationChecker;
use Foo\Bar\Domain\ItemRepository;
class ViewItemUseCase
{
/**
* @var AuthorizationChecker
*/
private $authorizationChecker;
/**
* @var ItemRepository
*/
private $itemRepository;
public function __construct(
AuthorizationChecker $authorizationChecker,
ItemRepository $itemRepository
) {
$this->authorizationChecker = $authorizationChecker;
$this->itemRepository = $itemRepository;
}
/**
* @param ViewItemRequest $request
* @return ViewItemResponse
* @throws ItemNotFoundException
* @throws ItemDeletedException
*/
public function viewItem(ViewItemRequest $request)
{
$item = $this->itemRepository->find($request->itemId);
if (null === $item) {
throw new ItemNotFoundException(sprintf('Item with id "%s" was not found', $request->itemId));
}
if ($item->isDeleted() && false === $this->authorizationChecker->isGranted('view', $item)) {
throw new ItemDeletedException(sprintf('Item with id "%s" is deleted', $request->itemId));
}
$response = new ViewItemResponse();
$response->item = $item;
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment