SignupForm.php 2.45 KB
<?php
    
    namespace artbox\order\models;
    
    use yii\base\Model;
    
    /**
     * Signup form
     */
    class SignupForm extends Model
    {
        public $username;
        public $email;
        public $password;
        
        /**
         * @inheritdoc
         */
        public function rules()
        {
            return [
                [
                    'username',
                    'trim',
                ],
                [
                    'username',
                    'required',
                ],
                [
                    'username',
                    'unique',
                    'targetClass' => '\artbox\order\models\Customer',
                    'message'     => 'This username has already been taken.',
                ],
                [
                    'username',
                    'string',
                    'min' => 2,
                    'max' => 255,
                ],
                
                [
                    'email',
                    'trim',
                ],
                [
                    'email',
                    'required',
                ],
                [
                    'email',
                    'email',
                ],
                [
                    'email',
                    'string',
                    'max' => 255,
                ],
                [
                    'email',
                    'unique',
                    'targetClass' => '\artbox\order\models\Customer',
                    'message'     => 'This email address has already been taken.',
                ],
                
                [
                    'password',
                    'required',
                ],
                [
                    'password',
                    'string',
                    'min' => 6,
                ],
            ];
        }
        
        /**
         * Signs user up.
         *
         * @return \artbox\order\models\Customer|null the saved model or null if saving fails
         */
        public function signup()
        {
            if (!$this->validate()) {
                return null;
            }
            
            $user = new Customer();
            $user->username = $this->username;
            $user->email = $this->email;
            $user->setPassword($this->password);
            $user->generateAuthKey();
            
            return $user->save() ? $user : null;
        }
    }