Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Ainet\Controllers;
- use Ainet\Models\User;
- class UserController
- {
- public function listUsers(){
- $users = User::all();
- $title = 'List users';
- render_view('users.list', compact('title', 'users'));
- }
- public function addUser(){
- $title = 'Add user';
- $user = new User;
- $errors = [];
- $formSubmitted = !empty($_POST);
- if (!$formSubmitted) {
- render_view('users.add', compact('title','user','errors'));
- }else{
- $user = $this->createUserFromData();
- $errors = $this->validate($user);
- require('src/views/users/partials/errors.view.php');
- render_view('users.add', compact('title','user','errors'));
- }
- }
- private function validate($user)
- {
- $errors = [];
- $passwordConfirmation = $_POST['password_confirmation'];
- if (!trim($user->fullname)) {
- $errors['Fullname'] = 'Fullname is required.';
- } elseif (!preg_match('/^[a-zA-Z ]+$/', $user->fullname)) {
- $errors['Fullname'] = 'Fullname must only contain letters and spaces.';
- }
- if (!$user->email) {
- $errors['Email'] = 'Email is required.';
- } elseif (!filter_var($user->email, FILTER_VALIDATE_EMAIL)) {
- $errors['Email'] = 'Invalid email address.';
- }
- if (!$user->password) {
- $errors['Password'] = 'Password is required.';
- } elseif (strlen($user->password) <= 8) {
- $errors['Password'] = 'Password must have at least 8 characters.';
- }
- if ($user->password && $passwordConfirmation != $user->password) {
- $errors['PasswordConfirmation'] = 'Password confirmation must be equal to password.';
- }
- if (!$user->user_type) {
- $errors['UserType'] = 'User type is required.';
- } else {
- switch ($user->user_type) {
- case 1:
- case 2:
- case 3:
- break;
- default:
- $errors['UserType'] = 'Type must be "administrator", "publisher" or "client".';
- }
- }
- return $errors;
- }
- private function createUserFromData()
- {
- $user = new User();
- if (array_key_exists('fullname', $_POST)) {
- $user->fullname = $_POST['fullname'];
- }
- else{
- $user->fullname = null;
- }
- if (array_key_exists('user_type', $_POST)) {
- $user->user_type = $_POST['user_type'];
- }
- else{
- $user->user_type = null;
- }
- if (array_key_exists('email', $_POST))
- {
- $user->email = $_POST['email'];
- }
- else{
- $user->email = null;
- }
- if(array_key_exists('password', $_POST))
- {
- $user->password = $_POST['password'];
- }
- else{
- $user->password = null;
- }
- return $user;
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement