Skip to content

Commit

Permalink
Cleanup index.php file (#70)
Browse files Browse the repository at this point in the history
  • Loading branch information
antonkomarev authored Sep 3, 2023
1 parent e7bc045 commit bd9bad0
Show file tree
Hide file tree
Showing 2 changed files with 107 additions and 87 deletions.
116 changes: 29 additions & 87 deletions public/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,37 +11,19 @@

declare(strict_types=1);

use Dotenv\Dotenv;
use Dotenv\Exception\InvalidPathException;
use Komarev\GitHubProfileViewsCounter\BadgeImageRendererService;
use Komarev\GitHubProfileViewsCounter\CounterFileRepository;
use Komarev\GitHubProfileViewsCounter\CounterPdoRepository;
use Komarev\GitHubProfileViewsCounter\CounterRepositoryFactory;
use Komarev\GitHubProfileViewsCounter\Username;

$basePath = realpath(__DIR__ . '/..');
$appBasePath = realpath(__DIR__ . '/..');

// Register The Auto Loader
require $basePath . '/vendor/autoload.php';

const REPOSITORY_TYPE_FILE = 'file';
const REPOSITORY_TYPE_PDO = 'pdo';

header('Content-Type: image/svg+xml');
header('Cache-Control: max-age=0, no-cache, no-store, must-revalidate');

$badgeImageRenderer = new BadgeImageRendererService();
require $appBasePath . '/vendor/autoload.php';

array_walk_recursive($_GET, function (&$input) {
$input = htmlspecialchars($input, ENT_NOQUOTES, 'UTF-8', false);
});

$httpUserAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$badgeLabel = $_GET['label'] ?? 'Profile views';
$badgeMessageBackgroundFill = $_GET['color'] ?? 'blue';
$badgeStyle = $_GET['style'] ?? 'flat';
if (!in_array($badgeStyle, ['flat', 'flat-square', 'plastic', 'for-the-badge'])) {
$badgeStyle = 'flat';
}
$username = $_GET['username'] ?? '';
$username = trim($username);

Expand All @@ -50,92 +32,52 @@
exit;
}

$httpUserAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$isGitHubUserAgent = strpos($httpUserAgent, 'github-camo') === 0;

$badgeLabel = $_GET['label'] ?? 'Profile views';
$badgeMessageBackgroundFill = $_GET['color'] ?? 'blue';
$badgeStyle = $_GET['style'] ?? 'flat';
if (!in_array($badgeStyle, ['flat', 'flat-square', 'plastic', 'for-the-badge', 'pixel'])) {
$badgeStyle = 'flat';
}

header('Content-Type: image/svg+xml');
header('Cache-Control: max-age=0, no-cache, no-store, must-revalidate');

$badgeImageRenderer = new BadgeImageRendererService();

try {
$dotEnv = Dotenv::createImmutable($basePath);
$dotEnv->load();

$dotEnv->required([
'REPOSITORY',
]);

$repositoryType = $_ENV['REPOSITORY'];

switch ($repositoryType) {
case REPOSITORY_TYPE_PDO:
$dotEnv->required([
'DB_DRIVER',
'DB_HOST',
'DB_PORT',
'DB_USER',
'DB_PASSWORD',
'DB_NAME',
]);

$dsn = sprintf(
'%s:host=%s;port=%d;dbname=%s',
$_ENV['DB_DRIVER'],
$_ENV['DB_HOST'],
$_ENV['DB_PORT'],
$_ENV['DB_NAME']
);
$dbConnection = new PDO(
$dsn,
$_ENV['DB_USER'],
$_ENV['DB_PASSWORD'],
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
],
);

$counterRepository = new CounterPdoRepository($dbConnection);
break;
case REPOSITORY_TYPE_FILE:
if (!isset($_ENV['FILE_STORAGE_PATH']) || $_ENV['FILE_STORAGE_PATH'] === '') {
$storagePath = $basePath . '/storage';
} else {
$storagePath = $_ENV['FILE_STORAGE_PATH'];
}

$counterRepository = new CounterFileRepository($storagePath);
break;
default:
throw new \Exception(
"Unsupported repository `$repositoryType`",
);
}
$counterRepository = (new CounterRepositoryFactory())->create($appBasePath);

$username = new Username($username);

if (strpos($httpUserAgent, 'github-camo') === 0) {
if ($isGitHubUserAgent) {
$counterRepository->addViewByUsername($username);
}

if ($badgeStyle === 'pixel') {
echo $badgeImageRenderer->renderPixel();
exit;
} else {
$count = $counterRepository->getViewsCountByUsername($username);

echo $badgeImageRenderer->renderBadgeWithCount(
$badgeLabel,
$count,
$badgeMessageBackgroundFill,
$badgeStyle,
);
}

$count = $counterRepository->getViewsCountByUsername($username);

echo $badgeImageRenderer->renderBadgeWithCount(
$badgeLabel,
$count,
$badgeMessageBackgroundFill,
$badgeStyle,
);
exit;
} catch (InvalidPathException $exception) {
echo $badgeImageRenderer->renderBadgeWithError(
$badgeLabel,
'Application environment file is missing',
$badgeStyle,
);
exit;
} catch (Exception $exception) {
echo $badgeImageRenderer->renderBadgeWithError(
$badgeLabel,
$exception->getMessage(),
$badgeStyle,
);
exit;
}
78 changes: 78 additions & 0 deletions src/CounterRepositoryFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php

/*
* This file is part of GitHub Profile Views Counter.
*
* (c) Anton Komarev <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace Komarev\GitHubProfileViewsCounter;

use Contracts\Komarev\GitHubProfileViewsCounter\CounterRepositoryInterface;
use Dotenv\Dotenv;
use PDO;

final class CounterRepositoryFactory
{
public function create(
string $appBasePath
): CounterRepositoryInterface {
$dotEnv = Dotenv::createImmutable($appBasePath);
$env = $dotEnv->load();

$dotEnv->required([
'REPOSITORY',
]);

$repositoryType = $env['REPOSITORY'];

switch ($repositoryType) {
case 'pdo':
$dotEnv->required([
'DB_DRIVER',
'DB_HOST',
'DB_PORT',
'DB_USER',
'DB_PASSWORD',
'DB_NAME',
]);

$dsn = sprintf(
'%s:host=%s;port=%d;dbname=%s',
$env['DB_DRIVER'],
$env['DB_HOST'],
$env['DB_PORT'],
$env['DB_NAME'],
);
$dbConnection = new PDO(
$dsn,
$env['DB_USER'],
$env['DB_PASSWORD'],
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
],
);

return new CounterPdoRepository($dbConnection);
case 'file':
$dotEnv->required([
'FILE_STORAGE_PATH',
]);

$storagePath = $env['FILE_STORAGE_PATH'] !== ''
? $env['FILE_STORAGE_PATH']
: $appBasePath . '/storage';

return new CounterFileRepository($storagePath);
default:
throw new \Exception(
"Unsupported repository `$repositoryType`",
);
}
}
}

0 comments on commit bd9bad0

Please sign in to comment.