Created
June 27, 2017 19:25
-
-
Save harrysbaraini/59418173a42229623edb6b97a56bf3e3 to your computer and use it in GitHub Desktop.
PHPExceptionsQuestion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Framework\Request; | |
use App\Exceptions\ModelNotFoundException; | |
use App\Exceptions\AuthorizationException; | |
class EntriesController | |
{ | |
public function getEntry(Request $request, $id) | |
{ | |
// First we look for the Entry by the provided ID. | |
// Depending on the result, we catch the error and redirect | |
// the user to the proper page with the proper error. | |
try { | |
$entry = $this->dispatchNow(new GetEntry($entryID, $request->whitelabel_group)); | |
} catch (ModelNotFoundException $exception) { | |
return redirect()->route('home')->with('error', trans('general.entries.messages.invalid')); | |
} catch (AuthorizationException $exception) { | |
return redirect()->route('home')->with('error', $exception->getMessage()); | |
} | |
// Process... | |
return view('entries.view')->with('entry', $entry); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* This class is a Self-handling Command Bus to fetch an Entry from database. | |
*/ | |
class GetEntry | |
{ | |
/** | |
* @var | |
*/ | |
private $entryID; | |
/** | |
* @var | |
*/ | |
private $community; | |
/** | |
* ... | |
* | |
* @param $entryID | |
* @param Community $community | |
*/ | |
public function __construct($entryID, Community $community) | |
{ | |
$this->entryID = $entryID; | |
$this->community = $community; | |
} | |
/** | |
* Execute the command. | |
* | |
* @return void | |
*/ | |
public function handle() | |
{ | |
$entry = Entry::findOrFail($this->entryID); // It throws an exception if record is not found on database | |
// No user logged in and community is private | |
if (!request()->user() && !$this->community->isOpen()) { | |
throw new AuthorizationException(trans('general.entries.messages.entry_view_not_allowed')); | |
} | |
// User is logged in but cannot view the entry (user is not subscribed to the private community) | |
if (!request()->user()->can('view', $entry, $this->community)) { | |
throw new AuthorizationException(trans('general.entries.messages.not_allowed')); | |
} | |
// User can view the entry, so we return it... | |
return $entry; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment