Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
dersonsena committed Sep 27, 2021
2 parents 491a4b7 + 3d40c7f commit 50bf0a1
Show file tree
Hide file tree
Showing 34 changed files with 1,252 additions and 214 deletions.
19 changes: 19 additions & 0 deletions config/dependencies.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

declare(strict_types=1);

use App\Adapter\Repository\Database\DbLongUrlRepository;
use App\Domain\Repository\LongUrlRepository;
use App\Shared\Adapter\Contracts\DatabaseOrm;
use App\Shared\Adapter\Contracts\UuidGenerator;
use App\Shared\Infra\PdoOrm;
use App\Shared\Infra\RamseyUiidAdapter;
use DI\ContainerBuilder;
use Odan\Session\Middleware\SessionMiddleware;
use Odan\Session\PhpSession;
Expand All @@ -24,5 +30,18 @@
$storage = [];
return new Messages($storage);
},
DatabaseOrm::class => function (ContainerInterface $c) {
return new PdoOrm($c->get('db'));
},
UuidGenerator::class => function (ContainerInterface $c) {
return new RamseyUiidAdapter();
},
LongUrlRepository::class => function (ContainerInterface $c) {
return new DbLongUrlRepository(
$c->get(DatabaseOrm::class),
$c->get(RamseyUiidAdapter::class),
$c->get('config')
);
},
]);
};
2 changes: 1 addition & 1 deletion config/middleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
declare(strict_types=1);

use Slim\App;
use App\Middleware\SessionMiddleware;
use App\Adapter\Middleware\SessionMiddleware;
use Slim\Views\TwigMiddleware;

return function (App $app) {
Expand Down
6 changes: 3 additions & 3 deletions config/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

declare(strict_types=1);

use App\Controllers\AccessUrlController;
use App\Controllers\HomeController;
use App\Controllers\ShortenUrlController;
use App\Adapter\Controllers\AccessUrlController;
use App\Adapter\Controllers\HomeController;
use App\Adapter\Controllers\ShortenUrlController;
use Slim\App;
use Slim\Routing\RouteCollectorProxy;

Expand Down
31 changes: 22 additions & 9 deletions public_html/js/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,19 @@ $(document).ready(function () {

if (urlHistory) {
urlHistory = JSON.parse(urlHistory);

urlHistory = urlHistory.map(row => {
if (!row.hasOwnProperty('huge')) return row;
return {
longUrl: row.huge,
shortenedUrl: row.shortened,
createdAt: row.created_at,
economyRate: row.economyRate,
};
});

window.localStorage.setItem('url_history', JSON.stringify(urlHistory));

for (let index in urlHistory) {
if (index === '5') break;
$('div.shortened-urls ul').append(getHistoryItemTemplate(urlHistory[index]));
Expand Down Expand Up @@ -58,7 +71,7 @@ $(document).ready(function () {
$.ajax({
url: `${baseUrl}/api/public/shorten`,
type: 'post',
data: { huge_url : $inputUrl.val() },
data: { long_url : $inputUrl.val() },
beforeSend : function() {
$inputUrl.prop('disabled', true);
$btnShorten.prop('disabled', true);
Expand All @@ -85,15 +98,15 @@ $(document).ready(function () {

const $divResult = $('div.shortened-url-result');
$divResult.css('display', 'flex');
$divResult.find('a').attr('href', payload.data.shortened);
$divResult.find('a span.url-text').html(payload.data.shortened);
$divResult.find('a').attr('href', payload.data.shortenedUrl);
$divResult.find('a span.url-text').html(payload.data.shortenedUrl);
$divResult.find('a span.badge').html(`-${payload.data.economyRate}%`);
$divResult.find('button').attr('data-url', payload.data.shortened);
$divResult.find('button').attr('data-url', payload.data.shortenedUrl);
}).fail(function(jqXHR, textStatus, msg) {
if (jqXHR.status === 400) {
const payload = jqXHR.responseJSON;
let message = '';
switch (payload.data.huge_url) {
switch (payload.data.longUrl) {
case 'invalid-url':
message = 'Insira ua URL válida com "http://" ou "https://" para poder encurtar.';
break;
Expand Down Expand Up @@ -132,16 +145,16 @@ $(document).ready(function () {
function getHistoryItemTemplate(data) {
return `
<li>
<div class="long-url" title="${data.huge}">${data.huge.substring(0, 38)}...</div>
<div class="long-url" title="${data.longUrl}">${data.longUrl.substring(0, 38)}...</div>
<div class="short-url">
<div class="link">
<a href="${data.shortened}" target="_blank" title="URL encurtada de ${data.huge}">
${data.shortened}
<a href="${data.shortenedUrl}" target="_blank" title="URL encurtada de ${data.longUrl}">
${data.shortenedUrl}
</a>
</div>
<div class="copy">
<div class="d-grid gap-2">
<button data-url="${data.shortened}" class="btn btn-outline-primary copy-button">
<button data-url="${data.shortenedUrl}" class="btn btn-outline-primary copy-button">
<i class="far fa-copy"></i> Copiar
</button>
</div>
Expand Down
48 changes: 48 additions & 0 deletions src/Adapter/Controllers/AccessUrlController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

declare(strict_types=1);

namespace App\Adapter\Controllers;

use App\Domain\Repository\LongUrlRepository;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\RequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Slim\Views\Twig;

final class AccessUrlController
{
private Twig $view;
private LongUrlRepository $longUrlRepo;

public function __construct(ContainerInterface $container)
{
$this->view = $container->get('view');
$this->longUrlRepo = $container->get(LongUrlRepository::class);
}

public function __invoke(Request $request, Response $response, array $args): Response
{
$url = $this->longUrlRepo->getUrlByPath($args['path']);

if (is_null($url)) {
return $this->view->render($response, 'notfound.html.twig', []);
}

$this->longUrlRepo->registerAccess($url, [
'REMOTE_ADDR' => $_SERVER['REMOTE_ADDR'],
'REMOTE_PORT' => $_SERVER['REMOTE_PORT'],
'SERVER_NAME' => $_SERVER['SERVER_NAME'],
'REQUEST_URI' => $_SERVER['REQUEST_URI'],
'HTTP_HOST' => $_SERVER['HTTP_HOST'],
'HTTP_USER_AGENT' => $_SERVER['HTTP_USER_AGENT']
]);

$newResponse = $response
->withHeader('Content-type', 'application/json')
->withStatus(302)
->withHeader('Location', $url->longUrl->value());

return $newResponse;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,29 @@

declare(strict_types=1);

namespace App\Controllers;
namespace App\Adapter\Controllers;

use PDO;
use App\Domain\Repository\LongUrlRepository;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\RequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Slim\Views\Twig;

final class HomeController
{
private PDO $db;
private Twig $view;
private LongUrlRepository $longUrlRepo;

public function __construct(ContainerInterface $container)
{
$this->db = $container->get('db');
$this->view = $container->get('view');
$this->longUrlRepo = $container->get(LongUrlRepository::class);
}

public function __invoke(Request $request, Response $response, array $args): Response
{
$stmt = $this->db->prepare(trim("
select count(*) as total_urls from urls
union all
select count(*) as total_clicks from urls_logs
"));

$stmt->execute();

[$totalUrls, $totalClicks] = $stmt->fetchAll(PDO::FETCH_COLUMN);

return $this->view->render($response, 'index.html.twig', [
'totalUrls' => ceil($totalUrls),
'totalClicks' => ceil($totalClicks)
]);
$rows = $this->longUrlRepo->countUrlsAndClicks();
return $this->view->render($response, 'index.html.twig', $rows);
}
}
72 changes: 72 additions & 0 deletions src/Adapter/Controllers/ShortenUrlController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

declare(strict_types=1);

namespace App\Adapter\Controllers;

use App\Domain\UseCase\ShortenUrl\InputData;
use App\Domain\UseCase\ShortenUrl\ShortenUrl;
use App\Domain\ValueObject\LongUrlType;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\RequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

final class ShortenUrlController
{
private array $config;
private ShortenUrl $useCase;

public function __construct(ContainerInterface $container)
{
$this->config = $container->get('config');
$this->useCase = $container->get(ShortenUrl::class);
}

public function __invoke(Request $request, Response $response, array $args): Response
{
$contents = $request->getParsedBody();

if (empty($contents) || !array_key_exists('long_url', $contents)) {
$newResponse = $response
->withHeader('Content-type', 'application/json')
->withStatus(400);

$newResponse->getBody()->write(json_encode([
'status' => 'fail',
'data' => ['long_url' => 'missing-param']
]));

return $newResponse;
}

if (empty($contents['long_url'])) {
$newResponse = $response
->withHeader('Content-type', 'application/json')
->withStatus(400);

$newResponse->getBody()->write(json_encode([
'status' => 'fail',
'data' => ['long_url' => 'empty-value']
]));

return $newResponse;
}

$result = $this->useCase->execute(InputData::create([
'longUrl' => $contents['long_url'],
'type' => LongUrlType::TYPE_RANDOM,
'baseUrl' => $this->config['baseUrl'],
]));

$newResponse = $response
->withHeader('Content-type', 'application/json')
->withStatus(200);

$newResponse->getBody()->write(json_encode([
'status' => 'success',
'data' => $result->values()
]));

return $newResponse;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

declare(strict_types=1);

namespace App\Middleware;
namespace App\Adapter\Middleware;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

namespace App\Middleware;
namespace App\Adapter\Middleware;

use Odan\Session\SessionInterface;
use Psr\Http\Message\ResponseInterface;
Expand Down
Loading

0 comments on commit 50bf0a1

Please sign in to comment.