Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

version hw06 #524

Draft
wants to merge 2 commits into
base: NDybnov/main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
MY_PATH_SRC=./src/
NGINX_PORT=8181
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
vendor/
.env
config.ini
69 changes: 67 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,68 @@
# PHP_2023
### Реализация домашнего задания

https://otus.ru/lessons/razrabotchik-php/?utm_source=github&utm_medium=free&utm_campaign=otus
Приложение верификации email

Инструкция по установке, настройки и использованию приложения верификации email.
-- --
#### Настройка

* создание файла конфигурации для запуска docker-контейнеров
```shell
cp ./.env.example ./.env
```

* создание файла конфигурации для использования приложения
```shell
cp ./src/config.ini.example ./src/config.ini
```

* Собрать и запустить docker-контейнеры
```shell
docker-compose up --build
```

* установка composer-зависимостей
```shell
docker exec -ti php-fpm-emails composer install
```

Теперь приложение готово к использованию.
-- --
#### Использование

В браузере открывается главная страница

* примерно с таким содержимом, проверяемый список email указан в файле `config.ini`
```
Emails: [email protected],er@mail.!ru,aa@qq,aa@q,[email protected],[email protected],[email protected]

Message-errors(11):
[filter_var] ~ [er@mail.!ru] :: Incorrect value `er@mail.!ru` by rule `filter_var`.
[reg_exp] ~ [er@mail.!ru] :: Incorrect value `er@mail.!ru` by rule `reg_exp`.
[external_dns_mx] ~ [er@mail.!ru] :: Incorrect value `er@mail.!ru` by rule `external_dns_mx`.
[filter_var] ~ [aa@qq] :: Incorrect value `aa@qq` by rule `filter_var`.
[reg_exp] ~ [aa@qq] :: Incorrect value `aa@qq` by rule `reg_exp`.
[external_dns_mx] ~ [aa@qq] :: Incorrect value `aa@qq` by rule `external_dns_mx`.
[filter_var] ~ [aa@q] :: Incorrect value `aa@q` by rule `filter_var`.
[reg_exp] ~ [aa@q] :: Incorrect value `aa@q` by rule `reg_exp`.
[external_dns_mx] ~ [aa@q] :: Incorrect value `aa@q` by rule `external_dns_mx`.
[external_dns_mx] ~ [[email protected]] :: Incorrect value `[email protected]` by rule `external_dns_mx`.
[external_dns_mx] ~ [[email protected]] :: Incorrect value `[email protected]` by rule `external_dns_mx`.
```

* или указать дополнительный параметр `emails` в get-запросе в браузере
`http://app.local:8181/?emails=aa@qq,aa@q,[email protected],[email protected],[email protected]`
```
Emails: aa@qq,aa@q,[email protected],[email protected],[email protected]

Message-errors(8):
[filter_var] ~ [aa@qq] :: Incorrect value `aa@qq` by rule `filter_var`.
[reg_exp] ~ [aa@qq] :: Incorrect value `aa@qq` by rule `reg_exp`.
[external_dns_mx] ~ [aa@qq] :: Incorrect value `aa@qq` by rule `external_dns_mx`.
[filter_var] ~ [aa@q] :: Incorrect value `aa@q` by rule `filter_var`.
[reg_exp] ~ [aa@q] :: Incorrect value `aa@q` by rule `reg_exp`.
[external_dns_mx] ~ [aa@q] :: Incorrect value `aa@q` by rule `external_dns_mx`.
[external_dns_mx] ~ [[email protected]] :: Incorrect value `[email protected]` by rule `external_dns_mx`.
[external_dns_mx] ~ [[email protected]] :: Incorrect value `[email protected]` by rule `external_dns_mx`.
```
-- --
30 changes: 30 additions & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
version: '3'

services:
nginx-emails:
build:
context: ./nginx
dockerfile: Dockerfile
image: image-nginx-emails
container_name: nginx-emails
ports:
- ${NGINX_PORT}:80
volumes:
- ${MY_PATH_SRC}:/data/app.local
networks:
- network-emails

php-fpm-emails:
build:
context: ./fpm
dockerfile: Dockerfile
image: image-php-fpm-emails
container_name: php-fpm-emails
volumes:
- ${MY_PATH_SRC}:/data/app.local
networks:
- network-emails

networks:
network-emails:
driver: bridge
5 changes: 5 additions & 0 deletions fpm/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
FROM php:8.1.22-fpm-alpine

COPY --from=composer/composer:latest-bin /composer /usr/bin/composer

WORKDIR /data/app.local
11 changes: 11 additions & 0 deletions nginx/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
FROM nginx:1.25.2-alpine3.18

COPY ./hosts/myapp.local.conf /etc/nginx/conf.d/default.conf

WORKDIR /data

VOLUME /data

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]
39 changes: 39 additions & 0 deletions nginx/hosts/myapp.local.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
upstream php-fpm-upstream {
least_conn;
server php-fpm-emails:9000;
}

server {
# указываем 80 порт для соединения
listen 80;
# нужно указать, какому доменному имени принадлежит наш конфиг
server_name app.local;

# задаём корневую директорию
root /data/app.local/public/;

# стартовый файл
index index.php index.html;

# при обращении к статическим файлам логи не нужны, равно как и обращение к fpm
location ~* .(jpg|jpeg|gif|css|png|js|ico|html)$ {
access_log off;
expires max;
}

# помним про единую точку доступа
# все запросы заворачиваются в корневую директорию root на index.php
location / {
try_files $uri $uri/ /index.php?$query_string;
}

# и наконец правило обращения к php-fpm
location ~* .php$ {
try_files $uri = 404;
fastcgi_split_path_info ^(.+.php)(/.+)$;
fastcgi_pass php-fpm-upstream;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
65 changes: 65 additions & 0 deletions src/commands/CheckEmailsCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

declare(strict_types=1);

namespace Ndybnov\Hw06\commands;

use Ndybnov\Hw06\emails\ExternalDnsMxValidateRule;
use Ndybnov\Hw06\emails\FilterVarValidateRule;
use Ndybnov\Hw06\emails\RegExpValidateRule;
use Ndybnov\Hw06\emails\Validator;
use Ndybnov\Hw06\hw\Output;
use Ndybnov\Hw06\hw\ParameterString;
use NdybnovHw03\CnfRead\ConfigStorage;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

class CheckEmailsCommand
{
private string $defaultEmails;

public function __construct()
{
$pathToConfigFile = dirname(__DIR__);
$configStorage = (new ConfigStorage())
->fromDotEnvFile([$pathToConfigFile, 'config.ini']);

$this->defaultEmails = $configStorage->get('default-emails');
}

public function run(Request $request, Response $response): Response
{
$strEmails = (new ParameterString())->getValue($request, '');

if (!strlen($strEmails)) {
$strEmails = $this->defaultEmails;
}

Output::show('Emails: ');
Output::show(strlen($strEmails) ? $strEmails : '[empty]');

if (!strlen($strEmails)) {
return $response->withStatus(200);
}

$validator = new Validator();

$validator->addRule('filter_var', new FilterVarValidateRule());
$validator->addRule('reg_exp', new RegExpValidateRule());
$validator->addRule('external_dns_mx', new ExternalDnsMxValidateRule());

if ($validator->fromString($strEmails)) {
$errors = $validator->getErrors();
Output::lineEnd();
Output::lineEnd();
Output::show('Message-errors(' . count($errors) . '):');
Output::lineEnd();
foreach ($errors as $key => $error) {
Output::show(' ' . $key . ' :: ' . $error);
Output::lineEnd();
}
}

return $response->withStatus(200);
}
}
33 changes: 33 additions & 0 deletions src/commands/MockExternalDnsMxCheckCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);

namespace Ndybnov\Hw06\commands;

use Ndybnov\Hw06\external\ValidateDnsMx;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

class MockExternalDnsMxCheckCommand
{
public function run(Request $request, Response $response): Response
{
try {
$queryParams = $request->getQueryParams();

$strEmail = $queryParams['email'] ?? '';

$isValidEmail = ValidateDnsMx::check($strEmail);
$body = [
'received' => $strEmail,
'info' => $isValidEmail ? 'ok' : 'error',
];

$response->getBody()->write(\json_encode($body, JSON_THROW_ON_ERROR));

return $response->withStatus($isValidEmail ? 200 : 406);
} catch (\Exception $exception) {
throw new $exception($exception->getMessage());
}
}
}
31 changes: 31 additions & 0 deletions src/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"name": "ndybnov/hw06-emails",
"type": "project",
"autoload": {
"psr-4": {
"Ndybnov\\Hw06\\": "."
}
},
"authors": [
{
"name": "DNickolay",
"email": "[email protected]"
}
],
"require": {
"php": ">=8.0",
"ndybnov-hw03/cnf-read": "^1.1.0",
"slim/slim": "^4.12",
"slim/psr7": "^1.6",
"slim/http": "^1.3",
"php-di/php-di": "^7.0",
"friendsofphp/proxy-manager-lts": "^1.0",
"doctrine/annotations": "^2.0",
"laminas/laminas-stdlib": "^3.17",
"ext-curl": "*"
},
"require-dev": {
"roave/security-advisories": "dev-latest"
}
}

Loading