Refactor CounterRepository

This commit is contained in:
antonkomarev
2020-07-12 12:43:51 +03:00
parent b33e9d4fcf
commit bf7b636702
3 changed files with 29 additions and 19 deletions

View File

@@ -15,7 +15,7 @@ namespace Contracts\Komarev\GitHubProfileViewsCounter;
interface CounterRepositoryInterface
{
public function getCount(): int;
public function getCountByUsername(string $username): int;
public function incrementCount(): void;
public function incrementCountByUsername(string $username): void;
}

View File

@@ -23,22 +23,17 @@ require $basePath . '/vendor/autoload.php';
$username = $_GET['username'] ?? '';
$username = trim($username);
if ($username === '') {
$counterFileName = 'views-count';
} else {
$counterFileName = $username . '-views-count';
}
try {
$counterRepository = new CounterFileRepository($storagePath, $counterFileName);
$counterRepository = new CounterFileRepository($storagePath);
$counterImageRenderer = new CounterImageRendererService($counterSourceImagePath);
$counterRepository->incrementCountByUsername($username);
$count = $counterRepository->getCountByUsername($username);
header('Content-Type: image/svg+xml');
header('Cache-Control: max-age=0, no-cache, no-store, must-revalidate');
$counterRepository->incrementCount();
echo $counterImageRenderer->getImageWithCount($counterRepository->getCount());
echo $counterImageRenderer->getImageWithCount($count);
} catch (Exception $exception) {
echo $exception->getMessage();
}

View File

@@ -17,20 +17,35 @@ use Contracts\Komarev\GitHubProfileViewsCounter\CounterRepositoryInterface;
final class CounterFileRepository implements CounterRepositoryInterface
{
private string $counterPath;
private string $storagePath;
public function __construct(string $storagePath, string $counterFileName)
public function __construct(string $storagePath)
{
$this->counterPath = $storagePath . '/' . $counterFileName;
$this->storagePath = $storagePath;
}
public function getCount(): int
public function getCountByUsername(string $username): int
{
return file_exists($this->counterPath) ? (int) file_get_contents($this->counterPath) : 0;
$counterFilePath = $this->getCounterFilePath($username);
return file_exists($counterFilePath) ? (int) file_get_contents($counterFilePath) : 0;
}
public function incrementCount(): void
public function incrementCountByUsername(string $username): void
{
file_put_contents($this->counterPath, $this->getCount() + 1);
$counterFilePath = $this->getCounterFilePath($username);
file_put_contents($counterFilePath, $this->getCountByUsername($username) + 1);
}
private function getCounterFilePath(string $username): string
{
if ($username === '') {
$counterFileName = 'views-count';
} else {
$counterFileName = $username . '-views-count';
}
return $this->storagePath . '/' . $counterFileName;
}
}