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

APinyansky/hw16 #413

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,14 @@
# PHP2021
# PHP2021

## Домашняя работа № 16. Очереди

### Запуск приложения

Отправка сообщений в очередь через форму по адресу `http://otus.local/index.php`

Запуск обработчика сообщений через кнопку по адресу `http://otus.local/consume.php`

Для обработчика необходимо опеределить почтовые переменные в env файле:
* EMAIL_HOST
* EMAIL_USER
* EMAIL_PASS
10 changes: 10 additions & 0 deletions code/app.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

require_once('vendor/autoload.php');

try {
$app = new App\Application();
$app->run();
} catch (Exception $e) {
App\Infrastructure\Response::generateBadRequestResponse($e->getMessage());
}
27 changes: 27 additions & 0 deletions code/app_src/Application.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace App;

use App\Infrastructure\RequestValidator;
use App\Infrastructure\RequestHandler;
use Exception;

class Application
{
private RequestHandler $handler;

public function __construct()
{
try {
$request = RequestValidator::validateRequest($_POST);
$this->handler = new RequestHandler($request);
} catch (\Exception $e) {
throw new \Exception($e->getMessage());
}
}

public function run(): void
{
$this->handler->execute();
}
}
21 changes: 21 additions & 0 deletions code/app_src/Application/Adapters/RabbitAdapter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace App\Application\Adapters;

use PhpAmqpLib\Connection\AMQPStreamConnection;
use App\Application\Interfaces\QueueInterface;

class RabbitAdapter implements QueueInterface
{
public AMQPStreamConnection $connection;

public function __construct()
{
$this->connection = new AMQPStreamConnection(
getenv('RABBITMQ_DEFAULT_NAME'),
getenv('RABBITMQ_DEFAULT_PORT'),
getenv('RABBITMQ_DEFAULT_USER'),
getenv('RABBITMQ_DEFAULT_PASS')
);
}
}
9 changes: 9 additions & 0 deletions code/app_src/Application/Interfaces/BankServiceInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace App\Application\Interfaces;


interface BankServiceInterface
{
public function getUserData();
}
10 changes: 10 additions & 0 deletions code/app_src/Application/Interfaces/ConsumerInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace App\Application\Interfaces;

interface ConsumerInterface
{
public function runFromQueue(string $queueName): void;

public function closeConnection(): void;
}
8 changes: 8 additions & 0 deletions code/app_src/Application/Interfaces/MailAgentInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace App\Application\Interfaces;

interface MailAgentInterface
{
public function send(string $to, string $subject, string $body): bool;
}
10 changes: 10 additions & 0 deletions code/app_src/Application/Interfaces/PublisherInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace App\Application\Interfaces;

interface PublisherInterface
{
public function addToQueue(array $request, string $queueName): string;

public function closeConnection(): void;
}
8 changes: 8 additions & 0 deletions code/app_src/Application/Interfaces/QueueInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace App\Application\Interfaces;

interface QueueInterface
{

}
39 changes: 39 additions & 0 deletions code/app_src/Domain/BankStatement.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace App\Domain;

class BankStatement
{
private string $dateFrom;
private string $dateTo;
private string $clientId;
private string $clientMail;

public function __construct(string $dateFrom, string $dateto, string $clientId, string $clientMail)
{
$this->dateFrom = $dateFrom;
$this->dateTo = $dateto;
$this->clientId = $clientId;
$this->clientMail = $clientMail;
}

public function getDateFrom(): string
{
return $this->dateFrom;
}

public function getDateTo(): string
{
return $this->dateTo;
}

public function getClientId(): string
{
return $this->clientId;
}

public function getClientMail(): string
{
return $this->clientMail;
}
}
27 changes: 27 additions & 0 deletions code/app_src/Helpers/AppHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace App\Helpers;

use App\Infrastructure\BankService;
use App\Infrastructure\Consumer;
use App\Infrastructure\Publisher;
use App\Infrastructure\MailAgent;
use App\Application\Interfaces\QueueInterface;
use PHPMailer\PHPMailer\PHPMailer;

class AppHelper
{
public static function createPublisher(QueueInterface $adapter): Publisher
{
return new Publisher($adapter->connection);
}

public static function createConsumer(QueueInterface $adapter): Consumer
{
return new Consumer(
$adapter->connection,
new BankService(),
new MailAgent(new PHPMailer())
);
}
}
64 changes: 64 additions & 0 deletions code/app_src/Infrastructure/BankService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

namespace App\Infrastructure;

use App\Domain\BankStatement;
use App\Application\Interfaces\BankServiceInterface;

class BankService implements BankServiceInterface
{

private BankStatement $bankStatement;
private array $requiredStatementFields = [
'date_from',
'date_to',
'client_id',
'client_email',
];

public function setBankStatement(string $userData): void
{
$statement = json_decode($userData, true);

if ($this->validateStatementData($statement)) {
throw new Exception('Not enough data for request');
}

$this->bankStatement = new BankStatement(
$statement['date_from'],
$statement['date_to'],
$statement['client_id'],
$statement['client_email']
);
}

public function validateStatementData(array $data): bool
{
if (is_null($data)) {
return false;
}

foreach ($this->requiredStatementFields as $field){
if (!in_array($field, $data)) {
return false;
}
}

return true;
}

public function getUserData(): array
{
if (isset($this->bankStatement)) {
//некоторая выборка данных за указанный пользователем период
$someClientInfo = range(0,100);
shuffle($someClientInfo);
return [
'client_mail' => $this->bankStatement->getClientMail(),
'client_info' => json_encode($someClientInfo)
];
} else {
throw new Exception('Empty statement');
}
}
}
88 changes: 88 additions & 0 deletions code/app_src/Infrastructure/Consumer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php

namespace App\Infrastructure;

use App\Application\Interfaces\BankServiceInterface;
use App\Application\Interfaces\ConsumerInterface;
use App\Application\Interfaces\MailAgentInterface;
use PhpAmqpLib\Channel\AMQPChannel;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use Closure;
use Exception;

class Consumer implements ConsumerInterface
{
private AMQPStreamConnection $connection;
private AMQPChannel $channel;
private BankServiceInterface $service;
private MailAgentInterface $mailAgent;

public function __construct(
AMQPStreamConnection $connection,
BankServiceInterface $service,
MailAgentInterface $mailAgent
)
{
$this->connection = $connection;
$this->channel = $connection->channel();
$this->service = $service;
$this->mailAgent = $mailAgent;
}

public function runFromQueue(string $queueName): void
{
$this->channel->queue_declare(
$queueName,
false,
true,
false,
false
);

$this->channel->basic_qos(null, 1, null);
$this->channel->basic_consume(
$queueName,
'',
false,
false,
false,
false,
$this->onConsume()
);

while(count($this->channel->callbacks)) {
$this->channel->wait();
}

$this->closeConnection();
}

public function closeConnection(): void
{
$this->channel->close();
$this->connection->close();
}

private function onConsume(): Closure
{
return function (AMQPMessage $request): void {
$request->ack();
$this->service->setBankStatement($request->getBody());

try {
$userData = $this->service->getUserData();

if (!empty($userData)) {
$this->mailAgent->send(
$userData['client_mail'],
'Bank statement',
$userData['client_info']
);
}
} catch (Exception $e) {
throw new Exception('Error while consuming message from queue');
}
};
}
}
35 changes: 35 additions & 0 deletions code/app_src/Infrastructure/MailAgent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace App\Infrastructure;

use App\Application\Interfaces\MailAgentInterface;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;

class MailAgent implements MailAgentInterface
{
private PHPMailer $mailer;

public function __construct(PHPMailer $mailer)
{
$this->mailer = $mailer;
$this->mailer->isSMTP();
$this->mailer->Host = getenv('EMAIL_HOST');
$this->mailer->SMTPAuth = true;
$this->mailer->Username = getenv('EMAIL_USER');
$this->mailer->Password = getenv('EMAIL_PASS');
$this->mailer->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$this->mailer->Port = 465;
}

public function send(string $to, string $subject, string $body): bool
{
$this->mailer->setFrom(getenv('EMAIL_USER'), 'Mailer');
$this->mailer->addAddress($to);
$this->mailer->isHTML(true);
$this->mailer->Subject = $subject;
$this->mailer->Body = $body;

return $this->mailer->send();
}
}
Loading