Skip to content

Commit

Permalink
fix templates
Browse files Browse the repository at this point in the history
  • Loading branch information
Smol-An committed Jan 28, 2024
1 parent 5c53eb6 commit 5c74d43
Show file tree
Hide file tree
Showing 5 changed files with 99 additions and 98 deletions.
132 changes: 61 additions & 71 deletions public/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,35 @@
use Carbon\Carbon;
use App\Connection;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\TransferException;
use DiDom\Document;

session_start();

$container = new Container();
$container->set('renderer', function () {
return new \Slim\Views\PhpRenderer(__DIR__ . '/../templates');
});

$app = AppFactory::createFromContainer($container);
$app->addErrorMiddleware(true, true, true);

$container->set('router', $app->getRouteCollector()->getRouteParser());

$container->set('flash', function () {
return new \Slim\Flash\Messages();
});
$container->set('connection', function () {
$conn = new App\Connection();
return $conn->connect();
});

$app = AppFactory::createFromContainer($container);
$app->addErrorMiddleware(true, true, true);

$router = $app->getRouteCollector()->getRouteParser();
$container->set('renderer', function () use ($container) {
$templateVariables = [
'router' => $container->get('router'),
'flash' => $container->get('flash')->getMessages()
];
return new \Slim\Views\PhpRenderer(__DIR__ . '/../templates', $templateVariables);
});

$app->get('/', function ($request, $response) {
return $this->get('renderer')->render($response, 'home.phtml');
Expand Down Expand Up @@ -66,7 +72,6 @@

$app->get('/urls/{id}', function ($request, $response, $args) {
$id = $args['id'];
$flash = $this->get('flash')->getMessages();

$allIdData = $this->get('connection')
->query('SELECT id FROM urls')
Expand All @@ -90,55 +95,52 @@
'id' => $urlData['id'],
'name' => $urlData['name'],
'created_at' => $urlData['created_at'],
'urlChecks' => $urlChecksData,
'flash' => $flash
'urlChecks' => $urlChecksData
];
return $this->get('renderer')->render($response, 'urls/show.phtml', $params);
})->setName('url');

$app->post('/urls', function ($request, $response) use ($router) {
$app->post('/urls', function ($request, $response) {
$url = $request->getParsedBodyParam('url');

$errors = [];
$v = new Validator(['name' => $url['name']]);
$v->rule('required', 'name')->rule('lengthMax', 'name', 255)->rule('url', 'name');

if (empty($url['name'])) {
$errors['name'] = 'URL не должен быть пустым';
} elseif (!$v->validate()) {
$errors['name'] = 'Некорректный URL';
$v = new Validator(['url_name' => $url['name']]);
$v->rule('required', 'url_name')->message('URL не должен быть пустым');
$v->rule('lengthMax', 'url_name', 255)->message('URL превышает 255 символов');
$v->rule('url', 'url_name')->message('Некорректный URL');

if (!$v->validate()) {
$params = [
'url' => $url['name'],
'errors' => $v->errors()
];
return $this->get('renderer')->render($response->withStatus(422), 'home.phtml', $params);
}

if (empty($errors['name'])) {
$parsedUrl = parse_url(strtolower($url['name']));
$name = "{$parsedUrl['scheme']}://{$parsedUrl['host']}";

$urlIdQuery = 'SELECT id FROM urls WHERE name = :name';
$urlIdStmt = $this->get('connection')->prepare($urlIdQuery);
$urlIdStmt->execute([':name' => $name]);
$urlId = $urlIdStmt->fetch();
$parsedUrl = parse_url(strtolower($url['name']));
$name = "{$parsedUrl['scheme']}://{$parsedUrl['host']}";

if (!empty($urlId)) {
$this->get('flash')->addMessage('success', 'Страница уже существует');
return $response->withRedirect($router->urlFor('url', ['id' => $urlId['id']]));
}
$urlIdQuery = 'SELECT id FROM urls WHERE name = :name';
$urlIdStmt = $this->get('connection')->prepare($urlIdQuery);
$urlIdStmt->execute([':name' => $name]);
$urlId = $urlIdStmt->fetch();

$created_at = Carbon::now();
if (!empty($urlId)) {
$this->get('flash')->addMessage('success', 'Страница уже существует');
return $response->withRedirect($this->get('router')->urlFor('url', ['id' => $urlId['id']]));
}

$newUrlQuery = 'INSERT INTO urls(name, created_at) VALUES(:name, :created_at)';
$newUrlStmt = $this->get('connection')->prepare($newUrlQuery);
$newUrlStmt->execute([':name' => $name, ':created_at' => $created_at]);
$created_at = Carbon::now();

$id = $this->get('connection')->lastInsertId();
$this->get('flash')->addMessage('success', 'Страница успешно добавлена');
return $response->withRedirect($router->urlFor('url', ['id' => $id]));
}
$newUrlQuery = 'INSERT INTO urls(name, created_at) VALUES(:name, :created_at)';
$newUrlStmt = $this->get('connection')->prepare($newUrlQuery);
$newUrlStmt->execute([':name' => $name, ':created_at' => $created_at]);

$params = ['errors' => $errors];
return $this->get('renderer')->render($response->withStatus(422), 'home.phtml', $params);
$id = $this->get('connection')->lastInsertId();
$this->get('flash')->addMessage('success', 'Страница успешно добавлена');
return $response->withRedirect($this->get('router')->urlFor('url', ['id' => $id]));
});

$app->post('/urls/{url_id}/checks', function ($request, $response, $args) use ($router) {
$app->post('/urls/{url_id}/checks', function ($request, $response, $args) {
$url_id = $args['url_id'];

$urlNameQuery = 'SELECT name FROM urls WHERE id = :id';
Expand All @@ -149,38 +151,26 @@
$client = new Client();

try {
$res = $client->request('GET', $urlName['name']);
$res = $client->request('GET', $urlName['name'], ['allow_redirects' => false]);
$this->get('flash')->addMessage('success', 'Страница успешно проверена');
$status_code = $res->getStatusCode();
} catch (ConnectException $e) {
$this->get('flash')->addMessage('failure', 'Произошла ошибка при проверке, не удалось подключиться');
return $response->withRedirect($router->urlFor('url', ['id' => $url_id]));
} catch (RequestException $e) {
} catch (ClientException $e) {
$res = $e->getResponse();
$this->get('flash')->addMessage('warning', 'Проверка была выполнена успешно, но сервер ответил c ошибкой');
return $response->withRedirect($this->get('router')->urlFor('url', ['id' => $url_id]));
} catch (ServerException $e) {
$res = $e->getResponse();
$status_code = !is_null($res) ? $res->getStatusCode() : null;
$check_created_at = Carbon::now();
$newCheckQuery = 'INSERT INTO url_checks(
url_id,
status_code,
created_at
) VALUES(
:url_id,
:status_code,
:check_created_at
)';
$newCheckStmt = $this->get('connection')->prepare($newCheckQuery);
$newCheckStmt->execute([
':url_id' => $url_id,
':status_code' => $status_code,
':check_created_at' => $check_created_at
]);
$this->get('flash')->addMessage('warning', 'Проверка была выполнена успешно, но сервер ответил c ошибкой');
return $response->withRedirect($router->urlFor('url', ['id' => $url_id]));
return $response->withRedirect($this->get('router')->urlFor('url', ['id' => $url_id]));
} catch (ConnectException $e) {
$this->get('flash')->addMessage('failure', 'Произошла ошибка при проверке, не удалось подключиться');
return $response->withRedirect($this->get('router')->urlFor('url', ['id' => $url_id]));
} catch (TransferException $e) {
$this->get('flash')->addMessage('failure', $e->getMessage());
return $response->withRedirect($router->urlFor('url', ['id' => $url_id]));
$this->get('flash')->addMessage('failure', 'Упс что-то пошло не так');
return $response->withRedirect($this->get('router')->urlFor('url', ['id' => $url_id]));
}

$status_code = $res->getStatusCode();

$document = new Document((string) $res->getBody());
$h1 = $document->first('h1') ? mb_substr(optional($document->first('h1'))->text(), 0, 255) : '';
$title = $document->first('title') ? mb_substr(optional($document->first('title'))->text(), 0, 255) : '';
Expand Down Expand Up @@ -215,7 +205,7 @@
':check_created_at' => $check_created_at
]);

return $response->withRedirect($router->urlFor('url', ['id' => $url_id]), 302);
return $response->withRedirect($this->get('router')->urlFor('url', ['id' => $url_id]));
});

$app->run();
12 changes: 9 additions & 3 deletions templates/header.phtml
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,23 @@
<body>
<nav class="navbar navbar-expand-lg bg-dark ps-1" data-bs-theme="dark">
<div class="container-fluid">
<a class="navbar-brand" href="/">Анализатор страниц</a>
<a class="navbar-brand" href="<?= $router->urlFor('home') ?>">Анализатор страниц</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link" aria-current="page" href="/">Главная</a>
<a class="nav-link"
href="<?= $router->urlFor('home') ?>">
Главная
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/urls">Сайты</a>
<a class="nav-link"
href="<?= $router->urlFor('urls') ?>">
Сайты
</a>
</li>
</ul>
</div>
Expand Down
11 changes: 6 additions & 5 deletions templates/home.phtml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?php include(__DIR__ . '/header.phtml'); ?>
<?php include(__DIR__ . '/header.phtml'); ?>

<main class="flex-grow-1">
<div class="container my-3">
Expand All @@ -10,18 +10,19 @@
<input
type="text"
name="url[name]"
value="<?= htmlspecialchars($url ?? '') ?>"
class="form-control form-control-lg
<?php if (isset($errors['name'])) : ?>
<?php if (isset($errors['url_name'])) : ?>
is-invalid
<?php endif ?>"
aria-describedby="validationFeedback"
placeholder="https://www.example.com">
<?php if (isset($errors['name'])) : ?>
<div id="validationFeedback" class="invalid-feedback"><?= htmlspecialchars($errors['name']) ?></div>
<?php if (isset($errors['url_name'])) : ?>
<div id="validationFeedback" class="invalid-feedback"><?= $errors['url_name'][0] ?></div>
<?php endif ?>
</div>
<div class="col-4">
<input type="submit" class="btn btn-primary btn-lg px-5" value="ПРОВЕРИТЬ">
<input type="submit" class="btn btn-primary btn-lg px-5 text-uppercase" value="Проверить">
</div>
</form>
</div>
Expand Down
14 changes: 9 additions & 5 deletions templates/urls/list.phtml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?php include(__DIR__ . '/../header.phtml'); ?>
<?php include(__DIR__ . '/../header.phtml'); ?>

<main>
<div class="container mt-3">
Expand All @@ -13,10 +13,14 @@
</tr>
<?php foreach ($data as $url) : ?>
<tr>
<td><?= htmlspecialchars($url['id']) ?></td>
<td><a href="/urls/<?= $url['id'] ?>"><?= htmlspecialchars($url['name']) ?></a></td>
<td><?= isset($url['last_check_created_at']) ? htmlspecialchars($url['last_check_created_at']) : '' ?></td>
<td><?= isset($url['status_code']) ? htmlspecialchars($url['status_code']) : '' ?></td>
<td><?= $url['id'] ?></td>
<td>
<a href="<?= $router->urlFor('url', ['id' => $url['id']]) ?>">
<?= $url['name'] ?>
</a>
</td>
<td><?= $url['last_check_created_at'] ?? '' ?></td>
<td><?= $url['status_code'] ?? '' ?></td>
</tr>
<?php endforeach ?>
</tbody>
Expand Down
28 changes: 14 additions & 14 deletions templates/urls/show.phtml
Original file line number Diff line number Diff line change
@@ -1,36 +1,36 @@
<?php include(__DIR__ . '/../header.phtml'); ?>
<?php include(__DIR__ . '/../header.phtml'); ?>

<div>
<?php if (isset($flash['success'])) : ?>
<?php foreach ($flash['success'] as $message) : ?>
<div class="alert alert-success" role="alert"><?= htmlspecialchars($message) ?></div>
<div class="alert alert-success" role="alert"><?= $message ?></div>
<?php endforeach ?>
<?php elseif (isset($flash['warning'])) : ?>
<?php foreach ($flash['warning'] as $message) : ?>
<div class="alert alert-warning" role="alert"><?= htmlspecialchars($message) ?></div>
<div class="alert alert-warning" role="alert"><?= $message ?></div>
<?php endforeach ?>
<?php elseif (isset($flash['failure'])) : ?>
<?php foreach ($flash['failure'] as $message) : ?>
<div class="alert alert-danger" role="alert"><?= htmlspecialchars($message) ?></div>
<div class="alert alert-danger" role="alert"><?= $message ?></div>
<?php endforeach ?>
<?php endif ?>
</div>
<main>
<div class="container mt-3">
<h1>Сайт: <?= htmlspecialchars($name) ?></h1>
<h1>Сайт: <?= $name ?></h1>
<table class="table table-hover table-bordered" data-test="url">
<tbody>
<tr>
<th>ID</th>
<td><?= htmlspecialchars($id) ?></td>
<td><?= $id ?></td>
</tr>
<tr>
<th>Имя</th>
<td><?= htmlspecialchars($name) ?></td>
<td><?= $name ?></td>
</tr>
<tr>
<th>Дата создания</th>
<td><?= htmlspecialchars($created_at) ?></td>
<td><?= $created_at ?></td>
</tr>
</tbody>
</table>
Expand All @@ -50,12 +50,12 @@
</tr>
<?php foreach ($urlChecks as $check) : ?>
<tr>
<td><?= htmlspecialchars($check['id']) ?></td>
<td><?= isset($check['status_code']) ? htmlspecialchars($check['status_code']) : '' ?></td>
<td><?= isset($check['h1']) ? htmlspecialchars($check['h1']) : '' ?></td>
<td><?= isset($check['title']) ? htmlspecialchars($check['title']) : '' ?></td>
<td><?= isset($check['description']) ? htmlspecialchars($check['description']) : '' ?></td>
<td><?= htmlspecialchars($check['created_at']) ?></td>
<td><?= $check['id'] ?></td>
<td><?= $check['status_code'] ?? '' ?></td>
<td><?= $check['h1'] ?? '' ?></td>
<td><?= $check['title'] ?? '' ?></td>
<td><?= $check['description'] ?? '' ?></td>
<td><?= $check['created_at'] ?></td>
</tr>
<?php endforeach ?>
</tbody>
Expand Down

0 comments on commit 5c74d43

Please sign in to comment.