Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. //trigger event
  2.  
  3. // Event
  4. class UserEarnedExperience
  5. {
  6. public $user;
  7.  
  8. public function __construct($user)
  9. {
  10. $this->user = $user;
  11. }
  12. }
  13.  
  14. // Listener
  15. class AwardAchivements
  16. {
  17. public function handle(UserEarnedExperience $event)
  18. {
  19. $achivementIdsToAwward = app('achievements')->filter(function ($achievement) use ($event) {
  20. return $achievement->qualified($event->user);
  21. })->map(function ($achievement) {
  22. return $achievement->modelKey();
  23. });
  24.  
  25. $event->user->achievements()->sync($achivementIdsToAwward);
  26. }
  27. }
  28.  
  29. class FirstThousandPoints extends AchievementType
  30. {
  31. public $name = 'First Thousand Points';
  32. public $description = 'Achieved by getting to 1000 points';
  33. public $icon = 'thousand-points.svg';
  34. public $level = 'beginer';
  35.  
  36. public function qualified($user)
  37. {
  38. return $user->points >= 1000;
  39. }
  40. }
  41. class StartYourEngines extends AchievementType
  42. {
  43. public $name = 'Start your engines';
  44. public $description = 'Achieved by completing at least one lesson';
  45. public $icon = 'start-your-engines.svg';
  46. public $level = 'beginer';
  47.  
  48. public function qualified($user)
  49. {
  50. return $user->completions()->count() >= 1;
  51. }
  52. }
  53.  
  54. abstract class AchievementType
  55. {
  56. // we might take a different approach to populate the database
  57. // Achievement is the Model with many2many relationship with User
  58. public function __construct()
  59. {
  60. $this->model = Achievement::firstOrCreate([
  61. 'name' => $this->name,
  62. 'description' => $this->description,
  63. 'icon' => $this->icon,
  64. 'level' => $this->level
  65. ]);
  66. }
  67.  
  68. public function modelKey()
  69. {
  70. return $this->model->getKey();
  71. }
  72. }
  73.  
  74. class AchievementServiceProvider extends ServiceProvider
  75. {
  76. protected $achievements = [
  77. FirstThousandPointsAchievement::class,
  78. StartYourEngines::class
  79. ];
  80.  
  81. public function register()
  82. {
  83. $this->app->singleton('achievement', function () {
  84. // caching because instead of hitting database every time on every user we hit only once
  85. // now when we hit this it looks up for achievement classes in cache
  86. // dont forget to clear cache when creating new achievement
  87. return cache()->rememberForever('achievements', function () {
  88. return collect($this->achievements)->map(function ($achievement) {
  89. return new $achievement;
  90. });
  91. });
  92. });
  93. }
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement