Created
May 24, 2020 23:41
-
-
Save lpj145/8f620aab6163bd18bfc1c767ab6e4732 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Usuarios Model | |
*/ | |
namespace Admin\Model\Table; | |
use Admin\Model\Table\AdminAppTable; | |
use Cake\ORM\Query; | |
use Cake\ORM\RulesChecker; | |
use Cake\Validation\Validator; | |
use Cake\Datasource\EntityInterface; | |
use Cake\Event\Event; | |
use ArrayObject; | |
use Exception; | |
/** | |
* mantem a tabela de usuário | |
*/ | |
class UsuariosTable extends AdminAppTable { | |
/** | |
* Guarda o id e e-mail do usuário excluído. | |
* | |
* @var array | |
*/ | |
private $dataDel = ['id'=>0, 'email'=>'']; | |
/** | |
* Initialize method | |
* | |
* @param array $config The configuration for the Table. | |
* @return void | |
*/ | |
public function initialize(array $config) | |
{ | |
parent::initialize($config); | |
$this->setTable('usuarios'); | |
$this->setDisplayField('email'); | |
$this->setPrimaryKey('id'); | |
$this->setEntityClass('Admin.Usuario'); | |
$this->belongsTo('Municipios', | |
[ | |
'foreignKey' => 'municipio_id', | |
'joinType' => 'INNER', | |
'className' => 'Admin.Municipios', | |
]); | |
$this->belongsTo('UltimoPapel', | |
[ | |
'foreignKey' => 'ultimo_papel_id', | |
'className' => 'Admin.Papeis', | |
]); | |
$this->belongsToMany('Papeis', | |
[ | |
'foreignKey' => 'usuario_id', | |
'targetForeignKey' => 'papel_id', | |
'joinTable' => 'usuarios_papeis', | |
'className' => 'Admin.Papeis', | |
]); | |
} | |
/** | |
* Default validation rules. | |
* | |
* @param \Cake\Validation\Validator $validator Validator instance. | |
* @return \Cake\Validation\Validator | |
*/ | |
public function validationDefault(Validator $validator) | |
{ | |
$validator | |
->integer('id') | |
->allowEmptyString('id', null, 'create'); | |
$validator | |
->scalar('nome') | |
->maxLength('nome', 100) | |
->minLength('nome', 3, __('O nome dever ter ao menos 3 caracteres!')) | |
->notEmptyString('nome'); | |
$validator | |
->email('email', null, __('e-mail inválido!') ) | |
->notEmptyString('email'); | |
$validator | |
->integer('ativo') | |
->notEmptyString('ativo', __("O Campo 'Ativo' é de preenchimento obrigatório!")); | |
$validator | |
->integer('ultimo_papel_id') | |
->requirePresence('ultimo_papel_id', 'create', __("O 'Último Papel' é obrigatório na inclusão!") ) | |
->notEmptyString('ultimo_papel_id'); | |
$validator | |
->scalar('senha') | |
->maxLength('senha', 100) | |
->minLength('senha', 8, __('A Senha deve ter ao menos 8 caracteres!') ) | |
->requirePresence('senha', 'create', __('A Senha é obrigatória na inclusão!') ) | |
->notEmptyString('senha', __("A senha não pode ser em branco!") ); | |
return $validator; | |
} | |
/** | |
* Returns a rules checker object that will be used for validating | |
* application integrity. | |
* | |
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified. | |
* @return \Cake\ORM\RulesChecker | |
*/ | |
public function buildRules(RulesChecker $rules) | |
{ | |
$rules->add($rules->isUnique(['email'], __('Este e-mail já foi cadastrado!'))); | |
$rules->add($rules->existsIn(['municipio_id'], 'Municipios')); | |
return $rules; | |
} | |
/** | |
* Executa código antes de validar e salvar | |
* | |
* @param $event | |
* @param $data | |
* @param $options | |
* @return self | |
*/ | |
public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options) | |
{ | |
$id = @$data['id']; | |
$inclusao = empty( $id ) ? true : false; | |
// se é uma inclusão, mas não informou a senha, configura a senha padrão. | |
if ( $inclusao && !isset($data['senha']) ) | |
{ | |
$data['senha'] = $data['email']; | |
} | |
// se é uma inclusão, mas não informou o último papel, configura o papel padrão. | |
if ( $inclusao && !isset($data['ultimo_papel_id']) ) | |
{ | |
$data['ultimo_papel_id'] = 3; | |
} | |
// usuário administrador sempre ativo e sempre administrador | |
if ( $id == 1) | |
{ | |
$data['ativo'] = 1; | |
if ( strpos( $data['papeis_ids'], 1 ) < -1 ) | |
{ | |
$data['papeis_ids'] .= ', 1'; | |
} | |
} | |
parent::beforeMarshal( $event, $data, $options ); | |
} | |
/** | |
* Executa código antes da exclusão. | |
* | |
* @return void | |
*/ | |
public function beforeDelete($event, $entity, $options) | |
{ | |
$this->dataDel['id'] = $entity->id; | |
$this->dataDel['email'] = $entity->email; | |
$idSessao = @$_SESSION['Auth']['User']['id']; | |
if ( $entity->id == $idSessao ) | |
{ | |
$this->errors[] = __( 'Você não pode excluir a si mesmo!' ); | |
} | |
if ( $entity->id == 1 ) | |
{ | |
$this->errors[] = __( 'O Usuário Administrador não pode excluído!' ); | |
} | |
return count( $this->errors ) ? false : true; | |
} | |
/** | |
* Executa código após uma exclusão | |
* | |
* @param string $email E-mail do usuário excluído. | |
* @return void | |
*/ | |
public function afterDelete() | |
{ | |
auditar("O Usuário de e-mail ".$this->dataDel['email']." foi excluído da base.", "exclusão"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment