Skip to content

Commit

Permalink
add illuminate, layout
Browse files Browse the repository at this point in the history
  • Loading branch information
Smol-An committed Feb 2, 2024
1 parent 0957baf commit 34dc7c4
Show file tree
Hide file tree
Showing 7 changed files with 109 additions and 115 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@
"slim/flash": "^0.4.0",
"guzzlehttp/guzzle": "^7.0",
"imangazaliev/didom": "^2.0",
"laravel/helpers": "^1.7"
"laravel/helpers": "^1.7",
"illuminate/support": "^10.43"
},
"require-dev": {
"squizlabs/php_codesniffer": "^3.7"
Expand Down
12 changes: 6 additions & 6 deletions composer.lock

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

128 changes: 65 additions & 63 deletions public/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\TransferException;
use DiDom\Document;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;

session_start();

Expand All @@ -41,29 +43,33 @@
$container->set('flash', function () {
return new \Slim\Flash\Messages();
});

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

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

$app->get('/', function ($request, $response) {
return $this->get('renderer')->render($response, 'home.phtml');
})->setName('home');

$app->get('/urls', function ($request, $response) {
$allUrlsData = $this->get('connection')
$allUrls = $this->get('connection')
->query('SELECT id, name FROM urls ORDER BY id DESC')
->fetchAll(PDO::FETCH_ASSOC);

$lastChecksData = $this->get('connection')
$lastChecks = $this->get('connection')
->query('SELECT
url_id,
MAX(created_at) AS last_check_created_at,
Expand All @@ -72,49 +78,47 @@
GROUP BY url_id, status_code')
->fetchAll(PDO::FETCH_ASSOC);

$data = array_map(function ($url) use ($lastChecksData) {
foreach ($lastChecksData as $check) {
if ($url['id'] === $check['url_id']) {
$url['last_check_created_at'] = $check['last_check_created_at'];
$url['status_code'] = $check['status_code'];
}
}
return $url;
}, $allUrlsData);
$urls = collect($allUrls);
$urlChecks = collect($lastChecks)->keyBy('url_id');

$params = ['data' => $data];
return $this->get('renderer')->render($response, 'urls/list.phtml', $params);
})->setName('urls');
$data = $urls->map(function ($url) use ($urlChecks) {
$urlCheck = $urlChecks->firstWhere('url_id', $url['id']);

$app->get('/urls/{id}', function ($request, $response, $args) {
$id = $args['id'];
return [
'id' => $url['id'],
'name' => $url['name'],
'last_check_created_at' => $urlCheck['last_check_created_at'] ?? null,
'status_code' => $urlCheck['status_code'] ?? null,
];
});

$allIdData = $this->get('connection')
->query('SELECT id FROM urls')
->fetchAll(PDO::FETCH_COLUMN);
$params = ['data' => $data];
return $this->get('renderer')->render($response, 'urls/index.phtml', $params);
})->setName('urls.index');

if (!in_array($id, $allIdData)) {
return $this->get('renderer')->render($response->withStatus(404), 'error404.phtml');
}
$app->get('/urls/{id:[0-9]+}', function ($request, $response, $args) {
$id = $args['id'];

$urlDataQuery = 'SELECT * FROM urls WHERE id = :id';
$urlDataStmt = $this->get('connection')->prepare($urlDataQuery);
$urlDataStmt->execute([':id' => $id]);
$urlData = $urlDataStmt->fetch();

if (empty($urlData)) {
return $this->get('renderer')->render($response->withStatus(404), 'error404.phtml');
}

$urlChecksQuery = 'SELECT * FROM url_checks WHERE url_id = :id ORDER BY id DESC';
$urlChecksStmt = $this->get('connection')->prepare($urlChecksQuery);
$urlChecksStmt->execute([':id' => $id]);
$urlChecksData = $urlChecksStmt->fetchAll();

$params = [
'id' => $urlData['id'],
'name' => $urlData['name'],
'created_at' => $urlData['created_at'],
'url' => $urlData,
'urlChecks' => $urlChecksData
];
return $this->get('renderer')->render($response, 'urls/show.phtml', $params);
})->setName('url');
})->setName('urls.show');

$app->post('/urls', function ($request, $response) {
$url = $request->getParsedBodyParam('url');
Expand All @@ -132,36 +136,34 @@
return $this->get('renderer')->render($response->withStatus(422), 'home.phtml', $params);
}

$parsedUrl = parse_url(strtolower($url['name']));
$name = "{$parsedUrl['scheme']}://{$parsedUrl['host']}";
$parsedUrl = parse_url(Str::lower($url['name']));
$urlName = "{$parsedUrl['scheme']}://{$parsedUrl['host']}";

$urlIdQuery = 'SELECT id FROM urls WHERE name = :name';
$urlIdStmt = $this->get('connection')->prepare($urlIdQuery);
$urlIdStmt->execute([':name' => $name]);
$urlIdStmt->execute([':name' => $urlName]);
$urlId = $urlIdStmt->fetch();

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

$created_at = Carbon::now();

$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]);
$newUrlStmt->execute([':name' => $urlName, ':created_at' => Carbon::now()]);

$id = $this->get('connection')->lastInsertId();
$lastInsertId = $this->get('connection')->lastInsertId();
$this->get('flash')->addMessage('success', 'Страница успешно добавлена');
return $response->withRedirect($this->get('router')->urlFor('url', ['id' => $id]));
});
return $response->withRedirect($this->get('router')->urlFor('urls.show', ['id' => $lastInsertId]));
})->setName('urls.store');

$app->post('/urls/{url_id}/checks', function ($request, $response, $args) {
$url_id = $args['url_id'];
$app->post('/urls/{url_id:[0-9]+}/checks', function ($request, $response, $args) {
$urlId = $args['url_id'];

$urlNameQuery = 'SELECT name FROM urls WHERE id = :id';
$urlNameStmt = $this->get('connection')->prepare($urlNameQuery);
$urlNameStmt->execute([':id' => $url_id]);
$urlNameStmt->execute([':id' => $urlId]);
$urlName = $urlNameStmt->fetch();

$client = new Client();
Expand All @@ -172,29 +174,29 @@
} catch (ClientException $e) {
$res = $e->getResponse();
$this->get('flash')->addMessage('warning', 'Проверка была выполнена успешно, но сервер ответил c ошибкой');
return $response->withRedirect($this->get('router')->urlFor('url', ['id' => $url_id]));
return $response->withRedirect($this->get('router')->urlFor('urls.show', ['id' => $urlId]));
} catch (ServerException $e) {
$res = $e->getResponse();
$this->get('flash')->addMessage('warning', 'Проверка была выполнена успешно, но сервер ответил c ошибкой');
return $response->withRedirect($this->get('router')->urlFor('url', ['id' => $url_id]));
return $response->withRedirect($this->get('router')->urlFor('urls.show', ['id' => $urlId]));
} catch (ConnectException $e) {
$this->get('flash')->addMessage('failure', 'Произошла ошибка при проверке, не удалось подключиться');
return $response->withRedirect($this->get('router')->urlFor('url', ['id' => $url_id]));
$this->get('flash')->addMessage('error', 'Произошла ошибка при проверке, не удалось подключиться');
return $response->withRedirect($this->get('router')->urlFor('urls.show', ['id' => $urlId]));
} catch (TransferException $e) {
$this->get('flash')->addMessage('failure', 'Упс что-то пошло не так');
return $response->withRedirect($this->get('router')->urlFor('url', ['id' => $url_id]));
$this->get('flash')->addMessage('error', 'Упс что-то пошло не так');
return $response->withRedirect($this->get('router')->urlFor('urls.show', ['id' => $urlId]));
}

$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) : '';
$description = $document->first('meta[name="description"]')
? mb_substr(optional($document->first('meta[name="description"]'))->getAttribute('content'), 0, 255)
: '';
$statusCode = $res->getStatusCode();
$resBody = (string) $res->getBody();

$check_created_at = Carbon::now();
if (!empty($resBody)) {
$document = new Document($resBody);
$h1 = Str::limit(optional($document->first('h1'))->text(), 250, '(...)');
$title = Str::limit(optional($document->first('title'))->text(), 250, '(...)');
$description = Str::limit(optional($document->first('meta[name="description"]'))
->getAttribute('content'), 250, '(...)');
}

$newCheckQuery = 'INSERT INTO url_checks(
url_id,
Expand All @@ -213,15 +215,15 @@
)';
$newCheckStmt = $this->get('connection')->prepare($newCheckQuery);
$newCheckStmt->execute([
':url_id' => $url_id,
':status_code' => $status_code,
':h1' => $h1,
':title' => $title,
':description' => $description,
':check_created_at' => $check_created_at
':url_id' => $urlId,
':status_code' => $statusCode ?? null,
':h1' => $h1 ?? null,
':title' => $title ?? null,
':description' => $description ?? null,
':check_created_at' => Carbon::now()
]);

return $response->withRedirect($this->get('router')->urlFor('url', ['id' => $url_id]));
});
return $response->withRedirect($this->get('router')->urlFor('urls.show', ['id' => $urlId]));
})->setName('urls.check');

$app->run();
8 changes: 2 additions & 6 deletions templates/home.phtml
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
<?php include(__DIR__ . '/header.phtml'); ?>

<main class="flex-grow-1">
<div class="container my-3">
<div class="p-5 mx-auto col-lg-8 bg-body-tertiary border rounded-3">
<h1 class="display-3">Анализатор страниц</h1>
<p class="lead">Бесплатно проверяйте сайты на SEO пригодность</p>
<form class="row mb-3" action="/urls" method="post" required>
<form class="row mb-3" action="<?= $router->urlFor('urls.store') ?>" method="post" required>
<div class="col-8">
<input
type="text"
Expand All @@ -27,6 +25,4 @@
</form>
</div>
</div>
</main>
</body>
</html>
</main>
22 changes: 20 additions & 2 deletions templates/header.phtml → templates/layout.phtml
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,31 @@
</a>
</li>
<li class="nav-item">
<a class="nav-link <?= $routeName === 'urls' ? 'active' : '' ?>"
href="<?= $router->urlFor('urls') ?>">
<a class="nav-link <?= $routeName === 'urls.index' ? 'active' : '' ?>"
href="<?= $router->urlFor('urls.index') ?>">
Сайты
</a>
</li>
</ul>
</div>
</div>
</nav>
<div>
<?php if (isset($flash['success'])) : ?>
<?php foreach ($flash['success'] as $message) : ?>
<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"><?= $message ?></div>
<?php endforeach ?>
<?php elseif (isset($flash['error'])) : ?>
<?php foreach ($flash['error'] as $message) : ?>
<div class="alert alert-danger" role="alert"><?= $message ?></div>
<?php endforeach ?>
<?php endif ?>
</div>
<?= $content ?>
</body>
</html>

12 changes: 4 additions & 8 deletions templates/urls/list.phtml → templates/urls/index.phtml
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
<?php include(__DIR__ . '/../header.phtml'); ?>

<main>
<div class="container mt-3">
<h1>Сайты</h1>
Expand All @@ -15,17 +13,15 @@
<tr>
<td><?= $url['id'] ?></td>
<td>
<a href="<?= $router->urlFor('url', ['id' => $url['id']]) ?>">
<a href="<?= $router->urlFor('urls.show', ['id' => $url['id']]) ?>">
<?= $url['name'] ?>
</a>
</td>
<td><?= $url['last_check_created_at'] ?? '' ?></td>
<td><?= $url['status_code'] ?? '' ?></td>
<td><?= $url['last_check_created_at'] ?></td>
<td><?= $url['status_code'] ?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
</div>
</main>
</body>
</html>
</main>
Loading

0 comments on commit 34dc7c4

Please sign in to comment.