Skip to content

Instantly share code, notes, and snippets.

@rizqidjamaluddin
Created February 23, 2015 02:10
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 rizqidjamaluddin/e0c72851823a8fc5dc22 to your computer and use it in GitHub Desktop.
Save rizqidjamaluddin/e0c72851823a8fc5dc22 to your computer and use it in GitHub Desktop.
<?php
class License extends Model {
public static function generate (User $user) {
$i = new static;
$i->made_by = $user->id;
$i->serial = \Str::random(64); // you can also use a separate factory class that injects a random generator
$i->save();
}
public function assignTo (User $user) {
$this->assigned = true;
$this->assigned_to = $user->id;
$this->save();
}
}
<?php
class LicenseGranter {
public function generate(User $user, $asignTo = null) {
$license = License::generate($user);
if ($assignTo) {
$this->assign($license, $user, $assignTo);
}
return $license;
}
public function assign(License $license, User $assigner, User $target) {
// this sort of awkward authorization checks typically go to their own class
if ($assigner->getRole() == 'superuser') {
if ($target->getRole() == 'admin') return $license->assignTo($target);
}
if ($assigner->getRole() == 'admin') {
if ($target->getRole() == 'consultant' && $assigner->getTeamMembers()->has($target)) return $license->assignTo($target);
}
throw new LicenseAssignmentNotAllowedException($assigner, $target);
}
}
@Dombo
Copy link

Dombo commented Feb 23, 2015

In regards to Line 16 I could put a canAssign() & canGenerate() method in the users model which does the necessary checks and returns true if they pass.

class User extends Model {

public function canAssign (User $user) {
$this->role == 'consultant' || 'admin';
return true;
}
}

public function canGenerate (User $user) {
$this->role == 'admin';
return true;
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment