Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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