Browse Source

added custom register, auth, getaverageAge. added db dump

Плотников Роман Вячеславович 3 years ago
parent
commit
d842d745cf

+ 41 - 3
app/Controller/Site.php

@@ -2,11 +2,15 @@
 
 namespace Controller;
 
+use DateTime;
+use DateTimeZone;
 use Src\View;
 use Src\Auth\Auth;
 use Src\Request;
 use Model\Post;
 use Model\User;
+use Model\State;
+use Illuminate\Database\QueryException;
 
 class Site
 {
@@ -23,10 +27,28 @@ class Site
 
     public function signup(Request $request): string
     {
-        if ($request->method === "POST" && User::create($request->all())) {
-            app()->route->redirect('/hello');
+        if ($request->method === "POST") {
+            $error = '';
+            $post = $request->post;
+            $states = State::all();
+
+            if ($post['password'] !== $post['password2']) $error = $error . 'Пароли не совпадают <br>';
+            if ($post['state'] === 'fake') $error = $error . 'Выберите штат <br>';
+            if ($post['gender'] === 'fake') $error = $error . 'Выберите пол <br>';
+
+            if (!empty($error)) return new View('site.signup', ['error' => $error, 'states' => $states]);
+
+            try {
+                if (User::create($request->all())) {
+                    app()->route->redirect('/hello');
+                }
+            } catch (QueryException $e) {
+                return new View('site.signup', ['error' => 'Логин занят.', 'states' => $states]);
+            }
         }
-        return new View('site.signup');
+
+        $states = State::all();
+        return new View('site.signup', ['states' => $states]);
     }
     public function login(Request $request): string
     {
@@ -47,4 +69,20 @@ class Site
         Auth::logout();
         app()->route->redirect('/hello');
     }
+
+    public function getAverageAge(): string
+    {
+        $users = User::all();
+        $age = 1;
+        $agesArray = [];
+        $averageAge = 'Средний возраст, лет: ';
+        foreach ($users as $user) {
+            $age = DateTime::createFromFormat('d/m/Y', date('d/m/Y', strtotime($user->birth_date)))
+                ->diff(new DateTime('now'))
+                ->y;
+            array_push($agesArray, $age);
+        }
+        $averageAge = $averageAge . array_sum($agesArray) / count($agesArray);
+        return (new View)->render('site.hello', ['age' => $averageAge]);
+    }
 }

+ 13 - 0
app/Model/State.php

@@ -0,0 +1,13 @@
+<?php
+
+namespace Model;
+
+use Illuminate\Database\Eloquent\Model;
+
+class State extends Model{
+
+    protected $table = 'states';
+    protected $fillable = [
+        'name'
+    ];
+}

+ 9 - 2
app/Model/User.php

@@ -11,9 +11,16 @@ class User extends Model implements IdentityInterface{
 
     public $timestamps = false;
     protected $fillable = [
-        'name',
+        'first_name',
+        'last_name',
+        'middle_name',
+        'gender',
+        'post',
+        'home_address',
+        'birth_date',
+        'state',
         'login',
-        'password'
+        'password',
     ];
 
     protected static function booted()

+ 2 - 0
core/Src/Request.php

@@ -9,12 +9,14 @@ class Request
     protected array $body;
     public string $method;
     public array $headers;
+    public array $post;
 
     public function __construct()
     {
         $this->body = $_REQUEST;
         $this->method = $_SERVER['REQUEST_METHOD'];
         $this->headers = getallheaders() ?? [];
+        $this->post = $_POST;
     }
 
     public function all(): array

+ 2 - 2
public/.htaccess

@@ -1,6 +1,6 @@
 <IfModule mod_rewrite.c>
     RewriteEngine on
-    RewriteCond ${REQUEST_FILENAME} !-d
-    RewriteCond ${REQUEST_FILENAME} !-f
+    RewriteCond %{REQUEST_FILENAME} !-f
+    RewriteCond %{REQUEST_FILENAME} !-d
     RewriteRule ^ index.php [L]
 </IfModule>

+ 38 - 0
public/css/style.css

@@ -0,0 +1,38 @@
+.form {
+    display: flex;
+    flex-direction: column;
+    justify-content: space-around;
+    align-items: center;
+}
+
+.form button, .form input{
+    display: block;
+    width: 20%;
+    margin: 5px 0;
+    padding: 10px;
+    font-size: 15px;
+}
+
+.form select {
+    display: block;
+    width: 21vw;
+    margin: 5px 0;
+    padding: 10px;
+    font-size: 15px;
+}
+
+.form label {
+    margin-top: 4px;
+}
+
+.form input, .form select, .form button {
+    border-radius: 10px;
+    border: 1px solid black
+}
+
+.form button {
+    border: 3px solid rgb(111, 231, 240);
+    width: 14vw;
+    background-color: rgb(198, 246, 255);
+}
+

+ 1 - 0
public/index.php

@@ -3,6 +3,7 @@
 declare(strict_types=1);
 session_start();
 
+
 try {
     $app = require_once __DIR__ . '/../core/bootstrap.php';
     $app->run();

+ 1 - 0
routes/web.php

@@ -7,3 +7,4 @@ Route::add('GET', '/hello', [Controller\Site::class, 'hello'])
 Route::add(['GET', 'POST'], '/signup', [Controller\Site::class, 'signup']);
 Route::add(['GET', 'POST'], '/login', [Controller\Site::class, 'login']);
 Route::add('GET', '/logout', [Controller\Site::class, 'logout']);
+Route::add("GET", '/getAverageAge', [Controller\Site::class, 'getAverageAge']);

+ 7 - 5
views/layouts/main.php

@@ -5,6 +5,7 @@
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
     <meta http-equiv="X-UA-Compatible" content="ie=edge">
+    <link rel="stylesheet" href="../../public/css/style.css">
     <title>Pop it MVC</title>
 </head>
 
@@ -13,14 +14,15 @@
         <nav>
             <a href="<?= app()->route->getUrl('/hello') ?>">Главная</a>
             <?php
-            if (!app()->auth::check()) :
-            ?>
+            if (!app()->auth::check()) : ?>
                 <a href="<?= app()->route->getUrl('/login') ?>">Вход</a>
                 <a href="<?= app()->route->getUrl('/signup') ?>">Регистрация</a>
             <?php
-            else :
-            ?>
-                <a href="<?= app()->route->getUrl('/logout') ?>">Выход (<?= app()->auth::user()->name ?>)</a>
+            else : ?>
+                <div class="logout">
+                    <span>Здравствуйте, <?= app()->auth::user()->first_name ?></span>
+                    <a href="<?= app()->route->getUrl('/logout') ?>">Выход</a>
+                </div>
             <?php
             endif;
             ?>

+ 4 - 1
views/site/hello.php

@@ -1 +1,4 @@
-<h2><?= $message ?? ''; ?></h2>
+<div class="get-average-age">
+    <a href="<?= app()->route->getUrl('/getAverageAge') ?>">Подсчитать средний возраст сотрудников</a>
+    <p><?= $age ?? '' ?></p>  
+</div>

+ 12 - 8
views/site/login.php

@@ -1,13 +1,17 @@
 <h2>Авторизация</h2>
-<h3><?= $message ?? ''; ?></h3>
 
 <h3><?= app()->auth->user()->name ?? ''; ?></h3>
 <?php
-if (!app()->auth::check()):
-   ?>
-   <form method="post">
-       <label>Логин <input type="text" name="login"></label>
-       <label>Пароль <input type="password" name="password"></label>
-       <button>Войти</button>
-   </form>
+if (!app()->auth::check()) :
+?>
+    <form method="post">
+        <div class="form">
+            <h1>Вход</h1>
+            <input type="text" name="login" required placeholder="Логин">
+            <input type="password" name="password" required placeholder="Пароль">
+            <button>Войти</button>
+            <p><?= $message ?? ''; ?></p>
+
+        </div>
+    </form>
 <?php endif;

+ 33 - 4
views/site/signup.php

@@ -1,8 +1,37 @@
 <h2>Регистрация нового пользователя</h2>
 <h3><?= $message ?? ''; ?></h3>
 <form method="post">
-   <label>Имя <input type="text" name="name"></label>
-   <label>Логин <input type="text" name="login"></label>
-   <label>Пароль <input type="password" name="password"></label>
-   <button>Зарегистрироваться</button>
+   <div class="form">
+      <h1>Регистрация</h1>
+      <input type="text" name="login" placeholder="Логин" required>
+      <input type="text" name="password" placeholder="Пароль" required>
+      <input type="text" name="password2" placeholder="Повтор пароля" required>
+      <input type="text" name="first_name" placeholder="Имя" required>
+      <input type="text" name="last_name" placeholder="Фамилия" required>
+      <input type="text" name="middle_name" placeholder="Отчество" required>
+
+      <select name="gender" id="" required>
+         <option value="fake">Пол</option>
+         <option value="Мужской">Мужской</option>
+         <option value="Женский">Женский</option>
+      </select>
+
+      <input type="text" name="post" placeholder="Должность" required>
+      <input type="text" name="home_address" placeholder="Адрес прописки" required>
+      <label for="birth_date">Дата рождения</label>
+      <input type="date" name="birth_date" placeholder="Дата рождения" id="birth_date" required>
+
+      <select name="state" id="" required>
+         <option value="fake" selected>Штат</option>
+         <?php
+
+         foreach ($states as $state) { ?>
+            <option value=<?= $state->id ?>><?= $state->name ?></option> <?php
+         } ?>
+         
+      </select>
+
+      <button>Зарегистрироваться</button>
+      <?= $error ?? '' ?>
+   </div>
 </form>