Advertisement
stixlink

model yii User

Nov 19th, 2014
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 11.54 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  * This is the model class for table "{{customer}}".
  5.  *
  6.  * The followings are the available columns in table '{{customer}}':
  7.  *
  8.  * @property integer $id
  9.  * @property string  $username
  10.  * @property string  $password
  11.  * @property string  $firstname
  12.  * @property string  $lastname
  13.  * @property string  $middlename
  14.  * @property integer $active
  15.  * @property string  $date_create
  16.  * @property string  $last_login
  17.  * @property float   $balance
  18.  * @property string  $ip
  19.  * @property string  $token
  20.  * @property string  $role
  21.  * @property string  $email
  22.  */
  23. class User extends CActiveRecord implements IUserLog {
  24.  
  25.     const ROLE_USER = 'user';
  26.     const ROLE_CUSTOMER = 'customer';
  27.     const ROLE_GUEST = 'guest';
  28.  
  29.     static public $roles = array(
  30.         self::ROLE_USER => 'User',
  31.         self::ROLE_CUSTOMER => 'Customer',
  32.         //        self::ROLE_GUEST => 'Guest'
  33.     );
  34.     static public $returnDataUser = array('username', 'firstname', 'lastname', 'date_create', 'balance', 'token');
  35.  
  36.  
  37.     public $confirmPassword;
  38.     public $token = null;
  39.  
  40.  
  41.     public $verifyCode;
  42.  
  43.     static public $lableActive = array(
  44.         '1' => 'Active',
  45.         '0' => 'Not active'
  46.     );
  47.  
  48.     /**
  49.      * @return string the associated database table name
  50.      */
  51.     public function tableName() {
  52.  
  53.         return '{{user}}';
  54.     }
  55.  
  56.     public function getLogId() {
  57.  
  58.         return $this->id;
  59.     }
  60.  
  61.     public function getTypeUser() {
  62.  
  63.         return $this->role;
  64.     }
  65.  
  66.     public function getRole() {
  67.  
  68.         return $this->role;
  69.     }
  70.  
  71.     public function getFullName() {
  72.  
  73.         return $this->lastname . ' ' . $this->firstname . ' ' . $this->middlename;
  74.     }
  75.  
  76.     public function getUsername() {
  77.  
  78.         return $this->username;
  79.     }
  80.  
  81.     public function getBalance() {
  82.  
  83.         return $this->balance;
  84.     }
  85.  
  86.  
  87. //todo add cache
  88.     /**
  89.      * @param             $mark
  90.      * @param CDbCriteria $criteria
  91.      *
  92.      * @return null
  93.      * @throws CDbException
  94.      * @throws CException
  95.      */
  96.     public function getFullAmountAndCountByMarkCustomer($mark, CDbCriteria $criteria) {
  97.  
  98.         if (HistoryBuy::getLabelStatus($mark) === null) {
  99.             throw new CException('Undefined "mark"! Use value "mark" defined in class "' . __CLASS__ . '"');
  100.         };
  101.  
  102.         $ids = implode(',', $this->getListIdShop());
  103.         if ($ids == '') {
  104.             $ids = 0;
  105.         }
  106.  
  107.         $condition = ($criteria->condition !== '' ? $criteria->condition . ' AND ' : $criteria->condition) . 'mark=:marked';
  108.         $params = CMap::mergeArray(array(':marked' => $mark), $criteria->params);
  109.  
  110.         $command = self::getDbConnection()->createCommand();
  111.         $command->select('SUM(amount) as sum_amount, COUNT(amount) as sum_count_goods')
  112.                 ->from(HistoryBuy::model()->tableName())
  113.                 ->where($condition, $params);
  114.         $result = $command->queryAll();
  115.  
  116.         return isset($result[0]) ? $result[0] : null;
  117.     }
  118.  
  119. //todo add cache
  120.     /**
  121.      * @param             $mark
  122.      * @param CDbCriteria $criteria
  123.      *
  124.      * @return null
  125.      * @throws CDbException
  126.      * @throws CException
  127.      */
  128.     public function getFullAmountAndCountByMarkUser($mark, CDbCriteria $criteria) {
  129.  
  130.         if (HistoryBuy::getLabelStatus($mark) === null) {
  131.             throw new CException('Undefined "mark"! Use value "mark" defined in class "' . __CLASS__ . '"');
  132.         };
  133.  
  134.         $condition = ($criteria->condition !== '' ? $criteria->condition . ' AND ' : $criteria->condition) . 'mark=:marked';
  135.         $params = CMap::mergeArray(array(':marked' => $mark), $criteria->params);
  136.  
  137.         $command = self::getDbConnection()->createCommand();
  138.         $command->select('SUM(amount) as sum_amount, COUNT(amount) as sum_count_goods')
  139.                 ->from(HistoryBuy::model()->tableName())
  140.                 ->where($condition, $params);
  141.  
  142.         $result = $command->queryAll();
  143.  
  144.         return isset($result[0]) ? $result[0] : null;
  145.     }
  146.  
  147.     public function getDataForShop() {
  148.  
  149.         $user = new User();
  150.         $arrayReturnColumn = array('id', 'username', 'last_login', 'date_create', 'balance', 'active');
  151.         $select = implode(', ', $arrayReturnColumn);
  152.         $sql = "SELECT {$select} FROM `{$user->tableName()}` WHERE id=:id ";
  153.         $command = $user->getDbConnection()->createCommand($sql);
  154.         $result = $command->queryRow(true, array(':id' => (int)Yii::app()->user->id));;
  155.         if (empty($result)) {
  156.  
  157.             return array('error' => 'Not found user!');
  158.         }
  159.  
  160.         $token = new TokensAuthenticate();
  161.         $tokenNew = $token->addToken((int)Yii::app()->user->id)->token;
  162.         $result['token'] = $tokenNew;
  163.  
  164.         return $result;
  165.     }
  166.  
  167.     /**
  168.      *
  169.      * Получение списка id всех магазинов пользователя
  170.      *
  171.      * @return array
  172.      * @throws CDbException
  173.      */
  174.     public function getListIdShop() {
  175.  
  176.         if ($this->role != self::ROLE_CUSTOMER) {
  177.             return array();
  178.         }
  179.         $command = self::getDbConnection()->createCommand();
  180.         $command->select('id,customer_id')
  181.                 ->from(Shops::model()->tableName())
  182.                 ->where('customer_id=:customer_id', array(':customer_id' => $this->id));
  183.         $result = $command->queryAll();
  184.         $ids = array();
  185.         if (is_array($result) && count($result) > 0) {
  186.             foreach ($result as $res) {
  187.                 $ids[] = $res['id'];
  188.             }
  189.         }
  190.  
  191.         return $ids;
  192.     }
  193.  
  194.     /**
  195.      * @return array validation rules for model attributes.
  196.      */
  197.     public function rules() {
  198.  
  199.         // NOTE: you should only define rules for those attributes that
  200.         // will receive user inputs.
  201.         return array(
  202.  
  203.             array('username, date_create, email, role', 'required'),
  204.             array('username', 'unique'),
  205.             array('active', 'numerical', 'integerOnly' => true),
  206.             array('username', 'length', 'max' => 45),
  207.             array('password, ip', 'length', 'max' => 100),
  208.             array('firstname, lastname, middlename', 'length', 'max' => 65),
  209.             array('last_login', 'safe'),
  210.             array('email', 'email'),
  211.             array('role', 'validRole'),
  212.  
  213.  
  214.             array('confirmPassword, password', 'unsafe', 'on' => 'profile'),
  215.             array('confirmPassword', 'checkConfirmPassword', 'on' => 'profile'),
  216.  
  217.             array('username', 'safe', 'on' => 'registration'),
  218.             array('confirmPassword, password', 'required', 'on' => 'registration'),
  219.             array('confirmPassword', 'checkConfirmPassword', 'on' => 'registration'),
  220.             array('verifyCode', 'captcha', 'allowEmpty' => !CCaptcha::checkRequirements(), 'on' => 'registration'),
  221.  
  222.             array('balance', 'unsafe'),
  223.             array('id, username, password, email, role, firstname, lastname, middlename, active, date_create, last_login, ip', 'safe', 'on' => 'search'),
  224.         );
  225.     }
  226.  
  227.     public function validRole($field, $params) {
  228.  
  229.         if (!isset(self::$roles[$this->role])) {
  230.             $this->addError($field, "Invalid role.");
  231.         }
  232.     }
  233.  
  234.     public function checkConfirmPassword($field, $params) {
  235.  
  236.         if ($this->getScenario() == 'registration') {
  237.             if ($this->password != $this->confirmPassword) {
  238.                 $this->addError($field, "Passwords do not match.");
  239.             }
  240.         } elseif ($this->getScenario() == 'profile') {
  241.             if ($this->password != '' && ($this->password != $this->confirmPassword)) {
  242.                 $this->addError($field, "Passwords do not match.");
  243.             }
  244.         }
  245.     }
  246.  
  247.     /**
  248.      * @return array relational rules.
  249.      */
  250.     public function relations() {
  251.  
  252.         // NOTE: you may need to adjust the relation name and the related
  253.         // class name for the relations automatically generated below.
  254.         return array();
  255.     }
  256.  
  257.     public function scopes() {
  258.  
  259.         return array(
  260.             'active' => array(
  261.                 'condition' => 'active=1'
  262.             )
  263.         );
  264.     }
  265.  
  266.     /**
  267.      * @return array customized attribute labels (name=>label)
  268.      */
  269.     public function attributeLabels() {
  270.  
  271.         return array(
  272.             'id' => 'ID',
  273.             'username' => 'Username',
  274.             'password' => 'Password',
  275.             'confirmPassword' => 'Confirm Password',
  276.             'firstname' => 'Firstname',
  277.             'lastname' => 'Lastname',
  278.             'middlename' => 'Middlename',
  279.             'active' => 'Active',
  280.             'date_create' => 'Date Create',
  281.             'last_login' => 'Last Login',
  282.             'balance' => 'Balance',
  283.             'ip' => 'Ip',
  284.             'role' => 'Role',
  285.             'email' => 'Email',
  286.         );
  287.     }
  288.  
  289.     public function beforeValidate() {
  290.  
  291.         if (!empty($this->username)) {
  292.             $this->username = mb_strtolower($this->username);
  293.         }
  294.  
  295.         if ($this->getScenario() == 'registration' && $this->isNewRecord) {
  296.             $this->date_create = date('Y-m-d H:i:s');
  297.  
  298.         }
  299.  
  300.         return parent::beforeValidate();
  301.     }
  302.  
  303.     public function beforeSave() {
  304.  
  305.         if ($this->getScenario() == 'registration' && $this->isNewRecord) {
  306.             $this->username = trim($this->username);
  307.             $this->password = md5(trim($this->password));
  308.  
  309.         }
  310.         if ($this->getScenario() == 'profile'
  311.             && $this->password != ''
  312.             && $this->confirmPassword != ''
  313.             && $this->confirmPassword == $this->password
  314.         ) {
  315.             $this->password = md5($this->password);
  316.  
  317.         }
  318.  
  319.  
  320.         return parent::beforeSave();
  321.     }
  322.  
  323.     /**
  324.      * Retrieves a list of models based on the current search/filter conditions.
  325.      *
  326.      * Typical usecase:
  327.      * - Initialize the model fields with values from filter form.
  328.      * - Execute this method to get CActiveDataProvider instance which will filter
  329.      * models according to data in model fields.
  330.      * - Pass data provider to CGridView, CListView or any similar widget.
  331.      *
  332.      * @return CActiveDataProvider the data provider that can return the models
  333.      * based on the search/filter conditions.
  334.      */
  335.     public function search() {
  336.  
  337.         // @todo Please modify the following code to remove attributes that should not be searched.
  338.  
  339.         $criteria = new CDbCriteria;
  340.  
  341.         $criteria->compare('id', $this->id);
  342.         $criteria->compare('username', $this->username, true);
  343.         $criteria->compare('password', $this->password, true);
  344.         $criteria->compare('firstname', $this->firstname, true);
  345.         $criteria->compare('lastname', $this->lastname, true);
  346.         $criteria->compare('middlename', $this->middlename, true);
  347.         $criteria->compare('active', $this->active);
  348.         $criteria->compare('balance', $this->balance);
  349.         $criteria->compare('date_create', $this->date_create, true);
  350.         $criteria->compare('last_login', $this->last_login, true);
  351.         $criteria->compare('ip', $this->ip, true);
  352.  
  353.         return new CActiveDataProvider($this, array(
  354.             'criteria' => $criteria,
  355.         ));
  356.     }
  357.  
  358.     /**
  359.      * Returns the static model of the specified AR class.
  360.      * Please note that you should have this exact method in all your CActiveRecord descendants!
  361.      *
  362.      * @param string $className active record class name.
  363.      *
  364.      * @return User the static model class
  365.      */
  366.     public static function model($className = __CLASS__) {
  367.  
  368.         return parent::model($className);
  369.     }
  370. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement