Skip to content

Instantly share code, notes, and snippets.

@mgerasimchuk
Created October 26, 2016 15:40
Show Gist options
  • Save mgerasimchuk/c2007eca90bb88ad5f29c2e9641c9b07 to your computer and use it in GitHub Desktop.
Save mgerasimchuk/c2007eca90bb88ad5f29c2e9641c9b07 to your computer and use it in GitHub Desktop.
StudentRegistrationForm http://frontend.sportstrack.projects.mg-dev.ru/ (click: sign up -> champion)
<?php
/**
* @author MGerasimchuk <gerasimchuk.mihail@gmail.com>
* DATE: 12.11.2015
* TIME: 17:36
*/
namespace common\models;
use email\models\Template;
use Yii;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "StudentRegistrationForm".
*/
class StudentRegistrationForm extends RegistrationForm
{
const SCENARIO_DEFAULT = "default";
const SCENARIO_FINISHED = "finished";
public $dBirth;
public $mBirth;
public $yBirth;
public $dateBirth;
public $groupId;
public $parentEmail;
/**
* @inheritdoc
*/
public function rules()
{
return [
['dateBirth', 'required'],
['dateBirth', 'date', 'format' => 'dd-mm-yyyy'],
['dateBirth', 'validateDateBirth'],
['groupId', 'integer'],
//[['dateBirth', 'groupId'], 'required'],
['parentEmail', 'email'],
[['dBirth', 'mBirth', 'yBirth'], 'integer'],
[
'parentEmail',
'required',
'when' => function ($model) {
return $model->isYoung();
},
'whenClient' => "function (attribute, value) {
var born = new Date($('#studentregistrationform-datebirth-kvdate').val());
var today = new Date();
var diff = new Date(today - born) / (365*1000*60*60*24);
return diff < 13;
}"
],
[['groupId'], 'exist', 'targetClass' => Group::className(), 'targetAttribute' => ['groupId' => 'id']],
['email', 'validateEmail', 'on' => static::SCENARIO_FINISHED],
[
'email',
'unique',
'targetClass' => UserAccount::className(),
'targetAttribute' => 'email',
'on' => static::SCENARIO_DEFAULT
],
['name', 'validateUser', 'on' => static::SCENARIO_FINISHED],
/** copyPaste from registrationForm */
[['name', 'email', 'fullName', 'gender', 'school'], 'string', 'max' => 255],
[['countryId'], 'integer'],
[['name', 'email', 'fullName', 'gender', 'password', 'repeatPassword', 'countryId', 'iAgree', 'school'], 'required'],
['name', 'match', 'pattern' => '/^[a-zA-Z0-9_-]+$/'],
['email', 'email'],
['repeatPassword', 'compare', 'compareAttribute' => 'password', 'message' => "Passwords don't match"],
['password', 'string', 'min' => 3],
[['iAgree'], 'boolean'],
['iAgree', 'compare', 'compareValue' => true, 'message' => 'You should have Sports Track TERMS & CONDITIONS!'],
[['countryId'], 'exist', 'targetClass' => Country::className(), 'targetAttribute' => ['countryId' => 'id']],
['city', 'required']
];
}
public function scenarios()
{
return ArrayHelper::merge(parent::scenarios(), [
static::SCENARIO_DEFAULT => [
'parentEmail',
'dateBirth',
'name',
'email',
'fullName',
'gender',
'password',
'repeatPassword',
'countryId',
'city',
'iAgree'
],
static::SCENARIO_FINISHED => [
'parentEmail',
'dateBirth',
'email',
'fullName',
'gender',
'password',
'repeatPassword',
'countryId',
'city',
'iAgree'
],
]);
}
public function validateEmail($attribute, $params)
{
$users = UserAccount::find()->all();
$regToken = Yii::$app->request->get('regToken');
foreach ($users as $user) {
if ($user->email === $this->email && $user->regToken != $regToken) {
$this->addError($attribute,
Yii::t('app', 'E-mail "' . $this->email . '" has already been taken.'));
}
}
}
public function validateDateBirth($attribute, $params)
{
$start = new \DateTime($this->dateBirth);
$end = new \DateTime();
$interval = $end->diff($start);
if($interval->y > 100) {
$this->addError($attribute, 'Age too large');
}
}
public function validateUser($attribute, $params)
{
$user = UserAccount::find()->where(['regToken' => Yii::$app->request->get('regToken')])->one();
if (!$user) {
$this->addError($attribute,
Yii::t('app', 'Reg token is not found'));
}
}
/**
* @return bool
*/
function isYoung()
{
$start = new \DateTime($this->dateBirth);
$end = new \DateTime();
$interval = $end->diff($start);
return $interval->y < 13;
}
/**
* @param bool|true $runValidation
* @return bool|UserAccount
* @throws \yii\base\Exception
* @throws \yii\base\InvalidConfigException
*/
public function register($runValidation = true)
{
assert(null !== Yii::$app->db->getTransaction());
if ($runValidation && !$this->validate()) {
return false;
}
/** CREATE SCHOOL */
$school = School::find()->where(['title' => $this->school, 'status' => School::STATUS_ACTIVE])->one();
if ($school) {
$this->schoolId = $school->id;
} else {
$school = new School();
$school->title = $this->school;
$school->countryId = $this->countryId;
$school->status = School::STATUS_NEW;
$school->trySave(false);
$this->schoolId = $school->id;
StudentRegistrationForm::sendCreateSchoolEmail($school->title, Yii::$app->params['adminEmail']);
StudentRegistrationForm::sendCreateSchoolEmail($school->title, 'info@sportstrack.world');
StudentRegistrationForm::sendCreateSchoolEmail($school->title, 'ciaran@sportstrack.world');
}
/** Save UserAccount Model */
$user = new UserAccount();
$user->setScenario(UserAccount::SCENARIO_ADMIN_CREATE);
$user->name = $this->name;
$user->status = UserAccount::STATUS_ACTIVE;
if ($this->isYoung()) {
$user->status = UserAccount::STATUS_INACTIVE;
$user->parentEmail = $this->parentEmail;
Template::findByShortcut(Template::SHORTCUT_LETTER_FOR_PARENTS)->queue($user->parentEmail);
do {
// TODO: Fix me!
$user->generateParentConfirmCode();
} while (UserAccount::find()->where(['parentConfirmCode' => $user->parentConfirmCode])->count() > 0);
$user->sendMailForParent();
}
$user->email = $this->email;
$user->countryId = $this->countryId;
$user->city = parent::refactorCity($this->city);
$user->schoolId = $this->schoolId;
$user->groupId = $this->groupId;
$user->passwordHash = \Yii::$app->security->generatePasswordHash($this->password);
$user->lastLoginAt = (new \DateTime())->format('Y-m-d H:i:s');
$user->lastLoginIp = Yii::$app->request->getUserIP();
$user->tryInsert(false);
Yii::$app->authManager->assign(Yii::$app->authManager->getRole(UserAccount::ROLE_STUDENT), $user->id);
/** Save UserProfile Model */
$userProfile = new UserProfile([
'ownerId' => $user->id,
]);
$userProfile->setScenario(UserAccount::SCENARIO_ADMIN_CREATE);
$fullName = explode(' ', $this->fullName);
$userProfile->firstName = ArrayHelper::getValue($fullName, 0);
$userProfile->lastName = ArrayHelper::getValue($fullName, 1);
$userProfile->gender = $this->gender;
$dateBirth = new \DateTime();
$dateBirth = $dateBirth->createFromFormat('d-m-Y', $this->dateBirth);
$userProfile->dateBirth = $dateBirth->format('Y-m-d');
$userProfile->tryInsert(false);
if (!$this->isYoung()) {
Template::findByShortcut(Template::SHORTCUT_CHAMPION_REGISTRATION)->queue($user->email, [
'username' => $this->fullName,
'date' => (new \DateTime())->format('M Y')
]);
}
return $user;
}
public static function sendCreateSchoolEmail($schoolName, $email)
{
Template::findByShortcut(Template::SHORTCUT_CREATE_SCHOOL)->queue($email, [
'school' => $schoolName,
'link' => Yii::$app->urlManager->createAbsoluteUrl(['admin/school']),
]);
}
public function finishRegistration($runValidation = true)
{
if ($runValidation && !$this->validate()) {
return false;
}
/** Save UserAccount Model */
$user = UserAccount::find()->where(['regToken' => Yii::$app->request->get('regToken')])->one();
$user->setScenario(UserAccount::SCENARIO_ADMIN_CREATE);
$user->name = $this->name;
$user->status = UserAccount::STATUS_ACTIVE;
if ($this->isYoung()) {
$user->status = UserAccount::STATUS_INACTIVE;
$user->parentEmail = $this->parentEmail;
Template::findByShortcut(Template::SHORTCUT_LETTER_FOR_PARENTS)->queue($user->parentEmail, [
'date' => (new \DateTime())->format('M Y')
]);
do {
$user->generateParentConfirmCode();
} while (UserAccount::find()->where(['parentConfirmCode' => $user->parentConfirmCode])->count() > 0);
$user->sendMailForParent();
}
$user->email = $this->email;
$user->countryId = $this->countryId;
$user->city = parent::refactorCity($this->city);
$user->schoolId = $this->schoolId;
$user->groupId = $this->groupId;
$user->passwordHash = \Yii::$app->security->generatePasswordHash($this->password);
$user->lastLoginAt = (new \DateTime())->format('Y-m-d H:i:s');
$user->lastLoginIp = Yii::$app->request->getUserIP();
$user->trySave(false);
/** Save UserProfile Model */
$userProfile = UserProfile::find()->where(['ownerId' => $user->id])->one();
if (!$userProfile) {
return false;
}
$userProfile->setScenario(UserAccount::SCENARIO_ADMIN_CREATE);
$fullName = explode(' ', $this->fullName);
$userProfile->firstName = ArrayHelper::getValue($fullName, 0);
$userProfile->lastName = ArrayHelper::getValue($fullName, 1);
$userProfile->gender = $this->gender;
$dateBirth = new \DateTime();
$dateBirth = $dateBirth->createFromFormat('d-m-Y', $this->dateBirth);
$userProfile->dateBirth = $dateBirth->format('Y-m-d');
$userProfile->trySave(false);
$user->regToken = null;
$user->trySave(false);
if (!$this->isYoung()) {
Template::findByShortcut(Template::SHORTCUT_CHAMPION_REGISTRATION)->queue($user->email, [
'username' => $this->fullName,
'date' => (new \DateTime())->format('M Y')
]);
}
return $user;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment