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

hw4 #1106

Open
wants to merge 2 commits into
base: KRudenko/main
Choose a base branch
from
Open

hw4 #1106

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: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
.idea/
/vendor/
/code/vendor/
.DS_Store
.AppleDouble
.LSOverride
86 changes: 84 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,85 @@
# PHP_2024
# Инструкция по установке и запуску приложения

https://otus.ru/lessons/razrabotchik-php/?utm_source=github&utm_medium=free&utm_campaign=otus
## Установка и запуск

1. Убедитесь, что у вас установлен Docker и Docker Compose.
2. Клонируйте репозиторий на ваш компьютер:

```bash
git clone -b KRudenko/hw4 [email protected]:otusteamedu/PHP_2024.git
```

3. Перейдите в каталог с репозиторием:

```bash
cd PHP_2024
```

4. Соберите и запустите контейнеры Docker с помощью Docker Compose:

```bash
docker-compose up -d
```

# Проверка работы кластера

Каждый раз делая запрос `localhost`, будет выводиться имя хоста:

```shell
Hello from hostname php-fpm2!
```

# Проверка работы скобок

## Успешный запрос

```shell
curl -X POST -w "\nHTTP Code: %{http_code}" localhost/string -d "string=(()()()())((((()()()))(()()()(((()))))))"
```

## Неуспешный запрос

```shell
curl -X POST -w "\nHTTP Code: %{http_code}" localhost/string -d "string=(()()()()))((((()()()))(()()()(((()))))))"
```

## Пустой запрос

```shell
curl -X POST -w "\nHTTP Code: %{http_code}" localhost/string -d "string"
```

## Неверный метод

```shell
curl -X GET -w "\nHTTP Code: %{http_code}" localhost/string -d "string"
```

# Проверка работы сессий

## Из браузера или postman

Запросите адрес `localhost/session` несколько раз подряд и вы увидите,
что в каждом запросе сессия остается неизменной, а счетчик увеличивается.

## Из консоли

Выполните запрос, что бы получить id сессии:

```shell
curl localhost/session
```

Затем подставьте полученный id сессии в следующий запрос вместо `{SESSION_ID}`.
Каждый раз выполняя запрос, вы увидите как увеличивается счетчик:

```shell
curl localhost/session -H 'Cookie: PHPSESSID={SESSION_ID}'
```

## Контейнер докера

```shell
docker exec -it otus-redis redis-cli
keys *
```
11 changes: 11 additions & 0 deletions code/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"name": "krudenko/hw4",
"description": "Otus Home Work 4",
"type": "project",
"autoload": {
"psr-4": {
"KRudenko\\Otus\\": "src/"
}
},
"require": {}
}
18 changes: 18 additions & 0 deletions code/composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions code/entrypoint.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/bin/bash

composer install

php-fpm
8 changes: 8 additions & 0 deletions code/public/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

require __DIR__ . '/../vendor/autoload.php';

use KRudenko\Otus\Core\App;

$app = new App();
echo $app->run();
33 changes: 33 additions & 0 deletions code/src/Controller/IndexController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace KRudenko\Otus\Controller;

use KRudenko\Otus\Service\SessionService;
use KRudenko\Otus\Service\StringService;

readonly class IndexController
{
private StringService $stringService;
private SessionService $sessionService;

public function __construct()
{
$this->stringService = new StringService();
$this->sessionService = new SessionService();
}

public function handleStringRequest(): string
{
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
return "Данные не были отправлены методом POST.";
}

return $this->stringService->processString();
}

public function handleSessionRequest(): string
{
return $this->sessionService->processSession();
}
}
26 changes: 26 additions & 0 deletions code/src/Core/App.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace KRudenko\Otus\Core;

use KRudenko\Otus\Service\RequestHandler;

readonly class App
{
private RequestHandler $handler;

public function __construct()
{
$this->handler = new RequestHandler();
}

public function run(): string
{
$this->startSession();
return $this->handler->handle();
}

public function startSession(): void
{
session_start();
}
}
27 changes: 27 additions & 0 deletions code/src/Service/RequestHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace KRudenko\Otus\Service;

use KRudenko\Otus\Controller\IndexController;

readonly class RequestHandler
{
private IndexController $controller;

public function __construct()
{

$this->controller = new IndexController();
}

public function handle(): string
{
$requestUri = $_SERVER['REQUEST_URI'];
return match ($requestUri) {
'/string' => $this->controller->handleStringRequest(),
'/session' => $this->controller->handleSessionRequest(),
'/' => sprintf('Hello from hostname %s!', gethostname()),
default => 'Доступны только адреса /string и /session',
};
}
}
16 changes: 16 additions & 0 deletions code/src/Service/SessionService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace KRudenko\Otus\Service;

class SessionService
{
public function processSession(): string
{
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
}
$_SESSION['count']++;
$sessionId = session_id();
return "Session ID: $sessionId" . PHP_EOL . "Session count: " . $_SESSION['count'];
}
}
42 changes: 42 additions & 0 deletions code/src/Service/StringService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

namespace KRudenko\Otus\Service;

class StringService
{
public function processString(): string
{
$string = $_POST['string'] ?? null;

if (empty($string)) {
http_response_code(400);
return "Отправлена пустая строка.";
}

$ans = $this->calculateBrackets($string);

if ($ans === 0) {
http_response_code(200);
return "Строка корректна";
} else {
http_response_code(400);
return "Строка не корректна";
}
}

public function calculateBrackets(string $string): int
{
$ans = 0;
foreach (str_split($string) as $char) {
if ($char === '(') {
$ans++;
} else {
$ans--;
}
if ($ans === -1) {
break;
}
}
return $ans;
}
}
Loading
Loading