phpvms/app/Interfaces/AwardInterface.php

81 lines
1.9 KiB
PHP
Raw Normal View History

2018-03-17 12:59:53 +08:00
<?php
namespace App\Interfaces;
use App\Facades\Utils;
use App\Models\Award;
2018-03-17 12:59:53 +08:00
use App\Models\User;
use App\Models\UserAward;
/**
* Base class for the Awards, they need to extend this
* @package App\Interfaces
*/
abstract class AwardInterface
2018-03-17 12:59:53 +08:00
{
public $name = '';
public $param_description = '';
2018-03-17 12:59:53 +08:00
protected $award;
protected $user;
2018-03-17 12:59:53 +08:00
/**
* Each award class just needs to return true or false if it should actually
* be awarded to a user. This is the only method that needs to be implemented
* @param null $parameter Optional parameters that are passed in from the UI
* @return bool
*/
abstract public function check($parameter = null): bool;
2018-03-17 12:59:53 +08:00
/**
* AwardInterface constructor.
* @param Award $award
* @param User $user
2018-03-17 12:59:53 +08:00
*/
public function __construct(Award $award = null, User $user = null)
2018-03-17 12:59:53 +08:00
{
$this->award = $award;
$this->user = $user;
2018-03-17 12:59:53 +08:00
}
/**
* Run the main handler for this award class to determine if
* it should be awarded or not
*/
public function handle()
{
# Check if the params are a JSON object or array
$param = $this->award->ref_class_params;
if ($this->award->ref_class_params && Utils::isObject($this->award->ref_class_params)) {
$param = json_decode($this->award->ref_class_params);
}
if ($this->check($param)) {
$this->addAward();
}
}
2018-03-17 12:59:53 +08:00
/**
* Add the award to this user, if they don't already have it
* @return bool|UserAward
2018-03-17 12:59:53 +08:00
*/
protected function addAward()
2018-03-17 12:59:53 +08:00
{
$w = [
'user_id' => $this->user->id,
2018-03-17 12:59:53 +08:00
'award_id' => $this->award->id
];
$found = UserAward::where($w)->count('id');
if ($found > 0) {
2018-03-17 12:59:53 +08:00
return true;
}
// Associate this award to the user now
$award = new UserAward($w);
$award->save();
return $award;
2018-03-17 12:59:53 +08:00
}
}