Skip to content

Instantly share code, notes, and snippets.

@phptuts
Created February 17, 2019 23:38
Show Gist options
  • Save phptuts/df89e7f090619be5b3294ffeab0802a4 to your computer and use it in GitHub Desktop.
Save phptuts/df89e7f090619be5b3294ffeab0802a4 to your computer and use it in GitHub Desktop.
Chain of Responsibility Pattern
<?php
abstract class RoleChecker {
/**
* @var RoleChecker
*/
protected $nextCheck;
abstract public function check(UserRole $userRole);
public function next(UserRole $userRole)
{
if ($this->nextCheck) {
$this->nextCheck->check($userRole);
}
}
public function setNextChecker(RoleChecker $checker)
{
$this->nextCheck = $checker;
}
}
class UserRole {
public $type;
public $date;
}
class AdminCheck extends RoleChecker {
public function check(UserRole $userRole)
{
if (!$userRole->type != 'ADMIN') {
throw new Exception('User Not Admin');
}
$this->next($userRole);
}
}
class RegistrationDate extends RoleChecker {
public function check(UserRole $userRole)
{
if (strtotime($userRole->date) > strtotime('2018-01-01')) {
throw new Exception('2018 Users only.');
}
$this->next($userRole);
}
}
$role = new UserRole();
$role->type = 'ROLE_USER';
$role->date = '2017-01-01';
$adminCheck = new AdminCheck();
$registrationCheck = new RegistrationDate();
$adminCheck->setNextChecker($registrationCheck);
$adminCheck->check($role);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment